blob: 4fb7dca9bb04ae094511c851442884afb4493e98 [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
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010078/* SSL error object */
79static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070080static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010081static PyObject *PySSLZeroReturnErrorObject;
82static PyObject *PySSLWantReadErrorObject;
83static PyObject *PySSLWantWriteErrorObject;
84static PyObject *PySSLSyscallErrorObject;
85static PyObject *PySSLEOFErrorObject;
86
87/* Error mappings */
88static PyObject *err_codes_to_names;
89static PyObject *err_names_to_codes;
90static PyObject *lib_codes_to_names;
91
92struct py_ssl_error_code {
93 const char *mnemonic;
94 int library, reason;
95};
96struct py_ssl_library_code {
97 const char *library;
98 int code;
99};
100
Steve Dower68d663c2017-07-17 11:15:48 +0200101#if defined(MS_WINDOWS) && defined(Py_DEBUG)
102/* Debug builds on Windows rely on getting errno directly from OpenSSL.
103 * However, because it uses a different CRT, we need to transfer the
104 * value of errno from OpenSSL into our debug CRT.
105 *
106 * Don't be fooled - this is horribly ugly code. The only reasonable
107 * alternative is to do both debug and release builds of OpenSSL, which
108 * requires much uglier code to transform their automatically generated
109 * makefile. This is the lesser of all the evils.
110 */
111
112static void _PySSLFixErrno(void) {
113 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
114 if (!ucrtbase) {
115 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
116 * have a catastrophic failure, but this function is not the
117 * place to raise it. */
118 return;
119 }
120
121 typedef int *(__stdcall *errno_func)(void);
122 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
123 if (ssl_errno) {
124 errno = *ssl_errno();
125 *ssl_errno() = 0;
126 } else {
127 errno = ENOTRECOVERABLE;
128 }
129}
130
131#undef _PySSL_FIX_ERRNO
132#define _PySSL_FIX_ERRNO _PySSLFixErrno()
133#endif
134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135/* Include generated data (error codes) */
136#include "_ssl_data.h"
137
Christian Heimes598894f2016-09-05 23:19:05 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
139# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100140# define PY_OPENSSL_1_1_API 1
141#endif
142
143/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
144#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
145# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200146#endif
147
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
149 http://www.openssl.org/news/changelog.html
150 */
151#if OPENSSL_VERSION_NUMBER >= 0x10001000L
152# define HAVE_TLSv1_2 1
153#else
154# define HAVE_TLSv1_2 0
155#endif
156
Christian Heimes470fba12013-11-28 15:12:15 +0100157/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100158 * This includes the SSL_set_SSL_CTX() function.
159 */
160#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
161# define HAVE_SNI 1
162#else
163# define HAVE_SNI 0
164#endif
165
Benjamin Petersond3308222015-09-27 00:09:02 -0700166#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Christian Heimes6cdb7952018-02-24 22:12:40 +0100172/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
173 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
174 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
175 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100182#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100183# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100184#else
Christian Heimes29eab552018-02-25 12:31:33 +0100185# define HAVE_NPN 0
186#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100187
Victor Stinner524714e2016-07-22 17:43:59 +0200188#ifndef INVALID_SOCKET /* MS defines this */
189#define INVALID_SOCKET (-1)
190#endif
191
Christian Heimes4ca07392018-03-24 15:41:37 +0100192/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
193#ifndef OPENSSL_VERSION_1_1
194#define HAVE_OPENSSL_CRYPTO_LOCK
195#endif
196
197#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200198#define OPENSSL_NO_SSL2
199#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100200
201#ifndef PY_OPENSSL_1_1_API
202/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200203
204#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200205#define TLS_client_method SSLv23_client_method
206#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
209{
210 return ne->set;
211}
212
213#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200214/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200215static int COMP_get_type(const COMP_METHOD *meth)
216{
217 return meth->type;
218}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200219/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200220#endif
221
222static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
223{
224 return ctx->default_passwd_callback;
225}
226
227static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
228{
229 return ctx->default_passwd_callback_userdata;
230}
231
232static int X509_OBJECT_get_type(X509_OBJECT *x)
233{
234 return x->type;
235}
236
237static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
238{
239 return x->data.x509;
240}
241
242static int BIO_up_ref(BIO *b)
243{
244 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
245 return 1;
246}
247
248static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
249 return store->objs;
250}
251
Christian Heimes99a65702016-09-10 23:44:53 +0200252static int
253SSL_SESSION_has_ticket(const SSL_SESSION *s)
254{
255 return (s->tlsext_ticklen > 0) ? 1 : 0;
256}
257
258static unsigned long
259SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
260{
261 return s->tlsext_tick_lifetime_hint;
262}
263
Christian Heimes4ca07392018-03-24 15:41:37 +0100264#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200265
Christian Heimes892d66e2018-01-29 14:10:18 +0100266/* Default cipher suites */
267#ifndef PY_SSL_DEFAULT_CIPHERS
268#define PY_SSL_DEFAULT_CIPHERS 1
269#endif
270
271#if PY_SSL_DEFAULT_CIPHERS == 0
272 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
273 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
274 #endif
275#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200276/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100277 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
278 * !aNULL:!eNULL: really no NULL ciphers
279 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
280 * !aDSS: no authentication with discrete logarithm DSA algorithm
281 * !SRP:!PSK: no secure remote password or pre-shared key authentication
282 */
283 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
284#elif PY_SSL_DEFAULT_CIPHERS == 2
285/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
286 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
287#else
288 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
289#endif
290
Christian Heimes598894f2016-09-05 23:19:05 +0200291
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000292enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 /* these mirror ssl.h */
294 PY_SSL_ERROR_NONE,
295 PY_SSL_ERROR_SSL,
296 PY_SSL_ERROR_WANT_READ,
297 PY_SSL_ERROR_WANT_WRITE,
298 PY_SSL_ERROR_WANT_X509_LOOKUP,
299 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
300 PY_SSL_ERROR_ZERO_RETURN,
301 PY_SSL_ERROR_WANT_CONNECT,
302 /* start of non ssl.h errorcodes */
303 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
304 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
305 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000306};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000307
Thomas Woutersed03b412007-08-28 21:37:11 +0000308enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 PY_SSL_CLIENT,
310 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000311};
312
313enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 PY_SSL_CERT_NONE,
315 PY_SSL_CERT_OPTIONAL,
316 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000317};
318
319enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200321 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200322 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100323#if HAVE_TLSv1_2
324 PY_SSL_VERSION_TLS1,
325 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200328 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000329#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS_CLIENT=0x10,
331 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100332};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200333
Christian Heimes698dde12018-02-27 11:54:43 +0100334enum py_proto_version {
335 PY_PROTO_MINIMUM_SUPPORTED = -2,
336 PY_PROTO_SSLv3 = SSL3_VERSION,
337 PY_PROTO_TLSv1 = TLS1_VERSION,
338 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
339 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
340#ifdef TLS1_3_VERSION
341 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
342#else
343 PY_PROTO_TLSv1_3 = 0x304,
344#endif
345 PY_PROTO_MAXIMUM_SUPPORTED = -1,
346
347/* OpenSSL has no dedicated API to set the minimum version to the maximum
348 * available version, and the other way around. We have to figure out the
349 * minimum and maximum available version on our own and hope for the best.
350 */
351#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
352 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
353#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
354 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
355#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
357#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
359#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
361#else
362 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
363#endif
364
365#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
366 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
367#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
368 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
369#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
371#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
373#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
375#else
376 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
377#endif
378};
379
380
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000381/* serves as a flag to see whether we've initialized the SSL thread support. */
382/* 0 means no, greater than 0 means yes */
383
384static unsigned int _ssl_locks_count = 0;
385
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386/* SSL socket object */
387
388#define X509_NAME_MAXLEN 256
389
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000390/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
391 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
392 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
393#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000394# define HAVE_SSL_CTX_CLEAR_OPTIONS
395#else
396# undef HAVE_SSL_CTX_CLEAR_OPTIONS
397#endif
398
Antoine Pitroud6494802011-07-21 01:11:30 +0200399/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
400 * older SSL, but let's be safe */
401#define PySSL_CB_MAXLEN 128
402
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100403
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000406 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100407#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500408 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100409 int npn_protocols_len;
410#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100411#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300413 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500414#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100415#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100416 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100417#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100418 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100419 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
420 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
421 */
422 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100423 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200424#ifdef TLS1_3_VERSION
425 int post_handshake_auth;
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 */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200449typedef struct {
450 PyObject_HEAD
451 BIO *bio;
452 int eof_written;
453} PySSLMemoryBIO;
454
Christian Heimes99a65702016-09-10 23:44:53 +0200455typedef struct {
456 PyObject_HEAD
457 SSL_SESSION *session;
458 PySSLContext *ctx;
459} PySSLSession;
460
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461static PyTypeObject PySSLContext_Type;
462static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200463static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200464static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000465
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700466static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
467{
468 _PySSLError err = { 0 };
469 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700470#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700471 err.ws = WSAGetLastError();
472 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700473#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700474 err.c = errno;
475 err.ssl = SSL_get_error(ssl, retcode);
476 }
477 return err;
478}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300480/*[clinic input]
481module _ssl
482class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
483class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
484class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200485class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300486[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200487/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300488
489#include "clinic/_ssl.c.h"
490
Victor Stinner14690702015-04-06 22:46:13 +0200491static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Christian Heimes141c5e82018-02-24 21:10:57 +0100493static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
494static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200496#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200497#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000498
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000499typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 SOCKET_IS_NONBLOCKING,
501 SOCKET_IS_BLOCKING,
502 SOCKET_HAS_TIMED_OUT,
503 SOCKET_HAS_BEEN_CLOSED,
504 SOCKET_TOO_LARGE_FOR_SELECT,
505 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000506} timeout_state;
507
Thomas Woutersed03b412007-08-28 21:37:11 +0000508/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000509#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200510#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000511
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512/* Get the socket from a PySSLSocket, if it has one */
513#define GET_SOCKET(obj) ((obj)->Socket ? \
514 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200515
Victor Stinner14690702015-04-06 22:46:13 +0200516/* If sock is NULL, use a timeout of 0 second */
517#define GET_SOCKET_TIMEOUT(sock) \
518 ((sock != NULL) ? (sock)->sock_timeout : 0)
519
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520/*
521 * SSL errors.
522 */
523
524PyDoc_STRVAR(SSLError_doc,
525"An error occurred in the SSL implementation.");
526
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700527PyDoc_STRVAR(SSLCertVerificationError_doc,
528"A certificate could not be verified.");
529
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200530PyDoc_STRVAR(SSLZeroReturnError_doc,
531"SSL/TLS session closed cleanly.");
532
533PyDoc_STRVAR(SSLWantReadError_doc,
534"Non-blocking SSL socket needs to read more data\n"
535"before the requested operation can be completed.");
536
537PyDoc_STRVAR(SSLWantWriteError_doc,
538"Non-blocking SSL socket needs to write more data\n"
539"before the requested operation can be completed.");
540
541PyDoc_STRVAR(SSLSyscallError_doc,
542"System error when attempting SSL operation.");
543
544PyDoc_STRVAR(SSLEOFError_doc,
545"SSL/TLS connection terminated abruptly.");
546
547static PyObject *
548SSLError_str(PyOSErrorObject *self)
549{
550 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
551 Py_INCREF(self->strerror);
552 return self->strerror;
553 }
554 else
555 return PyObject_Str(self->args);
556}
557
558static PyType_Slot sslerror_type_slots[] = {
559 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900560 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200561 {Py_tp_str, SSLError_str},
562 {0, 0},
563};
564
565static PyType_Spec sslerror_type_spec = {
566 "ssl.SSLError",
567 sizeof(PyOSErrorObject),
568 0,
569 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
570 sslerror_type_slots
571};
572
573static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700574fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
575 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200576{
577 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700578 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 PyObject *init_value, *msg, *key;
580 _Py_IDENTIFIER(reason);
581 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700582 _Py_IDENTIFIER(verify_message);
583 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200584
585 if (errcode != 0) {
586 int lib, reason;
587
588 lib = ERR_GET_LIB(errcode);
589 reason = ERR_GET_REASON(errcode);
590 key = Py_BuildValue("ii", lib, reason);
591 if (key == NULL)
592 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300593 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300595 if (reason_obj == NULL && PyErr_Occurred()) {
596 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 }
598 key = PyLong_FromLong(lib);
599 if (key == NULL)
600 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300601 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200602 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300603 if (lib_obj == NULL && PyErr_Occurred()) {
604 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200605 }
606 if (errstr == NULL)
607 errstr = ERR_reason_error_string(errcode);
608 }
609 if (errstr == NULL)
610 errstr = "unknown error";
611
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700612 /* verify code for cert validation error */
613 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
614 const char *verify_str = NULL;
615 long verify_code;
616
617 verify_code = SSL_get_verify_result(sslsock->ssl);
618 verify_code_obj = PyLong_FromLong(verify_code);
619 if (verify_code_obj == NULL) {
620 goto fail;
621 }
622
623 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700624#ifdef X509_V_ERR_HOSTNAME_MISMATCH
625 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700626 case X509_V_ERR_HOSTNAME_MISMATCH:
627 verify_obj = PyUnicode_FromFormat(
628 "Hostname mismatch, certificate is not valid for '%S'.",
629 sslsock->server_hostname
630 );
631 break;
Christian Heimes09153602017-09-08 14:47:58 -0700632#endif
633#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700634 case X509_V_ERR_IP_ADDRESS_MISMATCH:
635 verify_obj = PyUnicode_FromFormat(
636 "IP address mismatch, certificate is not valid for '%S'.",
637 sslsock->server_hostname
638 );
639 break;
Christian Heimes09153602017-09-08 14:47:58 -0700640#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700641 default:
642 verify_str = X509_verify_cert_error_string(verify_code);
643 if (verify_str != NULL) {
644 verify_obj = PyUnicode_FromString(verify_str);
645 } else {
646 verify_obj = Py_None;
647 Py_INCREF(verify_obj);
648 }
649 break;
650 }
651 if (verify_obj == NULL) {
652 goto fail;
653 }
654 }
655
656 if (verify_obj && reason_obj && lib_obj)
657 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
658 lib_obj, reason_obj, errstr, verify_obj,
659 lineno);
660 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200661 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
662 lib_obj, reason_obj, errstr, lineno);
663 else if (lib_obj)
664 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
665 lib_obj, errstr, lineno);
666 else
667 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200668 if (msg == NULL)
669 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100670
Paul Monsonfb7e7502019-05-15 15:38:55 -0700671 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100672 if (init_value == NULL)
673 goto fail;
674
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200675 err_value = PyObject_CallObject(type, init_value);
676 Py_DECREF(init_value);
677 if (err_value == NULL)
678 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100679
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200680 if (reason_obj == NULL)
681 reason_obj = Py_None;
682 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
683 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700684
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200685 if (lib_obj == NULL)
686 lib_obj = Py_None;
687 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
688 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700689
690 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
691 /* Only set verify code / message for SSLCertVerificationError */
692 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
693 verify_code_obj))
694 goto fail;
695 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
696 goto fail;
697 }
698
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200699 PyErr_SetObject(type, err_value);
700fail:
701 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700702 Py_XDECREF(verify_code_obj);
703 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200704}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000705
706static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700707PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000708{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200709 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200710 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700711 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200713 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000714
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200716 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000717
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700718 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700719 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000720
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700721 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200723 errstr = "TLS/SSL connection has been closed (EOF)";
724 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000725 p = PY_SSL_ERROR_ZERO_RETURN;
726 break;
727 case SSL_ERROR_WANT_READ:
728 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200729 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000730 p = PY_SSL_ERROR_WANT_READ;
731 break;
732 case SSL_ERROR_WANT_WRITE:
733 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200734 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000735 errstr = "The operation did not complete (write)";
736 break;
737 case SSL_ERROR_WANT_X509_LOOKUP:
738 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000739 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 break;
741 case SSL_ERROR_WANT_CONNECT:
742 p = PY_SSL_ERROR_WANT_CONNECT;
743 errstr = "The operation did not complete (connect)";
744 break;
745 case SSL_ERROR_SYSCALL:
746 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700748 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000750 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200751 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000752 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200753 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000754 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000755 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700756#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700757 if (err.ws) {
758 return PyErr_SetFromWindowsErr(err.ws);
759 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700760#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700761 if (err.c) {
762 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700763 return PyErr_SetFromErrno(PyExc_OSError);
764 }
765 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200766 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000767 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200768 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000770 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200771 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000772 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 }
774 } else {
775 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 }
777 break;
778 }
779 case SSL_ERROR_SSL:
780 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700782 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200783 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700785 }
786 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
787 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
788 type = PySSLCertVerificationErrorObject;
789 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 break;
791 }
792 default:
793 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
794 errstr = "Invalid error code";
795 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000796 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700797 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000798 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000800}
801
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200803_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000804
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200805 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200807 else
808 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700809 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000810 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000812}
813
Christian Heimes61d478c2018-01-27 15:51:38 +0100814/*
815 * SSL objects
816 */
817
818static int
819_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
820{
821 int retval = -1;
822 ASN1_OCTET_STRING *ip;
823 PyObject *hostname;
824 size_t len;
825
826 assert(server_hostname);
827
828 /* Disable OpenSSL's special mode with leading dot in hostname:
829 * When name starts with a dot (e.g ".example.com"), it will be
830 * matched by a certificate valid for any sub-domain of name.
831 */
832 len = strlen(server_hostname);
833 if (len == 0 || *server_hostname == '.') {
834 PyErr_SetString(
835 PyExc_ValueError,
836 "server_hostname cannot be an empty string or start with a "
837 "leading dot.");
838 return retval;
839 }
840
841 /* inet_pton is not available on all platforms. */
842 ip = a2i_IPADDRESS(server_hostname);
843 if (ip == NULL) {
844 ERR_clear_error();
845 }
846
Christian Heimes11a14932018-02-24 02:35:08 +0100847 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100848 if (hostname == NULL) {
849 goto error;
850 }
851 self->server_hostname = hostname;
852
853 /* Only send SNI extension for non-IP hostnames */
854 if (ip == NULL) {
855 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
856 _setSSLError(NULL, 0, __FILE__, __LINE__);
857 }
858 }
859 if (self->ctx->check_hostname) {
860 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
861 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200862 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
863 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100864 _setSSLError(NULL, 0, __FILE__, __LINE__);
865 goto error;
866 }
867 } else {
868 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
869 ASN1_STRING_length(ip))) {
870 _setSSLError(NULL, 0, __FILE__, __LINE__);
871 goto error;
872 }
873 }
874 }
875 retval = 0;
876 error:
877 if (ip != NULL) {
878 ASN1_OCTET_STRING_free(ip);
879 }
880 return retval;
881}
882
Antoine Pitrou152efa22010-05-16 18:19:27 +0000883static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100884newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000885 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200886 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100887 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200888 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000889{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000890 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100891 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700892 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000893
Antoine Pitrou152efa22010-05-16 18:19:27 +0000894 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000895 if (self == NULL)
896 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100900 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700901 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200902 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200903 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700904 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700905 self->err = err;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000911 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700913 if (self->ssl == NULL) {
914 Py_DECREF(self);
915 _setSSLError(NULL, 0, __FILE__, __LINE__);
916 return NULL;
917 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200918 SSL_set_app_data(self->ssl, self);
919 if (sock) {
920 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
921 } else {
922 /* BIOs are reference counted and SSL_set_bio borrows our reference.
923 * To prevent a double free in memory_bio_dealloc() we need to take an
924 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200925 BIO_up_ref(inbio->bio);
926 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200927 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
928 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400929 SSL_set_mode(self->ssl,
930 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000931
Christian Heimes61d478c2018-01-27 15:51:38 +0100932 if (server_hostname != NULL) {
933 if (_ssl_configure_hostname(self, server_hostname) < 0) {
934 Py_DECREF(self);
935 return NULL;
936 }
937 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 /* If the socket is in non-blocking mode or timeout mode, set the BIO
939 * to non-blocking mode (blocking is the default)
940 */
Victor Stinnere2452312015-03-28 03:00:46 +0100941 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
943 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
944 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 PySSL_BEGIN_ALLOW_THREADS
947 if (socket_type == PY_SSL_CLIENT)
948 SSL_set_connect_state(self->ssl);
949 else
950 SSL_set_accept_state(self->ssl);
951 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000952
Antoine Pitroud6494802011-07-21 01:11:30 +0200953 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200954 if (sock != NULL) {
955 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
956 if (self->Socket == NULL) {
957 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200958 return NULL;
959 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100960 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100961 if (owner && owner != Py_None) {
962 if (PySSL_set_owner(self, owner, NULL) == -1) {
963 Py_DECREF(self);
964 return NULL;
965 }
966 }
967 if (session && session != Py_None) {
968 if (PySSL_set_session(self, session, NULL) == -1) {
969 Py_DECREF(self);
970 return NULL;
971 }
972 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000974}
975
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000976/* SSL object methods */
977
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300978/*[clinic input]
979_ssl._SSLSocket.do_handshake
980[clinic start generated code]*/
981
982static PyObject *
983_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
984/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000985{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000986 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700987 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200989 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200990 _PyTime_t timeout, deadline = 0;
991 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000992
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200993 if (sock) {
994 if (((PyObject*)sock) == Py_None) {
995 _setSSLError("Underlying socket connection gone",
996 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
997 return NULL;
998 }
999 Py_INCREF(sock);
1000
1001 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001002 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001003 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1004 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001006
Victor Stinner14690702015-04-06 22:46:13 +02001007 timeout = GET_SOCKET_TIMEOUT(sock);
1008 has_timeout = (timeout > 0);
1009 if (has_timeout)
1010 deadline = _PyTime_GetMonotonicClock() + timeout;
1011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 /* Actually negotiate SSL connection */
1013 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001015 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001017 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001019 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001020
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001021 if (PyErr_CheckSignals())
1022 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001023
Victor Stinner14690702015-04-06 22:46:13 +02001024 if (has_timeout)
1025 timeout = deadline - _PyTime_GetMonotonicClock();
1026
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001027 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001028 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001029 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001030 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 } else {
1032 sockstate = SOCKET_OPERATION_OK;
1033 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001034
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001035 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001036 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001037 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001038 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1040 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001041 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001042 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1044 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001045 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001046 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1048 break;
1049 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001050 } while (err.ssl == SSL_ERROR_WANT_READ ||
1051 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001052 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001053 if (ret < 1)
1054 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001055
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001056 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001057
1058error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001059 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001060 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001061}
1062
Thomas Woutersed03b412007-08-28 21:37:11 +00001063static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001064_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1065{
1066 char buf[X509_NAME_MAXLEN];
1067 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001069 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001070
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001071 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 if (buflen < 0) {
1073 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001074 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001076 /* initial buffer is too small for oid + terminating null byte */
1077 if (buflen > X509_NAME_MAXLEN - 1) {
1078 /* make OBJ_obj2txt() calculate the required buflen */
1079 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1080 /* allocate len + 1 for terminating NULL byte */
1081 namebuf = PyMem_Malloc(buflen + 1);
1082 if (namebuf == NULL) {
1083 PyErr_NoMemory();
1084 return NULL;
1085 }
1086 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1087 if (buflen < 0) {
1088 _setSSLError(NULL, 0, __FILE__, __LINE__);
1089 goto done;
1090 }
1091 }
1092 if (!buflen && no_name) {
1093 Py_INCREF(Py_None);
1094 name_obj = Py_None;
1095 }
1096 else {
1097 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1098 }
1099
1100 done:
1101 if (buf != namebuf) {
1102 PyMem_Free(namebuf);
1103 }
1104 return name_obj;
1105}
1106
1107static PyObject *
1108_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1109{
1110 Py_ssize_t buflen;
1111 unsigned char *valuebuf = NULL;
1112 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1115 if (buflen < 0) {
1116 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001117 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001119 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001122}
1123
1124static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001126{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1128 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1129 PyObject *rdnt;
1130 PyObject *attr = NULL; /* tuple to hold an attribute */
1131 int entry_count = X509_NAME_entry_count(xname);
1132 X509_NAME_ENTRY *entry;
1133 ASN1_OBJECT *name;
1134 ASN1_STRING *value;
1135 int index_counter;
1136 int rdn_level = -1;
1137 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 dn = PyList_New(0);
1140 if (dn == NULL)
1141 return NULL;
1142 /* now create another tuple to hold the top-level RDN */
1143 rdn = PyList_New(0);
1144 if (rdn == NULL)
1145 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 for (index_counter = 0;
1148 index_counter < entry_count;
1149 index_counter++)
1150 {
1151 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 /* check to see if we've gotten to a new RDN */
1154 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001155 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 /* yes, new RDN */
1157 /* add old RDN to DN */
1158 rdnt = PyList_AsTuple(rdn);
1159 Py_DECREF(rdn);
1160 if (rdnt == NULL)
1161 goto fail0;
1162 retcode = PyList_Append(dn, rdnt);
1163 Py_DECREF(rdnt);
1164 if (retcode < 0)
1165 goto fail0;
1166 /* create new RDN */
1167 rdn = PyList_New(0);
1168 if (rdn == NULL)
1169 goto fail0;
1170 }
1171 }
Christian Heimes598894f2016-09-05 23:19:05 +02001172 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 /* now add this attribute to the current RDN */
1175 name = X509_NAME_ENTRY_get_object(entry);
1176 value = X509_NAME_ENTRY_get_data(entry);
1177 attr = _create_tuple_for_attribute(name, value);
1178 /*
1179 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1180 entry->set,
1181 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1182 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1183 */
1184 if (attr == NULL)
1185 goto fail1;
1186 retcode = PyList_Append(rdn, attr);
1187 Py_DECREF(attr);
1188 if (retcode < 0)
1189 goto fail1;
1190 }
1191 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001192 if (rdn != NULL) {
1193 if (PyList_GET_SIZE(rdn) > 0) {
1194 rdnt = PyList_AsTuple(rdn);
1195 Py_DECREF(rdn);
1196 if (rdnt == NULL)
1197 goto fail0;
1198 retcode = PyList_Append(dn, rdnt);
1199 Py_DECREF(rdnt);
1200 if (retcode < 0)
1201 goto fail0;
1202 }
1203 else {
1204 Py_DECREF(rdn);
1205 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 /* convert list to tuple */
1209 rdnt = PyList_AsTuple(dn);
1210 Py_DECREF(dn);
1211 if (rdnt == NULL)
1212 return NULL;
1213 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001214
1215 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001216 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001217
1218 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 Py_XDECREF(dn);
1220 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221}
1222
1223static PyObject *
1224_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 /* this code follows the procedure outlined in
1227 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1228 function to extract the STACK_OF(GENERAL_NAME),
1229 then iterates through the stack to add the
1230 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001231
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001232 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001234 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 GENERAL_NAMES *names = NULL;
1236 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 BIO *biobuf = NULL;
1238 char buf[2048];
1239 char *vptr;
1240 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 if (certificate == NULL)
1243 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001244
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 /* get a memory buffer */
1246 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001247 if (biobuf == NULL) {
1248 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1249 return NULL;
1250 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001252 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1253 certificate, NID_subject_alt_name, NULL, NULL);
1254 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 if (peer_alt_names == Py_None) {
1256 peer_alt_names = PyList_New(0);
1257 if (peer_alt_names == NULL)
1258 goto fail;
1259 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001263 int gntype;
1264 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001267 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001268 switch (gntype) {
1269 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 /* we special-case DirName as a tuple of
1271 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 t = PyTuple_New(2);
1274 if (t == NULL) {
1275 goto fail;
1276 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 v = PyUnicode_FromString("DirName");
1279 if (v == NULL) {
1280 Py_DECREF(t);
1281 goto fail;
1282 }
1283 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 v = _create_tuple_for_X509_NAME (name->d.dirn);
1286 if (v == NULL) {
1287 Py_DECREF(t);
1288 goto fail;
1289 }
1290 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001291 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001292
Christian Heimes824f7f32013-08-17 00:54:47 +02001293 case GEN_EMAIL:
1294 case GEN_DNS:
1295 case GEN_URI:
1296 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1297 correctly, CVE-2013-4238 */
1298 t = PyTuple_New(2);
1299 if (t == NULL)
1300 goto fail;
1301 switch (gntype) {
1302 case GEN_EMAIL:
1303 v = PyUnicode_FromString("email");
1304 as = name->d.rfc822Name;
1305 break;
1306 case GEN_DNS:
1307 v = PyUnicode_FromString("DNS");
1308 as = name->d.dNSName;
1309 break;
1310 case GEN_URI:
1311 v = PyUnicode_FromString("URI");
1312 as = name->d.uniformResourceIdentifier;
1313 break;
1314 }
1315 if (v == NULL) {
1316 Py_DECREF(t);
1317 goto fail;
1318 }
1319 PyTuple_SET_ITEM(t, 0, v);
1320 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1321 ASN1_STRING_length(as));
1322 if (v == NULL) {
1323 Py_DECREF(t);
1324 goto fail;
1325 }
1326 PyTuple_SET_ITEM(t, 1, v);
1327 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328
Christian Heimes1c03abd2016-09-06 23:25:35 +02001329 case GEN_RID:
1330 t = PyTuple_New(2);
1331 if (t == NULL)
1332 goto fail;
1333
1334 v = PyUnicode_FromString("Registered ID");
1335 if (v == NULL) {
1336 Py_DECREF(t);
1337 goto fail;
1338 }
1339 PyTuple_SET_ITEM(t, 0, v);
1340
1341 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1342 if (len < 0) {
1343 Py_DECREF(t);
1344 _setSSLError(NULL, 0, __FILE__, __LINE__);
1345 goto fail;
1346 } else if (len >= (int)sizeof(buf)) {
1347 v = PyUnicode_FromString("<INVALID>");
1348 } else {
1349 v = PyUnicode_FromStringAndSize(buf, len);
1350 }
1351 if (v == NULL) {
1352 Py_DECREF(t);
1353 goto fail;
1354 }
1355 PyTuple_SET_ITEM(t, 1, v);
1356 break;
1357
Christian Heimes824f7f32013-08-17 00:54:47 +02001358 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001360 switch (gntype) {
1361 /* check for new general name type */
1362 case GEN_OTHERNAME:
1363 case GEN_X400:
1364 case GEN_EDIPARTY:
1365 case GEN_IPADD:
1366 case GEN_RID:
1367 break;
1368 default:
1369 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1370 "Unknown general name type %d",
1371 gntype) == -1) {
1372 goto fail;
1373 }
1374 break;
1375 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 (void) BIO_reset(biobuf);
1377 GENERAL_NAME_print(biobuf, name);
1378 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1379 if (len < 0) {
1380 _setSSLError(NULL, 0, __FILE__, __LINE__);
1381 goto fail;
1382 }
1383 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001384 if (vptr == NULL) {
1385 PyErr_Format(PyExc_ValueError,
1386 "Invalid value %.200s",
1387 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001388 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001389 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 t = PyTuple_New(2);
1391 if (t == NULL)
1392 goto fail;
1393 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1394 if (v == NULL) {
1395 Py_DECREF(t);
1396 goto fail;
1397 }
1398 PyTuple_SET_ITEM(t, 0, v);
1399 v = PyUnicode_FromStringAndSize((vptr + 1),
1400 (len - (vptr - buf + 1)));
1401 if (v == NULL) {
1402 Py_DECREF(t);
1403 goto fail;
1404 }
1405 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001406 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 if (PyList_Append(peer_alt_names, t) < 0) {
1412 Py_DECREF(t);
1413 goto fail;
1414 }
1415 Py_DECREF(t);
1416 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001417 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 }
1419 BIO_free(biobuf);
1420 if (peer_alt_names != Py_None) {
1421 v = PyList_AsTuple(peer_alt_names);
1422 Py_DECREF(peer_alt_names);
1423 return v;
1424 } else {
1425 return peer_alt_names;
1426 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001427
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428
1429 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 if (biobuf != NULL)
1431 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001433 if (peer_alt_names != Py_None) {
1434 Py_XDECREF(peer_alt_names);
1435 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001437 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001438}
1439
1440static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001441_get_aia_uri(X509 *certificate, int nid) {
1442 PyObject *lst = NULL, *ostr = NULL;
1443 int i, result;
1444 AUTHORITY_INFO_ACCESS *info;
1445
1446 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001447 if (info == NULL)
1448 return Py_None;
1449 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1450 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001451 return Py_None;
1452 }
1453
1454 if ((lst = PyList_New(0)) == NULL) {
1455 goto fail;
1456 }
1457
1458 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1459 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1460 ASN1_IA5STRING *uri;
1461
1462 if ((OBJ_obj2nid(ad->method) != nid) ||
1463 (ad->location->type != GEN_URI)) {
1464 continue;
1465 }
1466 uri = ad->location->d.uniformResourceIdentifier;
1467 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1468 uri->length);
1469 if (ostr == NULL) {
1470 goto fail;
1471 }
1472 result = PyList_Append(lst, ostr);
1473 Py_DECREF(ostr);
1474 if (result < 0) {
1475 goto fail;
1476 }
1477 }
1478 AUTHORITY_INFO_ACCESS_free(info);
1479
1480 /* convert to tuple or None */
1481 if (PyList_Size(lst) == 0) {
1482 Py_DECREF(lst);
1483 return Py_None;
1484 } else {
1485 PyObject *tup;
1486 tup = PyList_AsTuple(lst);
1487 Py_DECREF(lst);
1488 return tup;
1489 }
1490
1491 fail:
1492 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001493 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001494 return NULL;
1495}
1496
1497static PyObject *
1498_get_crl_dp(X509 *certificate) {
1499 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001500 int i, j;
1501 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001502
Christian Heimes598894f2016-09-05 23:19:05 +02001503 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001504
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001505 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001506 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001507
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001508 lst = PyList_New(0);
1509 if (lst == NULL)
1510 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001511
1512 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1513 DIST_POINT *dp;
1514 STACK_OF(GENERAL_NAME) *gns;
1515
1516 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001517 if (dp->distpoint == NULL) {
1518 /* Ignore empty DP value, CVE-2019-5010 */
1519 continue;
1520 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001521 gns = dp->distpoint->name.fullname;
1522
1523 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1524 GENERAL_NAME *gn;
1525 ASN1_IA5STRING *uri;
1526 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001527 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001528
1529 gn = sk_GENERAL_NAME_value(gns, j);
1530 if (gn->type != GEN_URI) {
1531 continue;
1532 }
1533 uri = gn->d.uniformResourceIdentifier;
1534 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1535 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001536 if (ouri == NULL)
1537 goto done;
1538
1539 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001540 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001541 if (err < 0)
1542 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001543 }
1544 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001545
1546 /* Convert to tuple. */
1547 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1548
1549 done:
1550 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001551 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001552 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001553}
1554
1555static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001556_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 PyObject *retval = NULL;
1559 BIO *biobuf = NULL;
1560 PyObject *peer;
1561 PyObject *peer_alt_names = NULL;
1562 PyObject *issuer;
1563 PyObject *version;
1564 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001565 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 ASN1_INTEGER *serialNumber;
1567 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001568 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 ASN1_TIME *notBefore, *notAfter;
1570 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001572 retval = PyDict_New();
1573 if (retval == NULL)
1574 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 peer = _create_tuple_for_X509_NAME(
1577 X509_get_subject_name(certificate));
1578 if (peer == NULL)
1579 goto fail0;
1580 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1581 Py_DECREF(peer);
1582 goto fail0;
1583 }
1584 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001585
Antoine Pitroufb046912010-11-09 20:21:19 +00001586 issuer = _create_tuple_for_X509_NAME(
1587 X509_get_issuer_name(certificate));
1588 if (issuer == NULL)
1589 goto fail0;
1590 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001591 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001592 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001594 Py_DECREF(issuer);
1595
1596 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001597 if (version == NULL)
1598 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001599 if (PyDict_SetItemString(retval, "version", version) < 0) {
1600 Py_DECREF(version);
1601 goto fail0;
1602 }
1603 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 /* get a memory buffer */
1606 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001607 if (biobuf == NULL) {
1608 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1609 goto fail0;
1610 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001611
Antoine Pitroufb046912010-11-09 20:21:19 +00001612 (void) BIO_reset(biobuf);
1613 serialNumber = X509_get_serialNumber(certificate);
1614 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1615 i2a_ASN1_INTEGER(biobuf, serialNumber);
1616 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1617 if (len < 0) {
1618 _setSSLError(NULL, 0, __FILE__, __LINE__);
1619 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001621 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1622 if (sn_obj == NULL)
1623 goto fail1;
1624 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1625 Py_DECREF(sn_obj);
1626 goto fail1;
1627 }
1628 Py_DECREF(sn_obj);
1629
1630 (void) BIO_reset(biobuf);
1631 notBefore = X509_get_notBefore(certificate);
1632 ASN1_TIME_print(biobuf, notBefore);
1633 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1634 if (len < 0) {
1635 _setSSLError(NULL, 0, __FILE__, __LINE__);
1636 goto fail1;
1637 }
1638 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1639 if (pnotBefore == NULL)
1640 goto fail1;
1641 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1642 Py_DECREF(pnotBefore);
1643 goto fail1;
1644 }
1645 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 (void) BIO_reset(biobuf);
1648 notAfter = X509_get_notAfter(certificate);
1649 ASN1_TIME_print(biobuf, notAfter);
1650 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1651 if (len < 0) {
1652 _setSSLError(NULL, 0, __FILE__, __LINE__);
1653 goto fail1;
1654 }
1655 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1656 if (pnotAfter == NULL)
1657 goto fail1;
1658 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1659 Py_DECREF(pnotAfter);
1660 goto fail1;
1661 }
1662 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 peer_alt_names = _get_peer_alt_names(certificate);
1667 if (peer_alt_names == NULL)
1668 goto fail1;
1669 else if (peer_alt_names != Py_None) {
1670 if (PyDict_SetItemString(retval, "subjectAltName",
1671 peer_alt_names) < 0) {
1672 Py_DECREF(peer_alt_names);
1673 goto fail1;
1674 }
1675 Py_DECREF(peer_alt_names);
1676 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001677
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001678 /* Authority Information Access: OCSP URIs */
1679 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1680 if (obj == NULL) {
1681 goto fail1;
1682 } else if (obj != Py_None) {
1683 result = PyDict_SetItemString(retval, "OCSP", obj);
1684 Py_DECREF(obj);
1685 if (result < 0) {
1686 goto fail1;
1687 }
1688 }
1689
1690 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1691 if (obj == NULL) {
1692 goto fail1;
1693 } else if (obj != Py_None) {
1694 result = PyDict_SetItemString(retval, "caIssuers", obj);
1695 Py_DECREF(obj);
1696 if (result < 0) {
1697 goto fail1;
1698 }
1699 }
1700
1701 /* CDP (CRL distribution points) */
1702 obj = _get_crl_dp(certificate);
1703 if (obj == NULL) {
1704 goto fail1;
1705 } else if (obj != Py_None) {
1706 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1707 Py_DECREF(obj);
1708 if (result < 0) {
1709 goto fail1;
1710 }
1711 }
1712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 BIO_free(biobuf);
1714 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001715
1716 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001717 if (biobuf != NULL)
1718 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001719 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 Py_XDECREF(retval);
1721 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001722}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001723
Christian Heimes9a5395a2013-06-17 15:44:12 +02001724static PyObject *
1725_certificate_to_der(X509 *certificate)
1726{
1727 unsigned char *bytes_buf = NULL;
1728 int len;
1729 PyObject *retval;
1730
1731 bytes_buf = NULL;
1732 len = i2d_X509(certificate, &bytes_buf);
1733 if (len < 0) {
1734 _setSSLError(NULL, 0, __FILE__, __LINE__);
1735 return NULL;
1736 }
1737 /* this is actually an immutable bytes sequence */
1738 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1739 OPENSSL_free(bytes_buf);
1740 return retval;
1741}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001743/*[clinic input]
1744_ssl._test_decode_cert
1745 path: object(converter="PyUnicode_FSConverter")
1746 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001748[clinic start generated code]*/
1749
1750static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001751_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1752/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001753{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001754 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 X509 *x=NULL;
1756 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001757
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001758 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1759 PyErr_SetString(PySSLErrorObject,
1760 "Can't malloc memory to read file");
1761 goto fail0;
1762 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001764 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 PyErr_SetString(PySSLErrorObject,
1766 "Can't open file");
1767 goto fail0;
1768 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1771 if (x == NULL) {
1772 PyErr_SetString(PySSLErrorObject,
1773 "Error decoding PEM-encoded file");
1774 goto fail0;
1775 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001776
Antoine Pitroufb046912010-11-09 20:21:19 +00001777 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001778 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001779
1780 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001781 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001782 if (cert != NULL) BIO_free(cert);
1783 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001784}
1785
1786
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001787/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001788_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001789 der as binary_mode: bool = False
1790 /
1791
1792Returns the certificate for the peer.
1793
1794If no certificate was provided, returns None. If a certificate was
1795provided, but not validated, returns an empty dictionary. Otherwise
1796returns a dict containing information about the peer certificate.
1797
1798If the optional argument is True, returns a DER-encoded copy of the
1799peer certificate, or None if no certificate was provided. This will
1800return the certificate even if it wasn't validated.
1801[clinic start generated code]*/
1802
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001804_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1805/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001806{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 X509 *peer_cert;
1809 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001810
Christian Heimes66dc33b2017-05-23 16:02:02 -07001811 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001812 PyErr_SetString(PyExc_ValueError,
1813 "handshake not done yet");
1814 return NULL;
1815 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001816 peer_cert = SSL_get_peer_certificate(self->ssl);
1817 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001819
Antoine Pitrou721738f2012-08-15 23:20:39 +02001820 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001822 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001824 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001826 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001828 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001830 X509_free(peer_cert);
1831 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001832}
1833
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001834static PyObject *
1835cipher_to_tuple(const SSL_CIPHER *cipher)
1836{
1837 const char *cipher_name, *cipher_protocol;
1838 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 if (retval == NULL)
1840 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001841
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001842 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001844 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 PyTuple_SET_ITEM(retval, 0, Py_None);
1846 } else {
1847 v = PyUnicode_FromString(cipher_name);
1848 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001849 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 PyTuple_SET_ITEM(retval, 0, v);
1851 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001852
1853 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001855 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 PyTuple_SET_ITEM(retval, 1, Py_None);
1857 } else {
1858 v = PyUnicode_FromString(cipher_protocol);
1859 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001860 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 PyTuple_SET_ITEM(retval, 1, v);
1862 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001863
1864 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001866 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001868
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001870
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001871 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001872 Py_DECREF(retval);
1873 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001874}
1875
Christian Heimes25bfcd52016-09-06 00:04:45 +02001876#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1877static PyObject *
1878cipher_to_dict(const SSL_CIPHER *cipher)
1879{
1880 const char *cipher_name, *cipher_protocol;
1881
1882 unsigned long cipher_id;
1883 int alg_bits, strength_bits, len;
1884 char buf[512] = {0};
1885#if OPENSSL_VERSION_1_1
1886 int aead, nid;
1887 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1888#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001889
1890 /* can be NULL */
1891 cipher_name = SSL_CIPHER_get_name(cipher);
1892 cipher_protocol = SSL_CIPHER_get_version(cipher);
1893 cipher_id = SSL_CIPHER_get_id(cipher);
1894 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001895 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1896 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001897 if (len > 1 && buf[len-1] == '\n')
1898 buf[len-1] = '\0';
1899 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1900
1901#if OPENSSL_VERSION_1_1
1902 aead = SSL_CIPHER_is_aead(cipher);
1903 nid = SSL_CIPHER_get_cipher_nid(cipher);
1904 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1905 nid = SSL_CIPHER_get_digest_nid(cipher);
1906 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1907 nid = SSL_CIPHER_get_kx_nid(cipher);
1908 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1909 nid = SSL_CIPHER_get_auth_nid(cipher);
1910 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1911#endif
1912
Victor Stinner410b9882016-09-12 12:00:23 +02001913 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001914 "{sksssssssisi"
1915#if OPENSSL_VERSION_1_1
1916 "sOssssssss"
1917#endif
1918 "}",
1919 "id", cipher_id,
1920 "name", cipher_name,
1921 "protocol", cipher_protocol,
1922 "description", buf,
1923 "strength_bits", strength_bits,
1924 "alg_bits", alg_bits
1925#if OPENSSL_VERSION_1_1
1926 ,"aead", aead ? Py_True : Py_False,
1927 "symmetric", skcipher,
1928 "digest", digest,
1929 "kea", kx,
1930 "auth", auth
1931#endif
1932 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001933}
1934#endif
1935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001936/*[clinic input]
1937_ssl._SSLSocket.shared_ciphers
1938[clinic start generated code]*/
1939
1940static PyObject *
1941_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1942/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001943{
1944 STACK_OF(SSL_CIPHER) *ciphers;
1945 int i;
1946 PyObject *res;
1947
Christian Heimes598894f2016-09-05 23:19:05 +02001948 ciphers = SSL_get_ciphers(self->ssl);
1949 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001950 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001951 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1952 if (!res)
1953 return NULL;
1954 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1955 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1956 if (!tup) {
1957 Py_DECREF(res);
1958 return NULL;
1959 }
1960 PyList_SET_ITEM(res, i, tup);
1961 }
1962 return res;
1963}
1964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001965/*[clinic input]
1966_ssl._SSLSocket.cipher
1967[clinic start generated code]*/
1968
1969static PyObject *
1970_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1971/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001972{
1973 const SSL_CIPHER *current;
1974
1975 if (self->ssl == NULL)
1976 Py_RETURN_NONE;
1977 current = SSL_get_current_cipher(self->ssl);
1978 if (current == NULL)
1979 Py_RETURN_NONE;
1980 return cipher_to_tuple(current);
1981}
1982
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001983/*[clinic input]
1984_ssl._SSLSocket.version
1985[clinic start generated code]*/
1986
1987static PyObject *
1988_ssl__SSLSocket_version_impl(PySSLSocket *self)
1989/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001990{
1991 const char *version;
1992
1993 if (self->ssl == NULL)
1994 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001995 if (!SSL_is_init_finished(self->ssl)) {
1996 /* handshake not finished */
1997 Py_RETURN_NONE;
1998 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001999 version = SSL_get_version(self->ssl);
2000 if (!strcmp(version, "unknown"))
2001 Py_RETURN_NONE;
2002 return PyUnicode_FromString(version);
2003}
2004
Christian Heimes29eab552018-02-25 12:31:33 +01002005#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002006/*[clinic input]
2007_ssl._SSLSocket.selected_npn_protocol
2008[clinic start generated code]*/
2009
2010static PyObject *
2011_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2012/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2013{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002014 const unsigned char *out;
2015 unsigned int outlen;
2016
Victor Stinner4569cd52013-06-23 14:58:43 +02002017 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002018 &out, &outlen);
2019
2020 if (out == NULL)
2021 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002022 return PyUnicode_FromStringAndSize((char *)out, outlen);
2023}
2024#endif
2025
Christian Heimes29eab552018-02-25 12:31:33 +01002026#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002027/*[clinic input]
2028_ssl._SSLSocket.selected_alpn_protocol
2029[clinic start generated code]*/
2030
2031static PyObject *
2032_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2033/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2034{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002035 const unsigned char *out;
2036 unsigned int outlen;
2037
2038 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2039
2040 if (out == NULL)
2041 Py_RETURN_NONE;
2042 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002043}
2044#endif
2045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002046/*[clinic input]
2047_ssl._SSLSocket.compression
2048[clinic start generated code]*/
2049
2050static PyObject *
2051_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2052/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2053{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002054#ifdef OPENSSL_NO_COMP
2055 Py_RETURN_NONE;
2056#else
2057 const COMP_METHOD *comp_method;
2058 const char *short_name;
2059
2060 if (self->ssl == NULL)
2061 Py_RETURN_NONE;
2062 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002063 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002064 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002065 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002066 if (short_name == NULL)
2067 Py_RETURN_NONE;
2068 return PyUnicode_DecodeFSDefault(short_name);
2069#endif
2070}
2071
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002072static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2073 Py_INCREF(self->ctx);
2074 return self->ctx;
2075}
2076
2077static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2078 void *closure) {
2079
2080 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002081#if !HAVE_SNI
2082 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2083 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002084 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002085#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002086 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002087 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002088 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002089#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002090 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002091 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002092 return -1;
2093 }
2094
2095 return 0;
2096}
2097
2098PyDoc_STRVAR(PySSL_set_context_doc,
2099"_setter_context(ctx)\n\
2100\
2101This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002102used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002103on the SSLContext to change the certificate information associated with the\n\
2104SSLSocket before the cryptographic exchange handshake messages\n");
2105
2106
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002107static PyObject *
2108PySSL_get_server_side(PySSLSocket *self, void *c)
2109{
2110 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2111}
2112
2113PyDoc_STRVAR(PySSL_get_server_side_doc,
2114"Whether this is a server-side socket.");
2115
2116static PyObject *
2117PySSL_get_server_hostname(PySSLSocket *self, void *c)
2118{
2119 if (self->server_hostname == NULL)
2120 Py_RETURN_NONE;
2121 Py_INCREF(self->server_hostname);
2122 return self->server_hostname;
2123}
2124
2125PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2126"The currently set server hostname (for SNI).");
2127
2128static PyObject *
2129PySSL_get_owner(PySSLSocket *self, void *c)
2130{
2131 PyObject *owner;
2132
2133 if (self->owner == NULL)
2134 Py_RETURN_NONE;
2135
2136 owner = PyWeakref_GetObject(self->owner);
2137 Py_INCREF(owner);
2138 return owner;
2139}
2140
2141static int
2142PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2143{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002144 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002145 if (self->owner == NULL)
2146 return -1;
2147 return 0;
2148}
2149
2150PyDoc_STRVAR(PySSL_get_owner_doc,
2151"The Python-level owner of this object.\
2152Passed as \"self\" in servername callback.");
2153
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002154
Antoine Pitrou152efa22010-05-16 18:19:27 +00002155static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 if (self->ssl)
2158 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002160 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002161 Py_XDECREF(self->server_hostname);
2162 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002164}
2165
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002166/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002167 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002168 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002169 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002170
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002171static int
Victor Stinner14690702015-04-06 22:46:13 +02002172PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002173{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002174 int rc;
2175#ifdef HAVE_POLL
2176 struct pollfd pollfd;
2177 _PyTime_t ms;
2178#else
2179 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 fd_set fds;
2181 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002182#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002183
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002185 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002187 else if (timeout < 0) {
2188 if (s->sock_timeout > 0)
2189 return SOCKET_HAS_TIMED_OUT;
2190 else
2191 return SOCKET_IS_BLOCKING;
2192 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002195 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 /* Prefer poll, if available, since you can poll() any fd
2199 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002200#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002201 pollfd.fd = s->sock_fd;
2202 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002203
Victor Stinner14690702015-04-06 22:46:13 +02002204 /* timeout is in seconds, poll() uses milliseconds */
2205 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002207
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002208 PySSL_BEGIN_ALLOW_THREADS
2209 rc = poll(&pollfd, 1, (int)ms);
2210 PySSL_END_ALLOW_THREADS
2211#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002213 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002215
Victor Stinner14690702015-04-06 22:46:13 +02002216 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002218 FD_ZERO(&fds);
2219 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002220
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002221 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002223 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002225 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002227 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002229#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2232 (when we are able to write or when there's something to read) */
2233 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002234}
2235
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002236/*[clinic input]
2237_ssl._SSLSocket.write
2238 b: Py_buffer
2239 /
2240
2241Writes the bytes-like object b into the SSL object.
2242
2243Returns the number of bytes written.
2244[clinic start generated code]*/
2245
2246static PyObject *
2247_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2248/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002249{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 int len;
2251 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002252 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002254 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002255 _PyTime_t timeout, deadline = 0;
2256 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002257
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002258 if (sock != NULL) {
2259 if (((PyObject*)sock) == Py_None) {
2260 _setSSLError("Underlying socket connection gone",
2261 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2262 return NULL;
2263 }
2264 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 }
2266
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002267 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002268 PyErr_Format(PyExc_OverflowError,
2269 "string longer than %d bytes", INT_MAX);
2270 goto error;
2271 }
2272
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002273 if (sock != NULL) {
2274 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002275 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002276 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2277 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2278 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279
Victor Stinner14690702015-04-06 22:46:13 +02002280 timeout = GET_SOCKET_TIMEOUT(sock);
2281 has_timeout = (timeout > 0);
2282 if (has_timeout)
2283 deadline = _PyTime_GetMonotonicClock() + timeout;
2284
2285 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002287 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 "The write operation timed out");
2289 goto error;
2290 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2291 PyErr_SetString(PySSLErrorObject,
2292 "Underlying socket has been closed.");
2293 goto error;
2294 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2295 PyErr_SetString(PySSLErrorObject,
2296 "Underlying socket too large for select().");
2297 goto error;
2298 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002302 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002303 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002305 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002306
2307 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002309
Victor Stinner14690702015-04-06 22:46:13 +02002310 if (has_timeout)
2311 timeout = deadline - _PyTime_GetMonotonicClock();
2312
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002313 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002314 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002315 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002316 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002317 } else {
2318 sockstate = SOCKET_OPERATION_OK;
2319 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002320
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002322 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 "The write operation timed out");
2324 goto error;
2325 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2326 PyErr_SetString(PySSLErrorObject,
2327 "Underlying socket has been closed.");
2328 goto error;
2329 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2330 break;
2331 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002332 } while (err.ssl == SSL_ERROR_WANT_READ ||
2333 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002334
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002335 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 if (len > 0)
2337 return PyLong_FromLong(len);
2338 else
2339 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002340
2341error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002342 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002344}
2345
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002346/*[clinic input]
2347_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002349Returns the number of already decrypted bytes available for read, pending on the connection.
2350[clinic start generated code]*/
2351
2352static PyObject *
2353_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2354/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002355{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002357 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002358
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 PySSL_BEGIN_ALLOW_THREADS
2360 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002361 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002362 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002363 self->err = err;
2364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 if (count < 0)
2366 return PySSL_SetError(self, count, __FILE__, __LINE__);
2367 else
2368 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002369}
2370
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002371/*[clinic input]
2372_ssl._SSLSocket.read
2373 size as len: int
2374 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002375 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002376 ]
2377 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002378
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002379Read up to size bytes from the SSL socket.
2380[clinic start generated code]*/
2381
2382static PyObject *
2383_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2384 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002385/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002386{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002389 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002391 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002393 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002394 _PyTime_t timeout, deadline = 0;
2395 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002396
Martin Panter5503d472016-03-27 05:35:19 +00002397 if (!group_right_1 && len < 0) {
2398 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2399 return NULL;
2400 }
2401
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002402 if (sock != NULL) {
2403 if (((PyObject*)sock) == Py_None) {
2404 _setSSLError("Underlying socket connection gone",
2405 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2406 return NULL;
2407 }
2408 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002409 }
2410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002411 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002412 dest = PyBytes_FromStringAndSize(NULL, len);
2413 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002414 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002415 if (len == 0) {
2416 Py_XDECREF(sock);
2417 return dest;
2418 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002419 mem = PyBytes_AS_STRING(dest);
2420 }
2421 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002422 mem = buffer->buf;
2423 if (len <= 0 || len > buffer->len) {
2424 len = (int) buffer->len;
2425 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002426 PyErr_SetString(PyExc_OverflowError,
2427 "maximum length can't fit in a C 'int'");
2428 goto error;
2429 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002430 if (len == 0) {
2431 count = 0;
2432 goto done;
2433 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002434 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 }
2436
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002437 if (sock != NULL) {
2438 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002439 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002440 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2441 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2442 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443
Victor Stinner14690702015-04-06 22:46:13 +02002444 timeout = GET_SOCKET_TIMEOUT(sock);
2445 has_timeout = (timeout > 0);
2446 if (has_timeout)
2447 deadline = _PyTime_GetMonotonicClock() + timeout;
2448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 PySSL_BEGIN_ALLOW_THREADS
2451 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002452 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002454 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 if (PyErr_CheckSignals())
2457 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002458
Victor Stinner14690702015-04-06 22:46:13 +02002459 if (has_timeout)
2460 timeout = deadline - _PyTime_GetMonotonicClock();
2461
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002462 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002463 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002464 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002465 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002466 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002467 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002468 {
2469 count = 0;
2470 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002472 else
2473 sockstate = SOCKET_OPERATION_OK;
2474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002476 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 "The read operation timed out");
2478 goto error;
2479 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2480 break;
2481 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002482 } while (err.ssl == SSL_ERROR_WANT_READ ||
2483 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002484
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 if (count <= 0) {
2486 PySSL_SetError(self, count, __FILE__, __LINE__);
2487 goto error;
2488 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002489
2490done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002491 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002493 _PyBytes_Resize(&dest, count);
2494 return dest;
2495 }
2496 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 return PyLong_FromLong(count);
2498 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002499
2500error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002501 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002502 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002503 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002505}
2506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002507/*[clinic input]
2508_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002509
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002510Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002511[clinic start generated code]*/
2512
2513static PyObject *
2514_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002515/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002516{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002517 _PySSLError err;
2518 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002520 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002521 _PyTime_t timeout, deadline = 0;
2522 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002523
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002524 if (sock != NULL) {
2525 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002526 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002527 _setSSLError("Underlying socket connection gone",
2528 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2529 return NULL;
2530 }
2531 Py_INCREF(sock);
2532
2533 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002534 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002535 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2536 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002538
Victor Stinner14690702015-04-06 22:46:13 +02002539 timeout = GET_SOCKET_TIMEOUT(sock);
2540 has_timeout = (timeout > 0);
2541 if (has_timeout)
2542 deadline = _PyTime_GetMonotonicClock() + timeout;
2543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002544 while (1) {
2545 PySSL_BEGIN_ALLOW_THREADS
2546 /* Disable read-ahead so that unwrap can work correctly.
2547 * Otherwise OpenSSL might read in too much data,
2548 * eating clear text data that happens to be
2549 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002550 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002551 * function is used and the shutdown_seen_zero != 0
2552 * condition is met.
2553 */
2554 if (self->shutdown_seen_zero)
2555 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002556 ret = SSL_shutdown(self->ssl);
2557 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002559 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002562 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002564 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 /* Don't loop endlessly; instead preserve legacy
2566 behaviour of trying SSL_shutdown() only twice.
2567 This looks necessary for OpenSSL < 0.9.8m */
2568 if (++zeros > 1)
2569 break;
2570 /* Shutdown was sent, now try receiving */
2571 self->shutdown_seen_zero = 1;
2572 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002573 }
2574
Victor Stinner14690702015-04-06 22:46:13 +02002575 if (has_timeout)
2576 timeout = deadline - _PyTime_GetMonotonicClock();
2577
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002579 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002580 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002581 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002582 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002583 else
2584 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002585
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002587 if (err.ssl == SSL_ERROR_WANT_READ)
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 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002591 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002593 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002594 }
2595 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2596 PyErr_SetString(PySSLErrorObject,
2597 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002598 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002599 }
2600 else if (sockstate != SOCKET_OPERATION_OK)
2601 /* Retain the SSL error code */
2602 break;
2603 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002604
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002605 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002606 Py_XDECREF(sock);
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002607 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002608 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002609 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002610 /* It's already INCREF'ed */
2611 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002612 else
2613 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002614
2615error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002616 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002617 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002618}
2619
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002620/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002621_ssl._SSLSocket.get_channel_binding
2622 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002623
Christian Heimes141c5e82018-02-24 21:10:57 +01002624Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002625
Christian Heimes141c5e82018-02-24 21:10:57 +01002626Raise ValueError if the requested `cb_type` is not supported. Return bytes
2627of the data or None if the data is not available (e.g. before the handshake).
2628Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002629[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002630
Antoine Pitroud6494802011-07-21 01:11:30 +02002631static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002632_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2633 const char *cb_type)
2634/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002635{
Antoine Pitroud6494802011-07-21 01:11:30 +02002636 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002637 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002638
Christian Heimes141c5e82018-02-24 21:10:57 +01002639 if (strcmp(cb_type, "tls-unique") == 0) {
2640 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2641 /* if session is resumed XOR we are the client */
2642 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2643 }
2644 else {
2645 /* if a new session XOR we are the server */
2646 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2647 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002648 }
2649 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002650 PyErr_Format(
2651 PyExc_ValueError,
2652 "'%s' channel binding type not implemented",
2653 cb_type
2654 );
2655 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002656 }
2657
2658 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002659 if (len == 0)
2660 Py_RETURN_NONE;
2661
Christian Heimes141c5e82018-02-24 21:10:57 +01002662 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002663}
2664
Christian Heimes9fb051f2018-09-23 08:32:31 +02002665/*[clinic input]
2666_ssl._SSLSocket.verify_client_post_handshake
2667
2668Initiate TLS 1.3 post-handshake authentication
2669[clinic start generated code]*/
2670
2671static PyObject *
2672_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2673/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2674{
2675#ifdef TLS1_3_VERSION
2676 int err = SSL_verify_client_post_handshake(self->ssl);
2677 if (err == 0)
2678 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2679 else
2680 Py_RETURN_NONE;
2681#else
2682 PyErr_SetString(PyExc_NotImplementedError,
2683 "Post-handshake auth is not supported by your "
2684 "OpenSSL version.");
2685 return NULL;
2686#endif
2687}
2688
Christian Heimes99a65702016-09-10 23:44:53 +02002689#ifdef OPENSSL_VERSION_1_1
2690
2691static SSL_SESSION*
2692_ssl_session_dup(SSL_SESSION *session) {
2693 SSL_SESSION *newsession = NULL;
2694 int slen;
2695 unsigned char *senc = NULL, *p;
2696 const unsigned char *const_p;
2697
2698 if (session == NULL) {
2699 PyErr_SetString(PyExc_ValueError, "Invalid session");
2700 goto error;
2701 }
2702
2703 /* get length */
2704 slen = i2d_SSL_SESSION(session, NULL);
2705 if (slen == 0 || slen > 0xFF00) {
2706 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2707 goto error;
2708 }
2709 if ((senc = PyMem_Malloc(slen)) == NULL) {
2710 PyErr_NoMemory();
2711 goto error;
2712 }
2713 p = senc;
2714 if (!i2d_SSL_SESSION(session, &p)) {
2715 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2716 goto error;
2717 }
2718 const_p = senc;
2719 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2720 if (session == NULL) {
2721 goto error;
2722 }
2723 PyMem_Free(senc);
2724 return newsession;
2725 error:
2726 if (senc != NULL) {
2727 PyMem_Free(senc);
2728 }
2729 return NULL;
2730}
2731#endif
2732
2733static PyObject *
2734PySSL_get_session(PySSLSocket *self, void *closure) {
2735 /* get_session can return sessions from a server-side connection,
2736 * it does not check for handshake done or client socket. */
2737 PySSLSession *pysess;
2738 SSL_SESSION *session;
2739
2740#ifdef OPENSSL_VERSION_1_1
2741 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2742 * https://github.com/openssl/openssl/issues/1550 */
2743 session = SSL_get0_session(self->ssl); /* borrowed reference */
2744 if (session == NULL) {
2745 Py_RETURN_NONE;
2746 }
2747 if ((session = _ssl_session_dup(session)) == NULL) {
2748 return NULL;
2749 }
2750#else
2751 session = SSL_get1_session(self->ssl);
2752 if (session == NULL) {
2753 Py_RETURN_NONE;
2754 }
2755#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002756 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002757 if (pysess == NULL) {
2758 SSL_SESSION_free(session);
2759 return NULL;
2760 }
2761
2762 assert(self->ctx);
2763 pysess->ctx = self->ctx;
2764 Py_INCREF(pysess->ctx);
2765 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002766 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002767 return (PyObject *)pysess;
2768}
2769
2770static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2771 void *closure)
2772 {
2773 PySSLSession *pysess;
2774#ifdef OPENSSL_VERSION_1_1
2775 SSL_SESSION *session;
2776#endif
2777 int result;
2778
2779 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002780 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002781 return -1;
2782 }
2783 pysess = (PySSLSession *)value;
2784
2785 if (self->ctx->ctx != pysess->ctx->ctx) {
2786 PyErr_SetString(PyExc_ValueError,
2787 "Session refers to a different SSLContext.");
2788 return -1;
2789 }
2790 if (self->socket_type != PY_SSL_CLIENT) {
2791 PyErr_SetString(PyExc_ValueError,
2792 "Cannot set session for server-side SSLSocket.");
2793 return -1;
2794 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002795 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002796 PyErr_SetString(PyExc_ValueError,
2797 "Cannot set session after handshake.");
2798 return -1;
2799 }
2800#ifdef OPENSSL_VERSION_1_1
2801 /* duplicate session */
2802 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2803 return -1;
2804 }
2805 result = SSL_set_session(self->ssl, session);
2806 /* free duplicate, SSL_set_session() bumps ref count */
2807 SSL_SESSION_free(session);
2808#else
2809 result = SSL_set_session(self->ssl, pysess->session);
2810#endif
2811 if (result == 0) {
2812 _setSSLError(NULL, 0, __FILE__, __LINE__);
2813 return -1;
2814 }
2815 return 0;
2816}
2817
2818PyDoc_STRVAR(PySSL_set_session_doc,
2819"_setter_session(session)\n\
2820\
2821Get / set SSLSession.");
2822
2823static PyObject *
2824PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2825 if (SSL_session_reused(self->ssl)) {
2826 Py_RETURN_TRUE;
2827 } else {
2828 Py_RETURN_FALSE;
2829 }
2830}
2831
2832PyDoc_STRVAR(PySSL_get_session_reused_doc,
2833"Was the client session reused during handshake?");
2834
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002835static PyGetSetDef ssl_getsetlist[] = {
2836 {"context", (getter) PySSL_get_context,
2837 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002838 {"server_side", (getter) PySSL_get_server_side, NULL,
2839 PySSL_get_server_side_doc},
2840 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2841 PySSL_get_server_hostname_doc},
2842 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2843 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002844 {"session", (getter) PySSL_get_session,
2845 (setter) PySSL_set_session, PySSL_set_session_doc},
2846 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2847 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002848 {NULL}, /* sentinel */
2849};
2850
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002851static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002852 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2853 _SSL__SSLSOCKET_WRITE_METHODDEF
2854 _SSL__SSLSOCKET_READ_METHODDEF
2855 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002856 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2857 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002858 _SSL__SSLSOCKET_CIPHER_METHODDEF
2859 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2860 _SSL__SSLSOCKET_VERSION_METHODDEF
2861 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2862 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2863 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2864 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002865 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002866 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002867};
2868
Antoine Pitrou152efa22010-05-16 18:19:27 +00002869static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002870 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002871 "_ssl._SSLSocket", /*tp_name*/
2872 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002873 0, /*tp_itemsize*/
2874 /* methods */
2875 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002876 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002877 0, /*tp_getattr*/
2878 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002879 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002880 0, /*tp_repr*/
2881 0, /*tp_as_number*/
2882 0, /*tp_as_sequence*/
2883 0, /*tp_as_mapping*/
2884 0, /*tp_hash*/
2885 0, /*tp_call*/
2886 0, /*tp_str*/
2887 0, /*tp_getattro*/
2888 0, /*tp_setattro*/
2889 0, /*tp_as_buffer*/
2890 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2891 0, /*tp_doc*/
2892 0, /*tp_traverse*/
2893 0, /*tp_clear*/
2894 0, /*tp_richcompare*/
2895 0, /*tp_weaklistoffset*/
2896 0, /*tp_iter*/
2897 0, /*tp_iternext*/
2898 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002899 0, /*tp_members*/
2900 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002901};
2902
Antoine Pitrou152efa22010-05-16 18:19:27 +00002903
2904/*
2905 * _SSLContext objects
2906 */
2907
Christian Heimes5fe668c2016-09-12 00:01:11 +02002908static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002909_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002910{
2911 int mode;
2912 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2913
2914 switch(n) {
2915 case PY_SSL_CERT_NONE:
2916 mode = SSL_VERIFY_NONE;
2917 break;
2918 case PY_SSL_CERT_OPTIONAL:
2919 mode = SSL_VERIFY_PEER;
2920 break;
2921 case PY_SSL_CERT_REQUIRED:
2922 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2923 break;
2924 default:
2925 PyErr_SetString(PyExc_ValueError,
2926 "invalid value for verify_mode");
2927 return -1;
2928 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02002929#ifdef TLS1_3_VERSION
2930 if (self->post_handshake_auth)
2931 mode |= SSL_VERIFY_POST_HANDSHAKE;
2932#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002933 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002934 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2935 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002936 return 0;
2937}
2938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002939/*[clinic input]
2940@classmethod
2941_ssl._SSLContext.__new__
2942 protocol as proto_version: int
2943 /
2944[clinic start generated code]*/
2945
Antoine Pitrou152efa22010-05-16 18:19:27 +00002946static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002947_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2948/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002950 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002951 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002952 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002953 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002954 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002955#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002956 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002957#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002958
Antoine Pitrou152efa22010-05-16 18:19:27 +00002959 PySSL_BEGIN_ALLOW_THREADS
2960 if (proto_version == PY_SSL_VERSION_TLS1)
2961 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002962#if HAVE_TLSv1_2
2963 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2964 ctx = SSL_CTX_new(TLSv1_1_method());
2965 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2966 ctx = SSL_CTX_new(TLSv1_2_method());
2967#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002968#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002969 else if (proto_version == PY_SSL_VERSION_SSL3)
2970 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002971#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002972#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002973 else if (proto_version == PY_SSL_VERSION_SSL2)
2974 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002975#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002976 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002977 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002978 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2979 ctx = SSL_CTX_new(TLS_client_method());
2980 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2981 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002982 else
2983 proto_version = -1;
2984 PySSL_END_ALLOW_THREADS
2985
2986 if (proto_version == -1) {
2987 PyErr_SetString(PyExc_ValueError,
2988 "invalid protocol version");
2989 return NULL;
2990 }
2991 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002992 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002993 return NULL;
2994 }
2995
2996 assert(type != NULL && type->tp_alloc != NULL);
2997 self = (PySSLContext *) type->tp_alloc(type, 0);
2998 if (self == NULL) {
2999 SSL_CTX_free(ctx);
3000 return NULL;
3001 }
3002 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003003 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003004 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01003005#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003006 self->npn_protocols = NULL;
3007#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003008#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003009 self->alpn_protocols = NULL;
3010#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003011#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003012 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003013#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003014 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003015 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3016 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003017 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003018 Py_DECREF(self);
3019 return NULL;
3020 }
3021 } else {
3022 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003023 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003024 Py_DECREF(self);
3025 return NULL;
3026 }
3027 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003028 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003029 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3030 if (proto_version != PY_SSL_VERSION_SSL2)
3031 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003032 if (proto_version != PY_SSL_VERSION_SSL3)
3033 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003034 /* Minimal security flags for server and client side context.
3035 * Client sockets ignore server-side parameters. */
3036#ifdef SSL_OP_NO_COMPRESSION
3037 options |= SSL_OP_NO_COMPRESSION;
3038#endif
3039#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3040 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3041#endif
3042#ifdef SSL_OP_SINGLE_DH_USE
3043 options |= SSL_OP_SINGLE_DH_USE;
3044#endif
3045#ifdef SSL_OP_SINGLE_ECDH_USE
3046 options |= SSL_OP_SINGLE_ECDH_USE;
3047#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003048 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003049
Semen Zhydenko1295e112017-10-15 21:28:31 +02003050 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003051 * It's far from perfect but gives users a better head start. */
3052 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003053#if PY_SSL_DEFAULT_CIPHERS == 2
3054 /* stick to OpenSSL's default settings */
3055 result = 1;
3056#else
3057 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3058#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003059 } else {
3060 /* SSLv2 needs MD5 */
3061 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3062 }
3063 if (result == 0) {
3064 Py_DECREF(self);
3065 ERR_clear_error();
3066 PyErr_SetString(PySSLErrorObject,
3067 "No cipher can be selected.");
3068 return NULL;
3069 }
3070
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003071#if defined(SSL_MODE_RELEASE_BUFFERS)
3072 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3073 usage for no cost at all. However, don't do this for OpenSSL versions
3074 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3075 2014-0198. I can't find exactly which beta fixed this CVE, so be
3076 conservative and assume it wasn't fixed until release. We do this check
3077 at runtime to avoid problems from the dynamic linker.
3078 See #25672 for more on this. */
3079 libver = SSLeay();
3080 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3081 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3082 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3083 }
3084#endif
3085
3086
Donald Stufft8ae264c2017-03-02 11:45:29 -05003087#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003088 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3089 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003090 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3091 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003092#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003093 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3094#else
3095 {
3096 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3097 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3098 EC_KEY_free(key);
3099 }
3100#endif
3101#endif
3102
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003103#define SID_CTX "Python"
3104 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3105 sizeof(SID_CTX));
3106#undef SID_CTX
3107
Christian Heimes61d478c2018-01-27 15:51:38 +01003108 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003109#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003110 /* Improve trust chain building when cross-signed intermediate
3111 certificates are present. See https://bugs.python.org/issue23476. */
3112 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003113#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003114 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003115
Christian Heimes9fb051f2018-09-23 08:32:31 +02003116#ifdef TLS1_3_VERSION
3117 self->post_handshake_auth = 0;
3118 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3119#endif
3120
Antoine Pitrou152efa22010-05-16 18:19:27 +00003121 return (PyObject *)self;
3122}
3123
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003124static int
3125context_traverse(PySSLContext *self, visitproc visit, void *arg)
3126{
3127#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003128 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003129#endif
3130 return 0;
3131}
3132
3133static int
3134context_clear(PySSLContext *self)
3135{
3136#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003137 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003138#endif
3139 return 0;
3140}
3141
Antoine Pitrou152efa22010-05-16 18:19:27 +00003142static void
3143context_dealloc(PySSLContext *self)
3144{
INADA Naokia6296d32017-08-24 14:55:17 +09003145 /* bpo-31095: UnTrack is needed before calling any callbacks */
3146 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003147 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003148 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003149#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003150 PyMem_FREE(self->npn_protocols);
3151#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003152#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003153 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003154#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003155 Py_TYPE(self)->tp_free(self);
3156}
3157
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003158/*[clinic input]
3159_ssl._SSLContext.set_ciphers
3160 cipherlist: str
3161 /
3162[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003163
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003164static PyObject *
3165_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3166/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3167{
3168 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003169 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003170 /* Clearing the error queue is necessary on some OpenSSL versions,
3171 otherwise the error will be reported again when another SSL call
3172 is done. */
3173 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003174 PyErr_SetString(PySSLErrorObject,
3175 "No cipher can be selected.");
3176 return NULL;
3177 }
3178 Py_RETURN_NONE;
3179}
3180
Christian Heimes25bfcd52016-09-06 00:04:45 +02003181#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3182/*[clinic input]
3183_ssl._SSLContext.get_ciphers
3184[clinic start generated code]*/
3185
3186static PyObject *
3187_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3188/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3189{
3190 SSL *ssl = NULL;
3191 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003192 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003193 int i=0;
3194 PyObject *result = NULL, *dct;
3195
3196 ssl = SSL_new(self->ctx);
3197 if (ssl == NULL) {
3198 _setSSLError(NULL, 0, __FILE__, __LINE__);
3199 goto exit;
3200 }
3201 sk = SSL_get_ciphers(ssl);
3202
3203 result = PyList_New(sk_SSL_CIPHER_num(sk));
3204 if (result == NULL) {
3205 goto exit;
3206 }
3207
3208 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3209 cipher = sk_SSL_CIPHER_value(sk, i);
3210 dct = cipher_to_dict(cipher);
3211 if (dct == NULL) {
3212 Py_CLEAR(result);
3213 goto exit;
3214 }
3215 PyList_SET_ITEM(result, i, dct);
3216 }
3217
3218 exit:
3219 if (ssl != NULL)
3220 SSL_free(ssl);
3221 return result;
3222
3223}
3224#endif
3225
3226
Christian Heimes29eab552018-02-25 12:31:33 +01003227#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003228static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003229do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3230 const unsigned char *server_protocols, unsigned int server_protocols_len,
3231 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003232{
Benjamin Peterson88615022015-01-23 17:30:26 -05003233 int ret;
3234 if (client_protocols == NULL) {
3235 client_protocols = (unsigned char *)"";
3236 client_protocols_len = 0;
3237 }
3238 if (server_protocols == NULL) {
3239 server_protocols = (unsigned char *)"";
3240 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003241 }
3242
Benjamin Peterson88615022015-01-23 17:30:26 -05003243 ret = SSL_select_next_proto(out, outlen,
3244 server_protocols, server_protocols_len,
3245 client_protocols, client_protocols_len);
3246 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3247 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003248
3249 return SSL_TLSEXT_ERR_OK;
3250}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003251#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003252
Christian Heimes29eab552018-02-25 12:31:33 +01003253#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003254/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3255static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003256_advertiseNPN_cb(SSL *s,
3257 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003258 void *args)
3259{
3260 PySSLContext *ssl_ctx = (PySSLContext *) args;
3261
3262 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003263 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003264 *len = 0;
3265 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003266 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003267 *len = ssl_ctx->npn_protocols_len;
3268 }
3269
3270 return SSL_TLSEXT_ERR_OK;
3271}
3272/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3273static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003274_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003275 unsigned char **out, unsigned char *outlen,
3276 const unsigned char *server, unsigned int server_len,
3277 void *args)
3278{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003279 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003280 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003281 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003282}
3283#endif
3284
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003285/*[clinic input]
3286_ssl._SSLContext._set_npn_protocols
3287 protos: Py_buffer
3288 /
3289[clinic start generated code]*/
3290
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003291static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003292_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3293 Py_buffer *protos)
3294/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003295{
Christian Heimes29eab552018-02-25 12:31:33 +01003296#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003297 PyMem_Free(self->npn_protocols);
3298 self->npn_protocols = PyMem_Malloc(protos->len);
3299 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003300 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003301 memcpy(self->npn_protocols, protos->buf, protos->len);
3302 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003303
3304 /* set both server and client callbacks, because the context can
3305 * be used to create both types of sockets */
3306 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3307 _advertiseNPN_cb,
3308 self);
3309 SSL_CTX_set_next_proto_select_cb(self->ctx,
3310 _selectNPN_cb,
3311 self);
3312
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003313 Py_RETURN_NONE;
3314#else
3315 PyErr_SetString(PyExc_NotImplementedError,
3316 "The NPN extension requires OpenSSL 1.0.1 or later.");
3317 return NULL;
3318#endif
3319}
3320
Christian Heimes29eab552018-02-25 12:31:33 +01003321#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003322static int
3323_selectALPN_cb(SSL *s,
3324 const unsigned char **out, unsigned char *outlen,
3325 const unsigned char *client_protocols, unsigned int client_protocols_len,
3326 void *args)
3327{
3328 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003329 return do_protocol_selection(1, (unsigned char **)out, outlen,
3330 ctx->alpn_protocols, ctx->alpn_protocols_len,
3331 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003332}
3333#endif
3334
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003335/*[clinic input]
3336_ssl._SSLContext._set_alpn_protocols
3337 protos: Py_buffer
3338 /
3339[clinic start generated code]*/
3340
Benjamin Petersoncca27322015-01-23 16:35:37 -05003341static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003342_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3343 Py_buffer *protos)
3344/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003345{
Christian Heimes29eab552018-02-25 12:31:33 +01003346#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003347 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003348 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003349 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003350 return NULL;
3351 }
3352
Benjamin Petersoncca27322015-01-23 16:35:37 -05003353 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003354 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003355 if (!self->alpn_protocols)
3356 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003357 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003358 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003359
3360 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3361 return PyErr_NoMemory();
3362 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3363
Benjamin Petersoncca27322015-01-23 16:35:37 -05003364 Py_RETURN_NONE;
3365#else
3366 PyErr_SetString(PyExc_NotImplementedError,
3367 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3368 return NULL;
3369#endif
3370}
3371
Antoine Pitrou152efa22010-05-16 18:19:27 +00003372static PyObject *
3373get_verify_mode(PySSLContext *self, void *c)
3374{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003375 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3376 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3377 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3378 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003379 case SSL_VERIFY_NONE:
3380 return PyLong_FromLong(PY_SSL_CERT_NONE);
3381 case SSL_VERIFY_PEER:
3382 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3383 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3384 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3385 }
3386 PyErr_SetString(PySSLErrorObject,
3387 "invalid return value from SSL_CTX_get_verify_mode");
3388 return NULL;
3389}
3390
3391static int
3392set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3393{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003394 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003395 if (!PyArg_Parse(arg, "i", &n))
3396 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003397 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003398 PyErr_SetString(PyExc_ValueError,
3399 "Cannot set verify_mode to CERT_NONE when "
3400 "check_hostname is enabled.");
3401 return -1;
3402 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003403 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003404}
3405
3406static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003407get_verify_flags(PySSLContext *self, void *c)
3408{
Christian Heimes598894f2016-09-05 23:19:05 +02003409 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003410 unsigned long flags;
3411
Christian Heimes61d478c2018-01-27 15:51:38 +01003412 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003413 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003414 return PyLong_FromUnsignedLong(flags);
3415}
3416
3417static int
3418set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3419{
Christian Heimes598894f2016-09-05 23:19:05 +02003420 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003421 unsigned long new_flags, flags, set, clear;
3422
3423 if (!PyArg_Parse(arg, "k", &new_flags))
3424 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003425 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003426 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003427 clear = flags & ~new_flags;
3428 set = ~flags & new_flags;
3429 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003430 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003431 _setSSLError(NULL, 0, __FILE__, __LINE__);
3432 return -1;
3433 }
3434 }
3435 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003436 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003437 _setSSLError(NULL, 0, __FILE__, __LINE__);
3438 return -1;
3439 }
3440 }
3441 return 0;
3442}
3443
Christian Heimes698dde12018-02-27 11:54:43 +01003444/* Getter and setter for protocol version */
3445#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3446
3447
3448static int
3449set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3450{
3451 long v;
3452 int result;
3453
3454 if (!PyArg_Parse(arg, "l", &v))
3455 return -1;
3456 if (v > INT_MAX) {
3457 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3458 return -1;
3459 }
3460
3461 switch(self->protocol) {
3462 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3463 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3464 case PY_SSL_VERSION_TLS:
3465 break;
3466 default:
3467 PyErr_SetString(
3468 PyExc_ValueError,
3469 "The context's protocol doesn't support modification of "
3470 "highest and lowest version."
3471 );
3472 return -1;
3473 }
3474
3475 if (what == 0) {
3476 switch(v) {
3477 case PY_PROTO_MINIMUM_SUPPORTED:
3478 v = 0;
3479 break;
3480 case PY_PROTO_MAXIMUM_SUPPORTED:
3481 /* Emulate max for set_min_proto_version */
3482 v = PY_PROTO_MAXIMUM_AVAILABLE;
3483 break;
3484 default:
3485 break;
3486 }
3487 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3488 }
3489 else {
3490 switch(v) {
3491 case PY_PROTO_MAXIMUM_SUPPORTED:
3492 v = 0;
3493 break;
3494 case PY_PROTO_MINIMUM_SUPPORTED:
3495 /* Emulate max for set_min_proto_version */
3496 v = PY_PROTO_MINIMUM_AVAILABLE;
3497 break;
3498 default:
3499 break;
3500 }
3501 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3502 }
3503 if (result == 0) {
3504 PyErr_Format(PyExc_ValueError,
3505 "Unsupported protocol version 0x%x", v);
3506 return -1;
3507 }
3508 return 0;
3509}
3510
3511static PyObject *
3512get_minimum_version(PySSLContext *self, void *c)
3513{
3514 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3515 if (v == 0) {
3516 v = PY_PROTO_MINIMUM_SUPPORTED;
3517 }
3518 return PyLong_FromLong(v);
3519}
3520
3521static int
3522set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3523{
3524 return set_min_max_proto_version(self, arg, 0);
3525}
3526
3527static PyObject *
3528get_maximum_version(PySSLContext *self, void *c)
3529{
3530 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3531 if (v == 0) {
3532 v = PY_PROTO_MAXIMUM_SUPPORTED;
3533 }
3534 return PyLong_FromLong(v);
3535}
3536
3537static int
3538set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3539{
3540 return set_min_max_proto_version(self, arg, 1);
3541}
3542#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3543
Christian Heimes22587792013-11-21 23:56:13 +01003544static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003545get_options(PySSLContext *self, void *c)
3546{
3547 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3548}
3549
3550static int
3551set_options(PySSLContext *self, PyObject *arg, void *c)
3552{
3553 long new_opts, opts, set, clear;
3554 if (!PyArg_Parse(arg, "l", &new_opts))
3555 return -1;
3556 opts = SSL_CTX_get_options(self->ctx);
3557 clear = opts & ~new_opts;
3558 set = ~opts & new_opts;
3559 if (clear) {
3560#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3561 SSL_CTX_clear_options(self->ctx, clear);
3562#else
3563 PyErr_SetString(PyExc_ValueError,
3564 "can't clear options before OpenSSL 0.9.8m");
3565 return -1;
3566#endif
3567 }
3568 if (set)
3569 SSL_CTX_set_options(self->ctx, set);
3570 return 0;
3571}
3572
Christian Heimes1aa9a752013-12-02 02:41:19 +01003573static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003574get_host_flags(PySSLContext *self, void *c)
3575{
3576 return PyLong_FromUnsignedLong(self->hostflags);
3577}
3578
3579static int
3580set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3581{
3582 X509_VERIFY_PARAM *param;
3583 unsigned int new_flags = 0;
3584
3585 if (!PyArg_Parse(arg, "I", &new_flags))
3586 return -1;
3587
3588 param = SSL_CTX_get0_param(self->ctx);
3589 self->hostflags = new_flags;
3590 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3591 return 0;
3592}
3593
3594static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003595get_check_hostname(PySSLContext *self, void *c)
3596{
3597 return PyBool_FromLong(self->check_hostname);
3598}
3599
3600static int
3601set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3602{
3603 int check_hostname;
3604 if (!PyArg_Parse(arg, "p", &check_hostname))
3605 return -1;
3606 if (check_hostname &&
3607 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003608 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003609 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003610 return -1;
3611 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003612 }
3613 self->check_hostname = check_hostname;
3614 return 0;
3615}
3616
Christian Heimes11a14932018-02-24 02:35:08 +01003617static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003618get_post_handshake_auth(PySSLContext *self, void *c) {
3619#if TLS1_3_VERSION
3620 return PyBool_FromLong(self->post_handshake_auth);
3621#else
3622 Py_RETURN_NONE;
3623#endif
3624}
3625
3626#if TLS1_3_VERSION
3627static int
3628set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3629 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3630 int mode = SSL_CTX_get_verify_mode(self->ctx);
Zackery Spytz842acaa2018-12-17 07:52:45 -07003631 if (arg == NULL) {
3632 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3633 return -1;
3634 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003635 int pha = PyObject_IsTrue(arg);
3636
3637 if (pha == -1) {
3638 return -1;
3639 }
3640 self->post_handshake_auth = pha;
3641
3642 /* client-side socket setting, ignored by server-side */
3643 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3644
3645 /* server-side socket setting, ignored by client-side */
3646 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3647 if (pha) {
3648 mode |= SSL_VERIFY_POST_HANDSHAKE;
3649 } else {
3650 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3651 }
3652 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3653
3654 return 0;
3655}
3656#endif
3657
3658static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003659get_protocol(PySSLContext *self, void *c) {
3660 return PyLong_FromLong(self->protocol);
3661}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003662
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003663typedef struct {
3664 PyThreadState *thread_state;
3665 PyObject *callable;
3666 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003667 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003668 int error;
3669} _PySSLPasswordInfo;
3670
3671static int
3672_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3673 const char *bad_type_error)
3674{
3675 /* Set the password and size fields of a _PySSLPasswordInfo struct
3676 from a unicode, bytes, or byte array object.
3677 The password field will be dynamically allocated and must be freed
3678 by the caller */
3679 PyObject *password_bytes = NULL;
3680 const char *data = NULL;
3681 Py_ssize_t size;
3682
3683 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003684 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003685 if (!password_bytes) {
3686 goto error;
3687 }
3688 data = PyBytes_AS_STRING(password_bytes);
3689 size = PyBytes_GET_SIZE(password_bytes);
3690 } else if (PyBytes_Check(password)) {
3691 data = PyBytes_AS_STRING(password);
3692 size = PyBytes_GET_SIZE(password);
3693 } else if (PyByteArray_Check(password)) {
3694 data = PyByteArray_AS_STRING(password);
3695 size = PyByteArray_GET_SIZE(password);
3696 } else {
3697 PyErr_SetString(PyExc_TypeError, bad_type_error);
3698 goto error;
3699 }
3700
Victor Stinner9ee02032013-06-23 15:08:23 +02003701 if (size > (Py_ssize_t)INT_MAX) {
3702 PyErr_Format(PyExc_ValueError,
3703 "password cannot be longer than %d bytes", INT_MAX);
3704 goto error;
3705 }
3706
Victor Stinner11ebff22013-07-07 17:07:52 +02003707 PyMem_Free(pw_info->password);
3708 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003709 if (!pw_info->password) {
3710 PyErr_SetString(PyExc_MemoryError,
3711 "unable to allocate password buffer");
3712 goto error;
3713 }
3714 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003715 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003716
3717 Py_XDECREF(password_bytes);
3718 return 1;
3719
3720error:
3721 Py_XDECREF(password_bytes);
3722 return 0;
3723}
3724
3725static int
3726_password_callback(char *buf, int size, int rwflag, void *userdata)
3727{
3728 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3729 PyObject *fn_ret = NULL;
3730
3731 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3732
3733 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003734 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003735 if (!fn_ret) {
3736 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3737 core python API, so we could use it to add a frame here */
3738 goto error;
3739 }
3740
3741 if (!_pwinfo_set(pw_info, fn_ret,
3742 "password callback must return a string")) {
3743 goto error;
3744 }
3745 Py_CLEAR(fn_ret);
3746 }
3747
3748 if (pw_info->size > size) {
3749 PyErr_Format(PyExc_ValueError,
3750 "password cannot be longer than %d bytes", size);
3751 goto error;
3752 }
3753
3754 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3755 memcpy(buf, pw_info->password, pw_info->size);
3756 return pw_info->size;
3757
3758error:
3759 Py_XDECREF(fn_ret);
3760 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3761 pw_info->error = 1;
3762 return -1;
3763}
3764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003765/*[clinic input]
3766_ssl._SSLContext.load_cert_chain
3767 certfile: object
3768 keyfile: object = NULL
3769 password: object = NULL
3770
3771[clinic start generated code]*/
3772
Antoine Pitroub5218772010-05-21 09:56:06 +00003773static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003774_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3775 PyObject *keyfile, PyObject *password)
3776/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003777{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003778 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003779 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3780 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003781 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003782 int r;
3783
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003784 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003785 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003786 if (keyfile == Py_None)
3787 keyfile = NULL;
3788 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003789 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3790 PyErr_SetString(PyExc_TypeError,
3791 "certfile should be a valid filesystem path");
3792 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003793 return NULL;
3794 }
3795 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003796 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3797 PyErr_SetString(PyExc_TypeError,
3798 "keyfile should be a valid filesystem path");
3799 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003800 goto error;
3801 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003802 if (password && password != Py_None) {
3803 if (PyCallable_Check(password)) {
3804 pw_info.callable = password;
3805 } else if (!_pwinfo_set(&pw_info, password,
3806 "password should be a string or callable")) {
3807 goto error;
3808 }
3809 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3810 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3811 }
3812 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003813 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3814 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003815 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003816 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003817 if (pw_info.error) {
3818 ERR_clear_error();
3819 /* the password callback has already set the error information */
3820 }
3821 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003822 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003823 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003824 }
3825 else {
3826 _setSSLError(NULL, 0, __FILE__, __LINE__);
3827 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003828 goto error;
3829 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003830 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003831 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003832 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3833 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003834 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3835 Py_CLEAR(keyfile_bytes);
3836 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003837 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003838 if (pw_info.error) {
3839 ERR_clear_error();
3840 /* the password callback has already set the error information */
3841 }
3842 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003843 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003844 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003845 }
3846 else {
3847 _setSSLError(NULL, 0, __FILE__, __LINE__);
3848 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003849 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003850 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003851 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003852 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003853 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003854 if (r != 1) {
3855 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003856 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003857 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003858 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3859 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003860 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003861 Py_RETURN_NONE;
3862
3863error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003864 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3865 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003866 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003867 Py_XDECREF(keyfile_bytes);
3868 Py_XDECREF(certfile_bytes);
3869 return NULL;
3870}
3871
Christian Heimesefff7062013-11-21 03:35:02 +01003872/* internal helper function, returns -1 on error
3873 */
3874static int
3875_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3876 int filetype)
3877{
3878 BIO *biobuf = NULL;
3879 X509_STORE *store;
3880 int retval = 0, err, loaded = 0;
3881
3882 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3883
3884 if (len <= 0) {
3885 PyErr_SetString(PyExc_ValueError,
3886 "Empty certificate data");
3887 return -1;
3888 } else if (len > INT_MAX) {
3889 PyErr_SetString(PyExc_OverflowError,
3890 "Certificate data is too long.");
3891 return -1;
3892 }
3893
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003894 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003895 if (biobuf == NULL) {
3896 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3897 return -1;
3898 }
3899
3900 store = SSL_CTX_get_cert_store(self->ctx);
3901 assert(store != NULL);
3902
3903 while (1) {
3904 X509 *cert = NULL;
3905 int r;
3906
3907 if (filetype == SSL_FILETYPE_ASN1) {
3908 cert = d2i_X509_bio(biobuf, NULL);
3909 } else {
3910 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003911 SSL_CTX_get_default_passwd_cb(self->ctx),
3912 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3913 );
Christian Heimesefff7062013-11-21 03:35:02 +01003914 }
3915 if (cert == NULL) {
3916 break;
3917 }
3918 r = X509_STORE_add_cert(store, cert);
3919 X509_free(cert);
3920 if (!r) {
3921 err = ERR_peek_last_error();
3922 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3923 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3924 /* cert already in hash table, not an error */
3925 ERR_clear_error();
3926 } else {
3927 break;
3928 }
3929 }
3930 loaded++;
3931 }
3932
3933 err = ERR_peek_last_error();
3934 if ((filetype == SSL_FILETYPE_ASN1) &&
3935 (loaded > 0) &&
3936 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3937 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3938 /* EOF ASN1 file, not an error */
3939 ERR_clear_error();
3940 retval = 0;
3941 } else if ((filetype == SSL_FILETYPE_PEM) &&
3942 (loaded > 0) &&
3943 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3944 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3945 /* EOF PEM file, not an error */
3946 ERR_clear_error();
3947 retval = 0;
3948 } else {
3949 _setSSLError(NULL, 0, __FILE__, __LINE__);
3950 retval = -1;
3951 }
3952
3953 BIO_free(biobuf);
3954 return retval;
3955}
3956
3957
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003958/*[clinic input]
3959_ssl._SSLContext.load_verify_locations
3960 cafile: object = NULL
3961 capath: object = NULL
3962 cadata: object = NULL
3963
3964[clinic start generated code]*/
3965
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003967_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3968 PyObject *cafile,
3969 PyObject *capath,
3970 PyObject *cadata)
3971/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003972{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003973 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3974 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003975 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003977 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003978 if (cafile == Py_None)
3979 cafile = NULL;
3980 if (capath == Py_None)
3981 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003982 if (cadata == Py_None)
3983 cadata = NULL;
3984
3985 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003986 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003987 "cafile, capath and cadata cannot be all omitted");
3988 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003989 }
3990 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003991 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3992 PyErr_SetString(PyExc_TypeError,
3993 "cafile should be a valid filesystem path");
3994 }
Christian Heimesefff7062013-11-21 03:35:02 +01003995 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003996 }
3997 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003998 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3999 PyErr_SetString(PyExc_TypeError,
4000 "capath should be a valid filesystem path");
4001 }
Christian Heimesefff7062013-11-21 03:35:02 +01004002 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004003 }
Christian Heimesefff7062013-11-21 03:35:02 +01004004
4005 /* validata cadata type and load cadata */
4006 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004007 if (PyUnicode_Check(cadata)) {
4008 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4009 if (cadata_ascii == NULL) {
4010 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4011 goto invalid_cadata;
4012 }
4013 goto error;
4014 }
4015 r = _add_ca_certs(self,
4016 PyBytes_AS_STRING(cadata_ascii),
4017 PyBytes_GET_SIZE(cadata_ascii),
4018 SSL_FILETYPE_PEM);
4019 Py_DECREF(cadata_ascii);
4020 if (r == -1) {
4021 goto error;
4022 }
4023 }
4024 else if (PyObject_CheckBuffer(cadata)) {
4025 Py_buffer buf;
4026 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4027 goto error;
4028 }
Christian Heimesefff7062013-11-21 03:35:02 +01004029 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4030 PyBuffer_Release(&buf);
4031 PyErr_SetString(PyExc_TypeError,
4032 "cadata should be a contiguous buffer with "
4033 "a single dimension");
4034 goto error;
4035 }
4036 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4037 PyBuffer_Release(&buf);
4038 if (r == -1) {
4039 goto error;
4040 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004041 }
4042 else {
4043 invalid_cadata:
4044 PyErr_SetString(PyExc_TypeError,
4045 "cadata should be an ASCII string or a "
4046 "bytes-like object");
4047 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004048 }
4049 }
4050
4051 /* load cafile or capath */
4052 if (cafile || capath) {
4053 if (cafile)
4054 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4055 if (capath)
4056 capath_buf = PyBytes_AS_STRING(capath_bytes);
4057 PySSL_BEGIN_ALLOW_THREADS
4058 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4059 PySSL_END_ALLOW_THREADS
4060 if (r != 1) {
4061 ok = 0;
4062 if (errno != 0) {
4063 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004064 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004065 }
4066 else {
4067 _setSSLError(NULL, 0, __FILE__, __LINE__);
4068 }
4069 goto error;
4070 }
4071 }
4072 goto end;
4073
4074 error:
4075 ok = 0;
4076 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004077 Py_XDECREF(cafile_bytes);
4078 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004079 if (ok) {
4080 Py_RETURN_NONE;
4081 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004082 return NULL;
4083 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004084}
4085
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004086/*[clinic input]
4087_ssl._SSLContext.load_dh_params
4088 path as filepath: object
4089 /
4090
4091[clinic start generated code]*/
4092
Antoine Pitrou152efa22010-05-16 18:19:27 +00004093static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004094_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4095/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004096{
4097 FILE *f;
4098 DH *dh;
4099
Victor Stinnerdaf45552013-08-28 00:53:59 +02004100 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004101 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004102 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004103
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004104 errno = 0;
4105 PySSL_BEGIN_ALLOW_THREADS
4106 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004107 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004108 PySSL_END_ALLOW_THREADS
4109 if (dh == NULL) {
4110 if (errno != 0) {
4111 ERR_clear_error();
4112 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4113 }
4114 else {
4115 _setSSLError(NULL, 0, __FILE__, __LINE__);
4116 }
4117 return NULL;
4118 }
4119 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4120 _setSSLError(NULL, 0, __FILE__, __LINE__);
4121 DH_free(dh);
4122 Py_RETURN_NONE;
4123}
4124
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125/*[clinic input]
4126_ssl._SSLContext._wrap_socket
4127 sock: object(subclass_of="PySocketModule.Sock_Type")
4128 server_side: int
4129 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004130 *
4131 owner: object = None
4132 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004133
4134[clinic start generated code]*/
4135
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004136static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004137_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004138 int server_side, PyObject *hostname_obj,
4139 PyObject *owner, PyObject *session)
4140/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004141{
Antoine Pitroud5323212010-10-22 18:19:07 +00004142 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004143 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004144
Antoine Pitroud5323212010-10-22 18:19:07 +00004145 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004146 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004147 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004148 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004149 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004150 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004152 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4153 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004154 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004155 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004156 if (hostname != NULL)
4157 PyMem_Free(hostname);
4158 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004159}
4160
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004161/*[clinic input]
4162_ssl._SSLContext._wrap_bio
4163 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4164 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4165 server_side: int
4166 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004167 *
4168 owner: object = None
4169 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004170
4171[clinic start generated code]*/
4172
Antoine Pitroub0182c82010-10-12 20:09:02 +00004173static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4175 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004176 PyObject *hostname_obj, PyObject *owner,
4177 PyObject *session)
4178/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004180 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004182
4183 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004184 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004185 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004186 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188 }
4189
4190 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004191 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004192 incoming, outgoing);
4193
4194 PyMem_Free(hostname);
4195 return res;
4196}
4197
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004198/*[clinic input]
4199_ssl._SSLContext.session_stats
4200[clinic start generated code]*/
4201
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004202static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4204/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004205{
4206 int r;
4207 PyObject *value, *stats = PyDict_New();
4208 if (!stats)
4209 return NULL;
4210
4211#define ADD_STATS(SSL_NAME, KEY_NAME) \
4212 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4213 if (value == NULL) \
4214 goto error; \
4215 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4216 Py_DECREF(value); \
4217 if (r < 0) \
4218 goto error;
4219
4220 ADD_STATS(number, "number");
4221 ADD_STATS(connect, "connect");
4222 ADD_STATS(connect_good, "connect_good");
4223 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4224 ADD_STATS(accept, "accept");
4225 ADD_STATS(accept_good, "accept_good");
4226 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4227 ADD_STATS(accept, "accept");
4228 ADD_STATS(hits, "hits");
4229 ADD_STATS(misses, "misses");
4230 ADD_STATS(timeouts, "timeouts");
4231 ADD_STATS(cache_full, "cache_full");
4232
4233#undef ADD_STATS
4234
4235 return stats;
4236
4237error:
4238 Py_DECREF(stats);
4239 return NULL;
4240}
4241
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004242/*[clinic input]
4243_ssl._SSLContext.set_default_verify_paths
4244[clinic start generated code]*/
4245
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004246static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004247_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4248/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004249{
4250 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4251 _setSSLError(NULL, 0, __FILE__, __LINE__);
4252 return NULL;
4253 }
4254 Py_RETURN_NONE;
4255}
4256
Antoine Pitrou501da612011-12-21 09:27:41 +01004257#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004258/*[clinic input]
4259_ssl._SSLContext.set_ecdh_curve
4260 name: object
4261 /
4262
4263[clinic start generated code]*/
4264
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004265static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004266_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4267/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004268{
4269 PyObject *name_bytes;
4270 int nid;
4271 EC_KEY *key;
4272
4273 if (!PyUnicode_FSConverter(name, &name_bytes))
4274 return NULL;
4275 assert(PyBytes_Check(name_bytes));
4276 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4277 Py_DECREF(name_bytes);
4278 if (nid == 0) {
4279 PyErr_Format(PyExc_ValueError,
4280 "unknown elliptic curve name %R", name);
4281 return NULL;
4282 }
4283 key = EC_KEY_new_by_curve_name(nid);
4284 if (key == NULL) {
4285 _setSSLError(NULL, 0, __FILE__, __LINE__);
4286 return NULL;
4287 }
4288 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4289 EC_KEY_free(key);
4290 Py_RETURN_NONE;
4291}
Antoine Pitrou501da612011-12-21 09:27:41 +01004292#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004293
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004294#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004295static int
4296_servername_callback(SSL *s, int *al, void *args)
4297{
4298 int ret;
4299 PySSLContext *ssl_ctx = (PySSLContext *) args;
4300 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004301 PyObject *result;
4302 /* The high-level ssl.SSLSocket object */
4303 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004304 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004305 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004306
Christian Heimes11a14932018-02-24 02:35:08 +01004307 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004308 /* remove race condition in this the call back while if removing the
4309 * callback is in progress */
4310 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004311 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004312 }
4313
4314 ssl = SSL_get_app_data(s);
4315 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004316
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004317 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004318 * SSL connection and that has a .context attribute that can be changed to
4319 * identify the requested hostname. Since the official API is the Python
4320 * level API we want to pass the callback a Python level object rather than
4321 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4322 * SSLObject) that will be passed. Otherwise if there's a socket then that
4323 * will be passed. If both do not exist only then the C-level object is
4324 * passed. */
4325 if (ssl->owner)
4326 ssl_socket = PyWeakref_GetObject(ssl->owner);
4327 else if (ssl->Socket)
4328 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4329 else
4330 ssl_socket = (PyObject *) ssl;
4331
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004332 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004333 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004334 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004335
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004336 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004337 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004338 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004339 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004340 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004341 PyObject *servername_bytes;
4342 PyObject *servername_str;
4343
4344 servername_bytes = PyBytes_FromString(servername);
4345 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004346 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4347 goto error;
4348 }
Christian Heimes11a14932018-02-24 02:35:08 +01004349 /* server_hostname was encoded to an A-label by our caller; put it
4350 * back into a str object, but still as an A-label (bpo-28414)
4351 */
4352 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4353 Py_DECREF(servername_bytes);
4354 if (servername_str == NULL) {
4355 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004356 goto error;
4357 }
Christian Heimes11a14932018-02-24 02:35:08 +01004358 result = PyObject_CallFunctionObjArgs(
4359 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4360 ssl_ctx, NULL);
4361 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004362 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004363 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004364
4365 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004366 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004367 *al = SSL_AD_HANDSHAKE_FAILURE;
4368 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4369 }
4370 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004371 /* Result may be None, a SSLContext or an integer
4372 * None and SSLContext are OK, integer or other values are an error.
4373 */
4374 if (result == Py_None) {
4375 ret = SSL_TLSEXT_ERR_OK;
4376 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004377 *al = (int) PyLong_AsLong(result);
4378 if (PyErr_Occurred()) {
4379 PyErr_WriteUnraisable(result);
4380 *al = SSL_AD_INTERNAL_ERROR;
4381 }
4382 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4383 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004384 Py_DECREF(result);
4385 }
4386
4387 PyGILState_Release(gstate);
4388 return ret;
4389
4390error:
4391 Py_DECREF(ssl_socket);
4392 *al = SSL_AD_INTERNAL_ERROR;
4393 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4394 PyGILState_Release(gstate);
4395 return ret;
4396}
Antoine Pitroua5963382013-03-30 16:39:00 +01004397#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004398
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004399static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004400get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004401{
Christian Heimes11a14932018-02-24 02:35:08 +01004402 PyObject *cb = self->set_sni_cb;
4403 if (cb == NULL) {
4404 Py_RETURN_NONE;
4405 }
4406 Py_INCREF(cb);
4407 return cb;
4408}
4409
4410static int
4411set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4412{
4413 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4414 PyErr_SetString(PyExc_ValueError,
4415 "sni_callback cannot be set on TLS_CLIENT context");
4416 return -1;
4417 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004418#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004419 Py_CLEAR(self->set_sni_cb);
4420 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004421 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4422 }
4423 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004424 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004425 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4426 PyErr_SetString(PyExc_TypeError,
4427 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004428 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004429 }
Christian Heimes11a14932018-02-24 02:35:08 +01004430 Py_INCREF(arg);
4431 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004432 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4433 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4434 }
Christian Heimes11a14932018-02-24 02:35:08 +01004435 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004436#else
4437 PyErr_SetString(PyExc_NotImplementedError,
4438 "The TLS extension servername callback, "
4439 "SSL_CTX_set_tlsext_servername_callback, "
4440 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004441 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004442#endif
4443}
4444
Christian Heimes11a14932018-02-24 02:35:08 +01004445PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4446"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4447\n\
4448If the argument is None then the callback is disabled. The method is called\n\
4449with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4450See RFC 6066 for details of the SNI extension.");
4451
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004452/*[clinic input]
4453_ssl._SSLContext.cert_store_stats
4454
4455Returns quantities of loaded X.509 certificates.
4456
4457X.509 certificates with a CA extension and certificate revocation lists
4458inside the context's cert store.
4459
4460NOTE: Certificates in a capath directory aren't loaded unless they have
4461been used at least once.
4462[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004463
4464static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004465_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4466/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004467{
4468 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004469 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004470 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004471 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004472
4473 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004474 objs = X509_STORE_get0_objects(store);
4475 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4476 obj = sk_X509_OBJECT_value(objs, i);
4477 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004478 case X509_LU_X509:
4479 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004480 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004481 ca++;
4482 }
4483 break;
4484 case X509_LU_CRL:
4485 crl++;
4486 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004487 default:
4488 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4489 * As far as I can tell they are internal states and never
4490 * stored in a cert store */
4491 break;
4492 }
4493 }
4494 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4495 "x509_ca", ca);
4496}
4497
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004498/*[clinic input]
4499_ssl._SSLContext.get_ca_certs
4500 binary_form: bool = False
4501
4502Returns a list of dicts with information of loaded CA certs.
4503
4504If the optional argument is True, returns a DER-encoded copy of the CA
4505certificate.
4506
4507NOTE: Certificates in a capath directory aren't loaded unless they have
4508been used at least once.
4509[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004510
4511static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004512_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4513/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004514{
4515 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004516 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004517 PyObject *ci = NULL, *rlist = NULL;
4518 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004519
4520 if ((rlist = PyList_New(0)) == NULL) {
4521 return NULL;
4522 }
4523
4524 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004525 objs = X509_STORE_get0_objects(store);
4526 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004527 X509_OBJECT *obj;
4528 X509 *cert;
4529
Christian Heimes598894f2016-09-05 23:19:05 +02004530 obj = sk_X509_OBJECT_value(objs, i);
4531 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004532 /* not a x509 cert */
4533 continue;
4534 }
4535 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004536 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004537 if (!X509_check_ca(cert)) {
4538 continue;
4539 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004540 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004541 ci = _certificate_to_der(cert);
4542 } else {
4543 ci = _decode_certificate(cert);
4544 }
4545 if (ci == NULL) {
4546 goto error;
4547 }
4548 if (PyList_Append(rlist, ci) == -1) {
4549 goto error;
4550 }
4551 Py_CLEAR(ci);
4552 }
4553 return rlist;
4554
4555 error:
4556 Py_XDECREF(ci);
4557 Py_XDECREF(rlist);
4558 return NULL;
4559}
4560
4561
Antoine Pitrou152efa22010-05-16 18:19:27 +00004562static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004563 {"check_hostname", (getter) get_check_hostname,
4564 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004565 {"_host_flags", (getter) get_host_flags,
4566 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004567#if SSL_CTRL_GET_MAX_PROTO_VERSION
4568 {"minimum_version", (getter) get_minimum_version,
4569 (setter) set_minimum_version, NULL},
4570 {"maximum_version", (getter) get_maximum_version,
4571 (setter) set_maximum_version, NULL},
4572#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004573 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004574 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004575 {"options", (getter) get_options,
4576 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004577 {"post_handshake_auth", (getter) get_post_handshake_auth,
4578#ifdef TLS1_3_VERSION
4579 (setter) set_post_handshake_auth,
4580#else
4581 NULL,
4582#endif
4583 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004584 {"protocol", (getter) get_protocol,
4585 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004586 {"verify_flags", (getter) get_verify_flags,
4587 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004588 {"verify_mode", (getter) get_verify_mode,
4589 (setter) set_verify_mode, NULL},
4590 {NULL}, /* sentinel */
4591};
4592
4593static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004594 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4595 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4596 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4597 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4598 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4599 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4600 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4601 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4602 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4603 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4604 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004605 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4606 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004607 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004608 {NULL, NULL} /* sentinel */
4609};
4610
4611static PyTypeObject PySSLContext_Type = {
4612 PyVarObject_HEAD_INIT(NULL, 0)
4613 "_ssl._SSLContext", /*tp_name*/
4614 sizeof(PySSLContext), /*tp_basicsize*/
4615 0, /*tp_itemsize*/
4616 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004617 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004618 0, /*tp_getattr*/
4619 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004620 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004621 0, /*tp_repr*/
4622 0, /*tp_as_number*/
4623 0, /*tp_as_sequence*/
4624 0, /*tp_as_mapping*/
4625 0, /*tp_hash*/
4626 0, /*tp_call*/
4627 0, /*tp_str*/
4628 0, /*tp_getattro*/
4629 0, /*tp_setattro*/
4630 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004631 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004632 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004633 (traverseproc) context_traverse, /*tp_traverse*/
4634 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004635 0, /*tp_richcompare*/
4636 0, /*tp_weaklistoffset*/
4637 0, /*tp_iter*/
4638 0, /*tp_iternext*/
4639 context_methods, /*tp_methods*/
4640 0, /*tp_members*/
4641 context_getsetlist, /*tp_getset*/
4642 0, /*tp_base*/
4643 0, /*tp_dict*/
4644 0, /*tp_descr_get*/
4645 0, /*tp_descr_set*/
4646 0, /*tp_dictoffset*/
4647 0, /*tp_init*/
4648 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004650};
4651
4652
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004653/*
4654 * MemoryBIO objects
4655 */
4656
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004657/*[clinic input]
4658@classmethod
4659_ssl.MemoryBIO.__new__
4660
4661[clinic start generated code]*/
4662
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004663static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664_ssl_MemoryBIO_impl(PyTypeObject *type)
4665/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004667 BIO *bio;
4668 PySSLMemoryBIO *self;
4669
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004670 bio = BIO_new(BIO_s_mem());
4671 if (bio == NULL) {
4672 PyErr_SetString(PySSLErrorObject,
4673 "failed to allocate BIO");
4674 return NULL;
4675 }
4676 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4677 * just that no data is currently available. The SSL routines should retry
4678 * the read, which we can achieve by calling BIO_set_retry_read(). */
4679 BIO_set_retry_read(bio);
4680 BIO_set_mem_eof_return(bio, -1);
4681
4682 assert(type != NULL && type->tp_alloc != NULL);
4683 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4684 if (self == NULL) {
4685 BIO_free(bio);
4686 return NULL;
4687 }
4688 self->bio = bio;
4689 self->eof_written = 0;
4690
4691 return (PyObject *) self;
4692}
4693
4694static void
4695memory_bio_dealloc(PySSLMemoryBIO *self)
4696{
4697 BIO_free(self->bio);
4698 Py_TYPE(self)->tp_free(self);
4699}
4700
4701static PyObject *
4702memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4703{
Segev Finer5cff6372017-07-27 01:19:17 +03004704 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004705}
4706
4707PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4708"The number of bytes pending in the memory BIO.");
4709
4710static PyObject *
4711memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4712{
4713 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4714 && self->eof_written);
4715}
4716
4717PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4718"Whether the memory BIO is at EOF.");
4719
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004720/*[clinic input]
4721_ssl.MemoryBIO.read
4722 size as len: int = -1
4723 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004724
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004725Read up to size bytes from the memory BIO.
4726
4727If size is not specified, read the entire buffer.
4728If the return value is an empty bytes instance, this means either
4729EOF or that no data is available. Use the "eof" property to
4730distinguish between the two.
4731[clinic start generated code]*/
4732
4733static PyObject *
4734_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4735/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4736{
4737 int avail, nbytes;
4738 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004739
Segev Finer5cff6372017-07-27 01:19:17 +03004740 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004741 if ((len < 0) || (len > avail))
4742 len = avail;
4743
4744 result = PyBytes_FromStringAndSize(NULL, len);
4745 if ((result == NULL) || (len == 0))
4746 return result;
4747
4748 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004749 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004750 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004751 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004752 return NULL;
4753 }
4754
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004755 /* There should never be any short reads but check anyway. */
4756 if (nbytes < len) {
4757 _PyBytes_Resize(&result, nbytes);
4758 }
4759
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004760 return result;
4761}
4762
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004763/*[clinic input]
4764_ssl.MemoryBIO.write
4765 b: Py_buffer
4766 /
4767
4768Writes the bytes b into the memory BIO.
4769
4770Returns the number of bytes written.
4771[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004772
4773static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004774_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4775/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004776{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004777 int nbytes;
4778
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004779 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004780 PyErr_Format(PyExc_OverflowError,
4781 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004782 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004783 }
4784
4785 if (self->eof_written) {
4786 PyErr_SetString(PySSLErrorObject,
4787 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004788 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004789 }
4790
Segev Finer5cff6372017-07-27 01:19:17 +03004791 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004792 if (nbytes < 0) {
4793 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004794 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004795 }
4796
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004797 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004798}
4799
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004800/*[clinic input]
4801_ssl.MemoryBIO.write_eof
4802
4803Write an EOF marker to the memory BIO.
4804
4805When all data has been read, the "eof" property will be True.
4806[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004807
4808static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004809_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4810/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004811{
4812 self->eof_written = 1;
4813 /* After an EOF is written, a zero return from read() should be a real EOF
4814 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4815 BIO_clear_retry_flags(self->bio);
4816 BIO_set_mem_eof_return(self->bio, 0);
4817
4818 Py_RETURN_NONE;
4819}
4820
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004821static PyGetSetDef memory_bio_getsetlist[] = {
4822 {"pending", (getter) memory_bio_get_pending, NULL,
4823 PySSL_memory_bio_pending_doc},
4824 {"eof", (getter) memory_bio_get_eof, NULL,
4825 PySSL_memory_bio_eof_doc},
4826 {NULL}, /* sentinel */
4827};
4828
4829static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004830 _SSL_MEMORYBIO_READ_METHODDEF
4831 _SSL_MEMORYBIO_WRITE_METHODDEF
4832 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004833 {NULL, NULL} /* sentinel */
4834};
4835
4836static PyTypeObject PySSLMemoryBIO_Type = {
4837 PyVarObject_HEAD_INIT(NULL, 0)
4838 "_ssl.MemoryBIO", /*tp_name*/
4839 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4840 0, /*tp_itemsize*/
4841 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004842 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004843 0, /*tp_getattr*/
4844 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004845 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004846 0, /*tp_repr*/
4847 0, /*tp_as_number*/
4848 0, /*tp_as_sequence*/
4849 0, /*tp_as_mapping*/
4850 0, /*tp_hash*/
4851 0, /*tp_call*/
4852 0, /*tp_str*/
4853 0, /*tp_getattro*/
4854 0, /*tp_setattro*/
4855 0, /*tp_as_buffer*/
4856 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4857 0, /*tp_doc*/
4858 0, /*tp_traverse*/
4859 0, /*tp_clear*/
4860 0, /*tp_richcompare*/
4861 0, /*tp_weaklistoffset*/
4862 0, /*tp_iter*/
4863 0, /*tp_iternext*/
4864 memory_bio_methods, /*tp_methods*/
4865 0, /*tp_members*/
4866 memory_bio_getsetlist, /*tp_getset*/
4867 0, /*tp_base*/
4868 0, /*tp_dict*/
4869 0, /*tp_descr_get*/
4870 0, /*tp_descr_set*/
4871 0, /*tp_dictoffset*/
4872 0, /*tp_init*/
4873 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004874 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004875};
4876
Antoine Pitrou152efa22010-05-16 18:19:27 +00004877
Christian Heimes99a65702016-09-10 23:44:53 +02004878/*
4879 * SSL Session object
4880 */
4881
4882static void
4883PySSLSession_dealloc(PySSLSession *self)
4884{
INADA Naokia6296d32017-08-24 14:55:17 +09004885 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004886 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004887 Py_XDECREF(self->ctx);
4888 if (self->session != NULL) {
4889 SSL_SESSION_free(self->session);
4890 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004891 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004892}
4893
4894static PyObject *
4895PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4896{
4897 int result;
4898
4899 if (left == NULL || right == NULL) {
4900 PyErr_BadInternalCall();
4901 return NULL;
4902 }
4903
4904 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4905 Py_RETURN_NOTIMPLEMENTED;
4906 }
4907
4908 if (left == right) {
4909 result = 0;
4910 } else {
4911 const unsigned char *left_id, *right_id;
4912 unsigned int left_len, right_len;
4913 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4914 &left_len);
4915 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4916 &right_len);
4917 if (left_len == right_len) {
4918 result = memcmp(left_id, right_id, left_len);
4919 } else {
4920 result = 1;
4921 }
4922 }
4923
4924 switch (op) {
4925 case Py_EQ:
4926 if (result == 0) {
4927 Py_RETURN_TRUE;
4928 } else {
4929 Py_RETURN_FALSE;
4930 }
4931 break;
4932 case Py_NE:
4933 if (result != 0) {
4934 Py_RETURN_TRUE;
4935 } else {
4936 Py_RETURN_FALSE;
4937 }
4938 break;
4939 case Py_LT:
4940 case Py_LE:
4941 case Py_GT:
4942 case Py_GE:
4943 Py_RETURN_NOTIMPLEMENTED;
4944 break;
4945 default:
4946 PyErr_BadArgument();
4947 return NULL;
4948 }
4949}
4950
4951static int
4952PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4953{
4954 Py_VISIT(self->ctx);
4955 return 0;
4956}
4957
4958static int
4959PySSLSession_clear(PySSLSession *self)
4960{
4961 Py_CLEAR(self->ctx);
4962 return 0;
4963}
4964
4965
4966static PyObject *
4967PySSLSession_get_time(PySSLSession *self, void *closure) {
4968 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4969}
4970
4971PyDoc_STRVAR(PySSLSession_get_time_doc,
4972"Session creation time (seconds since epoch).");
4973
4974
4975static PyObject *
4976PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4977 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4978}
4979
4980PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4981"Session timeout (delta in seconds).");
4982
4983
4984static PyObject *
4985PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4986 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4987 return PyLong_FromUnsignedLong(hint);
4988}
4989
4990PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4991"Ticket life time hint.");
4992
4993
4994static PyObject *
4995PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4996 const unsigned char *id;
4997 unsigned int len;
4998 id = SSL_SESSION_get_id(self->session, &len);
4999 return PyBytes_FromStringAndSize((const char *)id, len);
5000}
5001
5002PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5003"Session id");
5004
5005
5006static PyObject *
5007PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5008 if (SSL_SESSION_has_ticket(self->session)) {
5009 Py_RETURN_TRUE;
5010 } else {
5011 Py_RETURN_FALSE;
5012 }
5013}
5014
5015PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5016"Does the session contain a ticket?");
5017
5018
5019static PyGetSetDef PySSLSession_getsetlist[] = {
5020 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5021 PySSLSession_get_has_ticket_doc},
5022 {"id", (getter) PySSLSession_get_session_id, NULL,
5023 PySSLSession_get_session_id_doc},
5024 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5025 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5026 {"time", (getter) PySSLSession_get_time, NULL,
5027 PySSLSession_get_time_doc},
5028 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5029 PySSLSession_get_timeout_doc},
5030 {NULL}, /* sentinel */
5031};
5032
5033static PyTypeObject PySSLSession_Type = {
5034 PyVarObject_HEAD_INIT(NULL, 0)
5035 "_ssl.Session", /*tp_name*/
5036 sizeof(PySSLSession), /*tp_basicsize*/
5037 0, /*tp_itemsize*/
5038 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005039 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005040 0, /*tp_getattr*/
5041 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005042 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005043 0, /*tp_repr*/
5044 0, /*tp_as_number*/
5045 0, /*tp_as_sequence*/
5046 0, /*tp_as_mapping*/
5047 0, /*tp_hash*/
5048 0, /*tp_call*/
5049 0, /*tp_str*/
5050 0, /*tp_getattro*/
5051 0, /*tp_setattro*/
5052 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005053 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005054 0, /*tp_doc*/
5055 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5056 (inquiry)PySSLSession_clear, /*tp_clear*/
5057 PySSLSession_richcompare, /*tp_richcompare*/
5058 0, /*tp_weaklistoffset*/
5059 0, /*tp_iter*/
5060 0, /*tp_iternext*/
5061 0, /*tp_methods*/
5062 0, /*tp_members*/
5063 PySSLSession_getsetlist, /*tp_getset*/
5064};
5065
5066
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005067/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005068/*[clinic input]
5069_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005070 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005071 entropy: double
5072 /
5073
5074Mix string into the OpenSSL PRNG state.
5075
5076entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305077string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005078[clinic start generated code]*/
5079
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005080static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005081_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005082/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005083{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005084 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005085 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005086
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005087 buf = (const char *)view->buf;
5088 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005089 do {
5090 written = Py_MIN(len, INT_MAX);
5091 RAND_add(buf, (int)written, entropy);
5092 buf += written;
5093 len -= written;
5094 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005095 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005096}
5097
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005098static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005099PySSL_RAND(int len, int pseudo)
5100{
5101 int ok;
5102 PyObject *bytes;
5103 unsigned long err;
5104 const char *errstr;
5105 PyObject *v;
5106
Victor Stinner1e81a392013-12-19 16:47:04 +01005107 if (len < 0) {
5108 PyErr_SetString(PyExc_ValueError, "num must be positive");
5109 return NULL;
5110 }
5111
Victor Stinner99c8b162011-05-24 12:05:19 +02005112 bytes = PyBytes_FromStringAndSize(NULL, len);
5113 if (bytes == NULL)
5114 return NULL;
5115 if (pseudo) {
5116 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5117 if (ok == 0 || ok == 1)
5118 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5119 }
5120 else {
5121 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5122 if (ok == 1)
5123 return bytes;
5124 }
5125 Py_DECREF(bytes);
5126
5127 err = ERR_get_error();
5128 errstr = ERR_reason_error_string(err);
5129 v = Py_BuildValue("(ks)", err, errstr);
5130 if (v != NULL) {
5131 PyErr_SetObject(PySSLErrorObject, v);
5132 Py_DECREF(v);
5133 }
5134 return NULL;
5135}
5136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005137/*[clinic input]
5138_ssl.RAND_bytes
5139 n: int
5140 /
5141
5142Generate n cryptographically strong pseudo-random bytes.
5143[clinic start generated code]*/
5144
Victor Stinner99c8b162011-05-24 12:05:19 +02005145static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005146_ssl_RAND_bytes_impl(PyObject *module, int n)
5147/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005148{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005149 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005150}
5151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005152/*[clinic input]
5153_ssl.RAND_pseudo_bytes
5154 n: int
5155 /
5156
5157Generate n pseudo-random bytes.
5158
5159Return a pair (bytes, is_cryptographic). is_cryptographic is True
5160if the bytes generated are cryptographically strong.
5161[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005162
5163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005164_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5165/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005166{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005167 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005168}
5169
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005170/*[clinic input]
5171_ssl.RAND_status
5172
5173Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5174
5175It is necessary to seed the PRNG with RAND_add() on some platforms before
5176using the ssl() function.
5177[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005178
5179static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005180_ssl_RAND_status_impl(PyObject *module)
5181/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005182{
Christian Heimes217cfd12007-12-02 14:31:20 +00005183 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005184}
5185
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005186#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005187/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005188/*[clinic input]
5189_ssl.RAND_egd
5190 path: object(converter="PyUnicode_FSConverter")
5191 /
5192
5193Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5194
5195Returns number of bytes read. Raises SSLError if connection to EGD
5196fails or if it does not provide enough data to seed PRNG.
5197[clinic start generated code]*/
5198
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005199static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005200_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5201/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005202{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005203 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005204 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005205 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005206 PyErr_SetString(PySSLErrorObject,
5207 "EGD connection failed or EGD did not return "
5208 "enough data to seed the PRNG");
5209 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005210 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005211 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005212}
Christian Heimesa5d07652016-09-24 10:48:05 +02005213/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005214#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005215
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005216
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005217
5218/*[clinic input]
5219_ssl.get_default_verify_paths
5220
5221Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5222
5223The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5224[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005225
5226static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005227_ssl_get_default_verify_paths_impl(PyObject *module)
5228/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005229{
5230 PyObject *ofile_env = NULL;
5231 PyObject *ofile = NULL;
5232 PyObject *odir_env = NULL;
5233 PyObject *odir = NULL;
5234
Benjamin Petersond113c962015-07-18 10:59:13 -07005235#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005236 const char *tmp = (info); \
5237 target = NULL; \
5238 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5239 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5240 target = PyBytes_FromString(tmp); } \
5241 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005242 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005243
Benjamin Petersond113c962015-07-18 10:59:13 -07005244 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5245 CONVERT(X509_get_default_cert_file(), ofile);
5246 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5247 CONVERT(X509_get_default_cert_dir(), odir);
5248#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005249
Christian Heimes200bb1b2013-06-14 15:14:29 +02005250 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005251
5252 error:
5253 Py_XDECREF(ofile_env);
5254 Py_XDECREF(ofile);
5255 Py_XDECREF(odir_env);
5256 Py_XDECREF(odir);
5257 return NULL;
5258}
5259
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005260static PyObject*
5261asn1obj2py(ASN1_OBJECT *obj)
5262{
5263 int nid;
5264 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005265
5266 nid = OBJ_obj2nid(obj);
5267 if (nid == NID_undef) {
5268 PyErr_Format(PyExc_ValueError, "Unknown object");
5269 return NULL;
5270 }
5271 sn = OBJ_nid2sn(nid);
5272 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005273 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005274}
5275
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005276/*[clinic input]
5277_ssl.txt2obj
5278 txt: str
5279 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005280
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005281Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5282
5283By default objects are looked up by OID. With name=True short and
5284long name are also matched.
5285[clinic start generated code]*/
5286
5287static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005288_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5289/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005290{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005291 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005292 ASN1_OBJECT *obj;
5293
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005294 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5295 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005296 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005297 return NULL;
5298 }
5299 result = asn1obj2py(obj);
5300 ASN1_OBJECT_free(obj);
5301 return result;
5302}
5303
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005304/*[clinic input]
5305_ssl.nid2obj
5306 nid: int
5307 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005308
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005309Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5310[clinic start generated code]*/
5311
5312static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005313_ssl_nid2obj_impl(PyObject *module, int nid)
5314/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005315{
5316 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005317 ASN1_OBJECT *obj;
5318
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005319 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005320 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005321 return NULL;
5322 }
5323 obj = OBJ_nid2obj(nid);
5324 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005325 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005326 return NULL;
5327 }
5328 result = asn1obj2py(obj);
5329 ASN1_OBJECT_free(obj);
5330 return result;
5331}
5332
Christian Heimes46bebee2013-06-09 19:03:31 +02005333#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005334
5335static PyObject*
5336certEncodingType(DWORD encodingType)
5337{
5338 static PyObject *x509_asn = NULL;
5339 static PyObject *pkcs_7_asn = NULL;
5340
5341 if (x509_asn == NULL) {
5342 x509_asn = PyUnicode_InternFromString("x509_asn");
5343 if (x509_asn == NULL)
5344 return NULL;
5345 }
5346 if (pkcs_7_asn == NULL) {
5347 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5348 if (pkcs_7_asn == NULL)
5349 return NULL;
5350 }
5351 switch(encodingType) {
5352 case X509_ASN_ENCODING:
5353 Py_INCREF(x509_asn);
5354 return x509_asn;
5355 case PKCS_7_ASN_ENCODING:
5356 Py_INCREF(pkcs_7_asn);
5357 return pkcs_7_asn;
5358 default:
5359 return PyLong_FromLong(encodingType);
5360 }
5361}
5362
5363static PyObject*
5364parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5365{
5366 CERT_ENHKEY_USAGE *usage;
5367 DWORD size, error, i;
5368 PyObject *retval;
5369
5370 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5371 error = GetLastError();
5372 if (error == CRYPT_E_NOT_FOUND) {
5373 Py_RETURN_TRUE;
5374 }
5375 return PyErr_SetFromWindowsErr(error);
5376 }
5377
5378 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5379 if (usage == NULL) {
5380 return PyErr_NoMemory();
5381 }
5382
5383 /* Now get the actual enhanced usage property */
5384 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5385 PyMem_Free(usage);
5386 error = GetLastError();
5387 if (error == CRYPT_E_NOT_FOUND) {
5388 Py_RETURN_TRUE;
5389 }
5390 return PyErr_SetFromWindowsErr(error);
5391 }
5392 retval = PySet_New(NULL);
5393 if (retval == NULL) {
5394 goto error;
5395 }
5396 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5397 if (usage->rgpszUsageIdentifier[i]) {
5398 PyObject *oid;
5399 int err;
5400 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5401 if (oid == NULL) {
5402 Py_CLEAR(retval);
5403 goto error;
5404 }
5405 err = PySet_Add(retval, oid);
5406 Py_DECREF(oid);
5407 if (err == -1) {
5408 Py_CLEAR(retval);
5409 goto error;
5410 }
5411 }
5412 }
5413 error:
5414 PyMem_Free(usage);
5415 return retval;
5416}
5417
kctherookied93fbbf2019-03-29 00:59:06 +07005418static HCERTSTORE
5419ssl_collect_certificates(const char *store_name)
5420{
5421/* this function collects the system certificate stores listed in
5422 * system_stores into a collection certificate store for being
5423 * enumerated. The store must be readable to be added to the
5424 * store collection.
5425 */
5426
5427 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5428 static DWORD system_stores[] = {
5429 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5430 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5431 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5432 CERT_SYSTEM_STORE_CURRENT_USER,
5433 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5434 CERT_SYSTEM_STORE_SERVICES,
5435 CERT_SYSTEM_STORE_USERS};
5436 size_t i, storesAdded;
5437 BOOL result;
5438
5439 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5440 (HCRYPTPROV)NULL, 0, NULL);
5441 if (!hCollectionStore) {
5442 return NULL;
5443 }
5444 storesAdded = 0;
5445 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5446 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5447 (HCRYPTPROV)NULL,
5448 CERT_STORE_READONLY_FLAG |
5449 system_stores[i], store_name);
5450 if (hSystemStore) {
5451 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5452 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5453 if (result) {
5454 ++storesAdded;
5455 }
5456 }
5457 }
5458 if (storesAdded == 0) {
5459 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5460 return NULL;
5461 }
5462
5463 return hCollectionStore;
5464}
5465
5466/* code from Objects/listobject.c */
5467
5468static int
5469list_contains(PyListObject *a, PyObject *el)
5470{
5471 Py_ssize_t i;
5472 int cmp;
5473
5474 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
5475 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
5476 Py_EQ);
5477 return cmp;
5478}
5479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005480/*[clinic input]
5481_ssl.enum_certificates
5482 store_name: str
5483
5484Retrieve certificates from Windows' cert store.
5485
5486store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5487more cert storages, too. The function returns a list of (bytes,
5488encoding_type, trust) tuples. The encoding_type flag can be interpreted
5489with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5490a set of OIDs or the boolean True.
5491[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005492
Christian Heimes46bebee2013-06-09 19:03:31 +02005493static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005494_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5495/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005496{
kctherookied93fbbf2019-03-29 00:59:06 +07005497 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005498 PCCERT_CONTEXT pCertCtx = NULL;
5499 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005500 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005501
Christian Heimes44109d72013-11-22 01:51:30 +01005502 result = PyList_New(0);
5503 if (result == NULL) {
5504 return NULL;
5505 }
kctherookied93fbbf2019-03-29 00:59:06 +07005506 hCollectionStore = ssl_collect_certificates(store_name);
5507 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005508 Py_DECREF(result);
5509 return PyErr_SetFromWindowsErr(GetLastError());
5510 }
5511
kctherookied93fbbf2019-03-29 00:59:06 +07005512 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005513 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5514 pCertCtx->cbCertEncoded);
5515 if (!cert) {
5516 Py_CLEAR(result);
5517 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005518 }
Christian Heimes44109d72013-11-22 01:51:30 +01005519 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5520 Py_CLEAR(result);
5521 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005522 }
Christian Heimes44109d72013-11-22 01:51:30 +01005523 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5524 if (keyusage == Py_True) {
5525 Py_DECREF(keyusage);
5526 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005527 }
Christian Heimes44109d72013-11-22 01:51:30 +01005528 if (keyusage == NULL) {
5529 Py_CLEAR(result);
5530 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005531 }
Christian Heimes44109d72013-11-22 01:51:30 +01005532 if ((tup = PyTuple_New(3)) == NULL) {
5533 Py_CLEAR(result);
5534 break;
5535 }
5536 PyTuple_SET_ITEM(tup, 0, cert);
5537 cert = NULL;
5538 PyTuple_SET_ITEM(tup, 1, enc);
5539 enc = NULL;
5540 PyTuple_SET_ITEM(tup, 2, keyusage);
5541 keyusage = NULL;
kctherookied93fbbf2019-03-29 00:59:06 +07005542 if (!list_contains((PyListObject*)result, tup)) {
5543 if (PyList_Append(result, tup) < 0) {
5544 Py_CLEAR(result);
5545 break;
5546 }
Christian Heimes44109d72013-11-22 01:51:30 +01005547 }
5548 Py_CLEAR(tup);
5549 }
5550 if (pCertCtx) {
5551 /* loop ended with an error, need to clean up context manually */
5552 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005553 }
5554
5555 /* In error cases cert, enc and tup may not be NULL */
5556 Py_XDECREF(cert);
5557 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005558 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005559 Py_XDECREF(tup);
5560
kctherookied93fbbf2019-03-29 00:59:06 +07005561 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5562 associated with the store, in this case our collection store and the
5563 associated system stores. */
5564 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005565 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005566 Py_XDECREF(result);
5567 return PyErr_SetFromWindowsErr(GetLastError());
5568 }
kctherookied93fbbf2019-03-29 00:59:06 +07005569
Christian Heimes44109d72013-11-22 01:51:30 +01005570 return result;
5571}
5572
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005573/*[clinic input]
5574_ssl.enum_crls
5575 store_name: str
5576
5577Retrieve CRLs from Windows' cert store.
5578
5579store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5580more cert storages, too. The function returns a list of (bytes,
5581encoding_type) tuples. The encoding_type flag can be interpreted with
5582X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5583[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005584
5585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005586_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5587/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005588{
kctherookied93fbbf2019-03-29 00:59:06 +07005589 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005590 PCCRL_CONTEXT pCrlCtx = NULL;
5591 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5592 PyObject *result = NULL;
5593
Christian Heimes44109d72013-11-22 01:51:30 +01005594 result = PyList_New(0);
5595 if (result == NULL) {
5596 return NULL;
5597 }
kctherookied93fbbf2019-03-29 00:59:06 +07005598 hCollectionStore = ssl_collect_certificates(store_name);
5599 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005600 Py_DECREF(result);
5601 return PyErr_SetFromWindowsErr(GetLastError());
5602 }
Christian Heimes44109d72013-11-22 01:51:30 +01005603
kctherookied93fbbf2019-03-29 00:59:06 +07005604 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005605 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5606 pCrlCtx->cbCrlEncoded);
5607 if (!crl) {
5608 Py_CLEAR(result);
5609 break;
5610 }
5611 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5612 Py_CLEAR(result);
5613 break;
5614 }
5615 if ((tup = PyTuple_New(2)) == NULL) {
5616 Py_CLEAR(result);
5617 break;
5618 }
5619 PyTuple_SET_ITEM(tup, 0, crl);
5620 crl = NULL;
5621 PyTuple_SET_ITEM(tup, 1, enc);
5622 enc = NULL;
5623
kctherookied93fbbf2019-03-29 00:59:06 +07005624 if (!list_contains((PyListObject*)result, tup)) {
5625 if (PyList_Append(result, tup) < 0) {
5626 Py_CLEAR(result);
5627 break;
5628 }
Christian Heimes44109d72013-11-22 01:51:30 +01005629 }
5630 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005631 }
Christian Heimes44109d72013-11-22 01:51:30 +01005632 if (pCrlCtx) {
5633 /* loop ended with an error, need to clean up context manually */
5634 CertFreeCRLContext(pCrlCtx);
5635 }
5636
5637 /* In error cases cert, enc and tup may not be NULL */
5638 Py_XDECREF(crl);
5639 Py_XDECREF(enc);
5640 Py_XDECREF(tup);
5641
kctherookied93fbbf2019-03-29 00:59:06 +07005642 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5643 associated with the store, in this case our collection store and the
5644 associated system stores. */
5645 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005646 /* This error case might shadow another exception.*/
5647 Py_XDECREF(result);
5648 return PyErr_SetFromWindowsErr(GetLastError());
5649 }
5650 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005651}
Christian Heimes44109d72013-11-22 01:51:30 +01005652
5653#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005654
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005655/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005656static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005657 _SSL__TEST_DECODE_CERT_METHODDEF
5658 _SSL_RAND_ADD_METHODDEF
5659 _SSL_RAND_BYTES_METHODDEF
5660 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5661 _SSL_RAND_EGD_METHODDEF
5662 _SSL_RAND_STATUS_METHODDEF
5663 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5664 _SSL_ENUM_CERTIFICATES_METHODDEF
5665 _SSL_ENUM_CRLS_METHODDEF
5666 _SSL_TXT2OBJ_METHODDEF
5667 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005668 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005669};
5670
5671
Christian Heimes598894f2016-09-05 23:19:05 +02005672#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005673
5674/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005675 * of the Python C thread library
5676 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5677 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005678
5679static PyThread_type_lock *_ssl_locks = NULL;
5680
Christian Heimes4d98ca92013-08-19 17:36:29 +02005681#if OPENSSL_VERSION_NUMBER >= 0x10000000
5682/* use new CRYPTO_THREADID API. */
5683static void
5684_ssl_threadid_callback(CRYPTO_THREADID *id)
5685{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005686 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005687}
5688#else
5689/* deprecated CRYPTO_set_id_callback() API. */
5690static unsigned long
5691_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005692 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005693}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005694#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005695
Bill Janssen6e027db2007-11-15 22:23:56 +00005696static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005697 (int mode, int n, const char *file, int line) {
5698 /* this function is needed to perform locking on shared data
5699 structures. (Note that OpenSSL uses a number of global data
5700 structures that will be implicitly shared whenever multiple
5701 threads use OpenSSL.) Multi-threaded applications will
5702 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005704 locking_function() must be able to handle up to
5705 CRYPTO_num_locks() different mutex locks. It sets the n-th
5706 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005707
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005708 file and line are the file number of the function setting the
5709 lock. They can be useful for debugging.
5710 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005712 if ((_ssl_locks == NULL) ||
5713 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5714 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005716 if (mode & CRYPTO_LOCK) {
5717 PyThread_acquire_lock(_ssl_locks[n], 1);
5718 } else {
5719 PyThread_release_lock(_ssl_locks[n]);
5720 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005721}
5722
5723static int _setup_ssl_threads(void) {
5724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005725 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005727 if (_ssl_locks == NULL) {
5728 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005729 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5730 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005731 if (_ssl_locks == NULL) {
5732 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005733 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005734 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005735 for (i = 0; i < _ssl_locks_count; i++) {
5736 _ssl_locks[i] = PyThread_allocate_lock();
5737 if (_ssl_locks[i] == NULL) {
5738 unsigned int j;
5739 for (j = 0; j < i; j++) {
5740 PyThread_free_lock(_ssl_locks[j]);
5741 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005742 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005743 return 0;
5744 }
5745 }
5746 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005747#if OPENSSL_VERSION_NUMBER >= 0x10000000
5748 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5749#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005750 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005751#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005752 }
5753 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005754}
5755
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005756#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005757
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005758PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005759"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005760for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005761
Martin v. Löwis1a214512008-06-11 05:26:20 +00005762
5763static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005764 PyModuleDef_HEAD_INIT,
5765 "_ssl",
5766 module_doc,
5767 -1,
5768 PySSL_methods,
5769 NULL,
5770 NULL,
5771 NULL,
5772 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005773};
5774
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005775
5776static void
5777parse_openssl_version(unsigned long libver,
5778 unsigned int *major, unsigned int *minor,
5779 unsigned int *fix, unsigned int *patch,
5780 unsigned int *status)
5781{
5782 *status = libver & 0xF;
5783 libver >>= 4;
5784 *patch = libver & 0xFF;
5785 libver >>= 8;
5786 *fix = libver & 0xFF;
5787 libver >>= 8;
5788 *minor = libver & 0xFF;
5789 libver >>= 8;
5790 *major = libver & 0xFF;
5791}
5792
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005793PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005794PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005795{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005796 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005797 unsigned long libver;
5798 unsigned int major, minor, fix, patch, status;
5799 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005800 struct py_ssl_error_code *errcode;
5801 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005802
Antoine Pitrou152efa22010-05-16 18:19:27 +00005803 if (PyType_Ready(&PySSLContext_Type) < 0)
5804 return NULL;
5805 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005806 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005807 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5808 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005809 if (PyType_Ready(&PySSLSession_Type) < 0)
5810 return NULL;
5811
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005813 m = PyModule_Create(&_sslmodule);
5814 if (m == NULL)
5815 return NULL;
5816 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005817
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005818 /* Load _socket module and its C API */
5819 socket_api = PySocketModule_ImportModuleAndAPI();
5820 if (!socket_api)
5821 return NULL;
5822 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005823
Christian Heimesc941e622017-09-05 15:47:11 +02005824#ifndef OPENSSL_VERSION_1_1
5825 /* Load all algorithms and initialize cpuid */
5826 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005827 /* Init OpenSSL */
5828 SSL_load_error_strings();
5829 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005830#endif
5831
Christian Heimes598894f2016-09-05 23:19:05 +02005832#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005833 /* note that this will start threading if not already started */
5834 if (!_setup_ssl_threads()) {
5835 return NULL;
5836 }
Christian Heimes598894f2016-09-05 23:19:05 +02005837#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5838 /* OpenSSL 1.1.0 builtin thread support is enabled */
5839 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005840#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005841
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005842 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005843 sslerror_type_slots[0].pfunc = PyExc_OSError;
5844 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005845 if (PySSLErrorObject == NULL)
5846 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005847
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005848 /* ssl.CertificateError used to be a subclass of ValueError */
5849 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5850 if (bases == NULL)
5851 return NULL;
5852 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5853 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5854 bases, NULL);
5855 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005856 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5857 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5858 PySSLErrorObject, NULL);
5859 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5860 "ssl.SSLWantReadError", SSLWantReadError_doc,
5861 PySSLErrorObject, NULL);
5862 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5863 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5864 PySSLErrorObject, NULL);
5865 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5866 "ssl.SSLSyscallError", SSLSyscallError_doc,
5867 PySSLErrorObject, NULL);
5868 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5869 "ssl.SSLEOFError", SSLEOFError_doc,
5870 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005871 if (PySSLCertVerificationErrorObject == NULL
5872 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005873 || PySSLWantReadErrorObject == NULL
5874 || PySSLWantWriteErrorObject == NULL
5875 || PySSLSyscallErrorObject == NULL
5876 || PySSLEOFErrorObject == NULL)
5877 return NULL;
5878 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005879 || PyDict_SetItemString(d, "SSLCertVerificationError",
5880 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005881 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5882 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5883 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5884 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5885 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005886 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005887 if (PyDict_SetItemString(d, "_SSLContext",
5888 (PyObject *)&PySSLContext_Type) != 0)
5889 return NULL;
5890 if (PyDict_SetItemString(d, "_SSLSocket",
5891 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005892 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005893 if (PyDict_SetItemString(d, "MemoryBIO",
5894 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5895 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005896 if (PyDict_SetItemString(d, "SSLSession",
5897 (PyObject *)&PySSLSession_Type) != 0)
5898 return NULL;
5899
Christian Heimes892d66e2018-01-29 14:10:18 +01005900 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5901 PY_SSL_DEFAULT_CIPHER_STRING);
5902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005903 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5904 PY_SSL_ERROR_ZERO_RETURN);
5905 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5906 PY_SSL_ERROR_WANT_READ);
5907 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5908 PY_SSL_ERROR_WANT_WRITE);
5909 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5910 PY_SSL_ERROR_WANT_X509_LOOKUP);
5911 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5912 PY_SSL_ERROR_SYSCALL);
5913 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5914 PY_SSL_ERROR_SSL);
5915 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5916 PY_SSL_ERROR_WANT_CONNECT);
5917 /* non ssl.h errorcodes */
5918 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5919 PY_SSL_ERROR_EOF);
5920 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5921 PY_SSL_ERROR_INVALID_ERROR_CODE);
5922 /* cert requirements */
5923 PyModule_AddIntConstant(m, "CERT_NONE",
5924 PY_SSL_CERT_NONE);
5925 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5926 PY_SSL_CERT_OPTIONAL);
5927 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5928 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005929 /* CRL verification for verification_flags */
5930 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5931 0);
5932 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5933 X509_V_FLAG_CRL_CHECK);
5934 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5935 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5936 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5937 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005938#ifdef X509_V_FLAG_TRUSTED_FIRST
5939 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5940 X509_V_FLAG_TRUSTED_FIRST);
5941#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005942
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005943 /* Alert Descriptions from ssl.h */
5944 /* note RESERVED constants no longer intended for use have been removed */
5945 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5946
5947#define ADD_AD_CONSTANT(s) \
5948 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5949 SSL_AD_##s)
5950
5951 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5952 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5953 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5954 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5955 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5956 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5957 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5958 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5959 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5960 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5961 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5962 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5963 ADD_AD_CONSTANT(UNKNOWN_CA);
5964 ADD_AD_CONSTANT(ACCESS_DENIED);
5965 ADD_AD_CONSTANT(DECODE_ERROR);
5966 ADD_AD_CONSTANT(DECRYPT_ERROR);
5967 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5968 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5969 ADD_AD_CONSTANT(INTERNAL_ERROR);
5970 ADD_AD_CONSTANT(USER_CANCELLED);
5971 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005972 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005973#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5974 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5975#endif
5976#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5977 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5978#endif
5979#ifdef SSL_AD_UNRECOGNIZED_NAME
5980 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5981#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005982#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5983 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5984#endif
5985#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5986 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5987#endif
5988#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5989 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5990#endif
5991
5992#undef ADD_AD_CONSTANT
5993
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005994 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005995#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005996 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5997 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005998#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005999#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006000 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6001 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006002#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006003 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006004 PY_SSL_VERSION_TLS);
6005 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6006 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006007 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6008 PY_SSL_VERSION_TLS_CLIENT);
6009 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6010 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006011 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6012 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006013#if HAVE_TLSv1_2
6014 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6015 PY_SSL_VERSION_TLS1_1);
6016 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6017 PY_SSL_VERSION_TLS1_2);
6018#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006019
Antoine Pitroub5218772010-05-21 09:56:06 +00006020 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006021 PyModule_AddIntConstant(m, "OP_ALL",
6022 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006023 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6024 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6025 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006026#if HAVE_TLSv1_2
6027 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6028 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6029#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006030#ifdef SSL_OP_NO_TLSv1_3
6031 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6032#else
6033 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6034#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006035 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6036 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006037 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006038 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006039#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006040 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006041#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006042#ifdef SSL_OP_NO_COMPRESSION
6043 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6044 SSL_OP_NO_COMPRESSION);
6045#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006046#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6047 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6048 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6049#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006050#ifdef SSL_OP_NO_RENEGOTIATION
6051 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6052 SSL_OP_NO_RENEGOTIATION);
6053#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006054
Christian Heimes61d478c2018-01-27 15:51:38 +01006055#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6056 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6057 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6058#endif
6059#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6060 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6061 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6062#endif
6063#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6064 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6065 X509_CHECK_FLAG_NO_WILDCARDS);
6066#endif
6067#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6068 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6069 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6070#endif
6071#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6072 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6073 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6074#endif
6075#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6076 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6077 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6078#endif
6079
Christian Heimes698dde12018-02-27 11:54:43 +01006080 /* protocol versions */
6081 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6082 PY_PROTO_MINIMUM_SUPPORTED);
6083 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6084 PY_PROTO_MAXIMUM_SUPPORTED);
6085 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6086 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6087 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6088 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6089 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006090
Victor Stinnerb37672d2018-11-22 03:37:50 +01006091#define addbool(m, key, value) \
6092 do { \
6093 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6094 Py_INCREF(bool_obj); \
6095 PyModule_AddObject((m), (key), bool_obj); \
6096 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006097
6098#if HAVE_SNI
6099 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006100#else
Christian Heimes698dde12018-02-27 11:54:43 +01006101 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006102#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006103
6104 addbool(m, "HAS_TLS_UNIQUE", 1);
6105
6106#ifndef OPENSSL_NO_ECDH
6107 addbool(m, "HAS_ECDH", 1);
6108#else
6109 addbool(m, "HAS_ECDH", 0);
6110#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006111
Christian Heimes29eab552018-02-25 12:31:33 +01006112#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006113 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006114#else
Christian Heimes698dde12018-02-27 11:54:43 +01006115 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006116#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006117
Christian Heimes29eab552018-02-25 12:31:33 +01006118#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006119 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006120#else
Christian Heimes698dde12018-02-27 11:54:43 +01006121 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006122#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006123
6124#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6125 addbool(m, "HAS_SSLv2", 1);
6126#else
6127 addbool(m, "HAS_SSLv2", 0);
6128#endif
6129
6130#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6131 addbool(m, "HAS_SSLv3", 1);
6132#else
6133 addbool(m, "HAS_SSLv3", 0);
6134#endif
6135
6136#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6137 addbool(m, "HAS_TLSv1", 1);
6138#else
6139 addbool(m, "HAS_TLSv1", 0);
6140#endif
6141
6142#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6143 addbool(m, "HAS_TLSv1_1", 1);
6144#else
6145 addbool(m, "HAS_TLSv1_1", 0);
6146#endif
6147
6148#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6149 addbool(m, "HAS_TLSv1_2", 1);
6150#else
6151 addbool(m, "HAS_TLSv1_2", 0);
6152#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006153
Christian Heimescb5b68a2017-09-07 18:07:00 -07006154#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006155 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006156#else
Christian Heimes698dde12018-02-27 11:54:43 +01006157 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006158#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006159
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006160 /* Mappings for error codes */
6161 err_codes_to_names = PyDict_New();
6162 err_names_to_codes = PyDict_New();
6163 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6164 return NULL;
6165 errcode = error_codes;
6166 while (errcode->mnemonic != NULL) {
6167 PyObject *mnemo, *key;
6168 mnemo = PyUnicode_FromString(errcode->mnemonic);
6169 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6170 if (mnemo == NULL || key == NULL)
6171 return NULL;
6172 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6173 return NULL;
6174 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6175 return NULL;
6176 Py_DECREF(key);
6177 Py_DECREF(mnemo);
6178 errcode++;
6179 }
6180 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6181 return NULL;
6182 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6183 return NULL;
6184
6185 lib_codes_to_names = PyDict_New();
6186 if (lib_codes_to_names == NULL)
6187 return NULL;
6188 libcode = library_codes;
6189 while (libcode->library != NULL) {
6190 PyObject *mnemo, *key;
6191 key = PyLong_FromLong(libcode->code);
6192 mnemo = PyUnicode_FromString(libcode->library);
6193 if (key == NULL || mnemo == NULL)
6194 return NULL;
6195 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6196 return NULL;
6197 Py_DECREF(key);
6198 Py_DECREF(mnemo);
6199 libcode++;
6200 }
6201 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6202 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006204 /* OpenSSL version */
6205 /* SSLeay() gives us the version of the library linked against,
6206 which could be different from the headers version.
6207 */
6208 libver = SSLeay();
6209 r = PyLong_FromUnsignedLong(libver);
6210 if (r == NULL)
6211 return NULL;
6212 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6213 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006214 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006215 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6216 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6217 return NULL;
6218 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6219 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6220 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006221
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006222 libver = OPENSSL_VERSION_NUMBER;
6223 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6224 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6225 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6226 return NULL;
6227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006228 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006229}