blob: fff1a28843d0564fb667cbfe8093805a960bf52c [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"
Miss Islington (bot)e2c0aea2018-09-17 05:18:23 -070066#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
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700140# 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
Miss Islington (bot)96177412018-02-25 04:18:43 -0800167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800172/* 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.
Miss Islington (bot)96177412018-02-25 04:18:43 -0800176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Miss Islington (bot)96177412018-02-25 04:18:43 -0800179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800182#elif defined(TLSEXT_TYPE_next_proto_neg)
Miss Islington (bot)96177412018-02-25 04:18:43 -0800183# define HAVE_NPN 1
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800184#else
Miss Islington (bot)96177412018-02-25 04:18:43 -0800185# define HAVE_NPN 0
186#endif
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800187
Victor Stinner524714e2016-07-22 17:43:59 +0200188#ifndef INVALID_SOCKET /* MS defines this */
189#define INVALID_SOCKET (-1)
190#endif
191
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700192/* 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
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700200
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
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700264#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
Miss Islington (bot)b3c4a052018-10-05 07:35:18 -0700276/* 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
Miss Islington (bot)4c842b02018-02-27 03:41:04 -0800334enum 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;
Miss Islington (bot)96177412018-02-25 04:18:43 -0800407#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
Miss Islington (bot)96177412018-02-25 04:18:43 -0800411#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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800416 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;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800423 int protocol;
Christian Heimes2756ef32018-09-23 09:22:52 +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 {
Miss Islington (bot)12296642018-09-17 12:12:13 -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;
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)12296642018-09-17 12:12:13 -0700471 err.ws = WSAGetLastError();
472 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700473#endif
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800493static 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 */
560 {Py_tp_doc, SSLError_doc},
561 {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;
593 reason_obj = PyDict_GetItem(err_codes_to_names, key);
594 Py_DECREF(key);
595 if (reason_obj == NULL) {
596 /* XXX if reason < 100, it might reflect a library number (!!) */
597 PyErr_Clear();
598 }
599 key = PyLong_FromLong(lib);
600 if (key == NULL)
601 goto fail;
602 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
603 Py_DECREF(key);
604 if (lib_obj == NULL) {
605 PyErr_Clear();
606 }
607 if (errstr == NULL)
608 errstr = ERR_reason_error_string(errcode);
609 }
610 if (errstr == NULL)
611 errstr = "unknown error";
612
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700613 /* verify code for cert validation error */
614 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
615 const char *verify_str = NULL;
616 long verify_code;
617
618 verify_code = SSL_get_verify_result(sslsock->ssl);
619 verify_code_obj = PyLong_FromLong(verify_code);
620 if (verify_code_obj == NULL) {
621 goto fail;
622 }
623
624 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700625#ifdef X509_V_ERR_HOSTNAME_MISMATCH
626 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700627 case X509_V_ERR_HOSTNAME_MISMATCH:
628 verify_obj = PyUnicode_FromFormat(
629 "Hostname mismatch, certificate is not valid for '%S'.",
630 sslsock->server_hostname
631 );
632 break;
Christian Heimes09153602017-09-08 14:47:58 -0700633#endif
634#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 case X509_V_ERR_IP_ADDRESS_MISMATCH:
636 verify_obj = PyUnicode_FromFormat(
637 "IP address mismatch, certificate is not valid for '%S'.",
638 sslsock->server_hostname
639 );
640 break;
Christian Heimes09153602017-09-08 14:47:58 -0700641#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700642 default:
643 verify_str = X509_verify_cert_error_string(verify_code);
644 if (verify_str != NULL) {
645 verify_obj = PyUnicode_FromString(verify_str);
646 } else {
647 verify_obj = Py_None;
648 Py_INCREF(verify_obj);
649 }
650 break;
651 }
652 if (verify_obj == NULL) {
653 goto fail;
654 }
655 }
656
657 if (verify_obj && reason_obj && lib_obj)
658 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
659 lib_obj, reason_obj, errstr, verify_obj,
660 lineno);
661 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200662 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
663 lib_obj, reason_obj, errstr, lineno);
664 else if (lib_obj)
665 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
666 lib_obj, errstr, lineno);
667 else
668 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200669 if (msg == NULL)
670 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100671
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200672 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100673 if (init_value == NULL)
674 goto fail;
675
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200676 err_value = PyObject_CallObject(type, init_value);
677 Py_DECREF(init_value);
678 if (err_value == NULL)
679 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100680
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200681 if (reason_obj == NULL)
682 reason_obj = Py_None;
683 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
684 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700685
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 if (lib_obj == NULL)
687 lib_obj = Py_None;
688 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
689 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700690
691 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
692 /* Only set verify code / message for SSLCertVerificationError */
693 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
694 verify_code_obj))
695 goto fail;
696 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
697 goto fail;
698 }
699
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200700 PyErr_SetObject(type, err_value);
701fail:
702 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700703 Py_XDECREF(verify_code_obj);
704 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200705}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000706
707static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700708PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000709{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200710 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711 char *errstr = NULL;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700712 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200714 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200717 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000718
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700719 if (sslsock->ssl != NULL) {
Miss Islington (bot)12296642018-09-17 12:12:13 -0700720 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000721
Miss Islington (bot)12296642018-09-17 12:12:13 -0700722 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200724 errstr = "TLS/SSL connection has been closed (EOF)";
725 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 p = PY_SSL_ERROR_ZERO_RETURN;
727 break;
728 case SSL_ERROR_WANT_READ:
729 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200730 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 p = PY_SSL_ERROR_WANT_READ;
732 break;
733 case SSL_ERROR_WANT_WRITE:
734 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200735 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 errstr = "The operation did not complete (write)";
737 break;
738 case SSL_ERROR_WANT_X509_LOOKUP:
739 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000740 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 break;
742 case SSL_ERROR_WANT_CONNECT:
743 p = PY_SSL_ERROR_WANT_CONNECT;
744 errstr = "The operation did not complete (connect)";
745 break;
746 case SSL_ERROR_SYSCALL:
747 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700749 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000751 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200752 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000753 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200754 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000755 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000756 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700757#ifdef MS_WINDOWS
Miss Islington (bot)12296642018-09-17 12:12:13 -0700758 if (err.ws) {
759 return PyErr_SetFromWindowsErr(err.ws);
760 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700761#endif
Miss Islington (bot)12296642018-09-17 12:12:13 -0700762 if (err.c) {
763 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700764 return PyErr_SetFromErrno(PyExc_OSError);
765 }
766 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200767 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000768 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200769 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000771 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200772 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000773 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 }
775 } else {
776 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 }
778 break;
779 }
780 case SSL_ERROR_SSL:
781 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700783 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200784 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000785 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700786 }
787 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
788 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
789 type = PySSLCertVerificationErrorObject;
790 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 break;
792 }
793 default:
794 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
795 errstr = "Invalid error code";
796 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700798 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000799 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000801}
802
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200804_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200806 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200808 else
809 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700810 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000811 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813}
814
Christian Heimes61d478c2018-01-27 15:51:38 +0100815/*
816 * SSL objects
817 */
818
819static int
820_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
821{
822 int retval = -1;
823 ASN1_OCTET_STRING *ip;
824 PyObject *hostname;
825 size_t len;
826
827 assert(server_hostname);
828
829 /* Disable OpenSSL's special mode with leading dot in hostname:
830 * When name starts with a dot (e.g ".example.com"), it will be
831 * matched by a certificate valid for any sub-domain of name.
832 */
833 len = strlen(server_hostname);
834 if (len == 0 || *server_hostname == '.') {
835 PyErr_SetString(
836 PyExc_ValueError,
837 "server_hostname cannot be an empty string or start with a "
838 "leading dot.");
839 return retval;
840 }
841
842 /* inet_pton is not available on all platforms. */
843 ip = a2i_IPADDRESS(server_hostname);
844 if (ip == NULL) {
845 ERR_clear_error();
846 }
847
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800848 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100849 if (hostname == NULL) {
850 goto error;
851 }
852 self->server_hostname = hostname;
853
854 /* Only send SNI extension for non-IP hostnames */
855 if (ip == NULL) {
856 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
857 _setSSLError(NULL, 0, __FILE__, __LINE__);
858 }
859 }
860 if (self->ctx->check_hostname) {
861 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
862 if (ip == NULL) {
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -0700863 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
864 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100865 _setSSLError(NULL, 0, __FILE__, __LINE__);
866 goto error;
867 }
868 } else {
869 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
870 ASN1_STRING_length(ip))) {
871 _setSSLError(NULL, 0, __FILE__, __LINE__);
872 goto error;
873 }
874 }
875 }
876 retval = 0;
877 error:
878 if (ip != NULL) {
879 ASN1_OCTET_STRING_free(ip);
880 }
881 return retval;
882}
883
Antoine Pitrou152efa22010-05-16 18:19:27 +0000884static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100885newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000886 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200887 char *server_hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800888 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200889 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000890{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000891 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100892 SSL_CTX *ctx = sslctx->ctx;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700893 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000894
Antoine Pitrou152efa22010-05-16 18:19:27 +0000895 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 if (self == NULL)
897 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100901 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700902 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200903 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700905 self->server_hostname = NULL;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700906 self->err = err;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 /* Make sure the SSL error state is initialized */
909 (void) ERR_get_state();
910 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000913 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 PySSL_END_ALLOW_THREADS
Zackery Spytz602d3072018-12-07 05:17:43 -0700915 if (self->ssl == NULL) {
916 Py_DECREF(self);
917 _setSSLError(NULL, 0, __FILE__, __LINE__);
918 return NULL;
919 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200920 SSL_set_app_data(self->ssl, self);
921 if (sock) {
922 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
923 } else {
924 /* BIOs are reference counted and SSL_set_bio borrows our reference.
925 * To prevent a double free in memory_bio_dealloc() we need to take an
926 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200927 BIO_up_ref(inbio->bio);
928 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200929 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
930 }
Miss Islington (bot)67d19682018-05-14 10:45:45 -0700931 SSL_set_mode(self->ssl,
932 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000933
Christian Heimes61d478c2018-01-27 15:51:38 +0100934 if (server_hostname != NULL) {
935 if (_ssl_configure_hostname(self, server_hostname) < 0) {
936 Py_DECREF(self);
937 return NULL;
938 }
939 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 /* If the socket is in non-blocking mode or timeout mode, set the BIO
941 * to non-blocking mode (blocking is the default)
942 */
Victor Stinnere2452312015-03-28 03:00:46 +0100943 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
945 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
946 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 PySSL_BEGIN_ALLOW_THREADS
949 if (socket_type == PY_SSL_CLIENT)
950 SSL_set_connect_state(self->ssl);
951 else
952 SSL_set_accept_state(self->ssl);
953 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000954
Antoine Pitroud6494802011-07-21 01:11:30 +0200955 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200956 if (sock != NULL) {
957 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
958 if (self->Socket == NULL) {
959 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200960 return NULL;
961 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100962 }
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800963 if (owner && owner != Py_None) {
964 if (PySSL_set_owner(self, owner, NULL) == -1) {
965 Py_DECREF(self);
966 return NULL;
967 }
968 }
969 if (session && session != Py_None) {
970 if (PySSL_set_session(self, session, NULL) == -1) {
971 Py_DECREF(self);
972 return NULL;
973 }
974 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000976}
977
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000978/* SSL object methods */
979
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300980/*[clinic input]
981_ssl._SSLSocket.do_handshake
982[clinic start generated code]*/
983
984static PyObject *
985_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
986/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000987{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 int ret;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700989 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200991 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200992 _PyTime_t timeout, deadline = 0;
993 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000994
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200995 if (sock) {
996 if (((PyObject*)sock) == Py_None) {
997 _setSSLError("Underlying socket connection gone",
998 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
999 return NULL;
1000 }
1001 Py_INCREF(sock);
1002
1003 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001004 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001005 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1006 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001008
Victor Stinner14690702015-04-06 22:46:13 +02001009 timeout = GET_SOCKET_TIMEOUT(sock);
1010 has_timeout = (timeout > 0);
1011 if (has_timeout)
1012 deadline = _PyTime_GetMonotonicClock() + timeout;
1013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 /* Actually negotiate SSL connection */
1015 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001017 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 ret = SSL_do_handshake(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001019 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07001021 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001022
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001023 if (PyErr_CheckSignals())
1024 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001025
Victor Stinner14690702015-04-06 22:46:13 +02001026 if (has_timeout)
1027 timeout = deadline - _PyTime_GetMonotonicClock();
1028
Miss Islington (bot)12296642018-09-17 12:12:13 -07001029 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001030 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001031 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001032 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 } else {
1034 sockstate = SOCKET_OPERATION_OK;
1035 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001038 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001039 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001040 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1042 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001043 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001044 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1046 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001047 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001048 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1050 break;
1051 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07001052 } while (err.ssl == SSL_ERROR_WANT_READ ||
1053 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001054 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 if (ret < 1)
1056 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001057
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001058 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001059
1060error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001061 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001062 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001063}
1064
Thomas Woutersed03b412007-08-28 21:37:11 +00001065static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001066_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1067{
1068 char buf[X509_NAME_MAXLEN];
1069 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001071 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001072
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001073 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 if (buflen < 0) {
1075 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001076 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001078 /* initial buffer is too small for oid + terminating null byte */
1079 if (buflen > X509_NAME_MAXLEN - 1) {
1080 /* make OBJ_obj2txt() calculate the required buflen */
1081 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1082 /* allocate len + 1 for terminating NULL byte */
1083 namebuf = PyMem_Malloc(buflen + 1);
1084 if (namebuf == NULL) {
1085 PyErr_NoMemory();
1086 return NULL;
1087 }
1088 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1089 if (buflen < 0) {
1090 _setSSLError(NULL, 0, __FILE__, __LINE__);
1091 goto done;
1092 }
1093 }
1094 if (!buflen && no_name) {
1095 Py_INCREF(Py_None);
1096 name_obj = Py_None;
1097 }
1098 else {
1099 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1100 }
1101
1102 done:
1103 if (buf != namebuf) {
1104 PyMem_Free(namebuf);
1105 }
1106 return name_obj;
1107}
1108
1109static PyObject *
1110_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1111{
1112 Py_ssize_t buflen;
1113 unsigned char *valuebuf = NULL;
1114 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001115
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1117 if (buflen < 0) {
1118 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001119 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001121 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001124}
1125
1126static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001128{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1130 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1131 PyObject *rdnt;
1132 PyObject *attr = NULL; /* tuple to hold an attribute */
1133 int entry_count = X509_NAME_entry_count(xname);
1134 X509_NAME_ENTRY *entry;
1135 ASN1_OBJECT *name;
1136 ASN1_STRING *value;
1137 int index_counter;
1138 int rdn_level = -1;
1139 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 dn = PyList_New(0);
1142 if (dn == NULL)
1143 return NULL;
1144 /* now create another tuple to hold the top-level RDN */
1145 rdn = PyList_New(0);
1146 if (rdn == NULL)
1147 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 for (index_counter = 0;
1150 index_counter < entry_count;
1151 index_counter++)
1152 {
1153 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 /* check to see if we've gotten to a new RDN */
1156 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001157 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 /* yes, new RDN */
1159 /* add old RDN to DN */
1160 rdnt = PyList_AsTuple(rdn);
1161 Py_DECREF(rdn);
1162 if (rdnt == NULL)
1163 goto fail0;
1164 retcode = PyList_Append(dn, rdnt);
1165 Py_DECREF(rdnt);
1166 if (retcode < 0)
1167 goto fail0;
1168 /* create new RDN */
1169 rdn = PyList_New(0);
1170 if (rdn == NULL)
1171 goto fail0;
1172 }
1173 }
Christian Heimes598894f2016-09-05 23:19:05 +02001174 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 /* now add this attribute to the current RDN */
1177 name = X509_NAME_ENTRY_get_object(entry);
1178 value = X509_NAME_ENTRY_get_data(entry);
1179 attr = _create_tuple_for_attribute(name, value);
1180 /*
1181 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1182 entry->set,
1183 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1184 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1185 */
1186 if (attr == NULL)
1187 goto fail1;
1188 retcode = PyList_Append(rdn, attr);
1189 Py_DECREF(attr);
1190 if (retcode < 0)
1191 goto fail1;
1192 }
1193 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001194 if (rdn != NULL) {
1195 if (PyList_GET_SIZE(rdn) > 0) {
1196 rdnt = PyList_AsTuple(rdn);
1197 Py_DECREF(rdn);
1198 if (rdnt == NULL)
1199 goto fail0;
1200 retcode = PyList_Append(dn, rdnt);
1201 Py_DECREF(rdnt);
1202 if (retcode < 0)
1203 goto fail0;
1204 }
1205 else {
1206 Py_DECREF(rdn);
1207 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 /* convert list to tuple */
1211 rdnt = PyList_AsTuple(dn);
1212 Py_DECREF(dn);
1213 if (rdnt == NULL)
1214 return NULL;
1215 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216
1217 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219
1220 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 Py_XDECREF(dn);
1222 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001223}
1224
1225static PyObject *
1226_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 /* this code follows the procedure outlined in
1229 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1230 function to extract the STACK_OF(GENERAL_NAME),
1231 then iterates through the stack to add the
1232 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001233
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001234 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001236 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 GENERAL_NAMES *names = NULL;
1238 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 BIO *biobuf = NULL;
1240 char buf[2048];
1241 char *vptr;
1242 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 if (certificate == NULL)
1245 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 /* get a memory buffer */
1248 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz602d3072018-12-07 05:17:43 -07001249 if (biobuf == NULL) {
1250 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1251 return NULL;
1252 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001254 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1255 certificate, NID_subject_alt_name, NULL, NULL);
1256 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 if (peer_alt_names == Py_None) {
1258 peer_alt_names = PyList_New(0);
1259 if (peer_alt_names == NULL)
1260 goto fail;
1261 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001265 int gntype;
1266 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001269 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001270 switch (gntype) {
1271 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 /* we special-case DirName as a tuple of
1273 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 t = PyTuple_New(2);
1276 if (t == NULL) {
1277 goto fail;
1278 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 v = PyUnicode_FromString("DirName");
1281 if (v == NULL) {
1282 Py_DECREF(t);
1283 goto fail;
1284 }
1285 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 v = _create_tuple_for_X509_NAME (name->d.dirn);
1288 if (v == NULL) {
1289 Py_DECREF(t);
1290 goto fail;
1291 }
1292 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001293 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001294
Christian Heimes824f7f32013-08-17 00:54:47 +02001295 case GEN_EMAIL:
1296 case GEN_DNS:
1297 case GEN_URI:
1298 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1299 correctly, CVE-2013-4238 */
1300 t = PyTuple_New(2);
1301 if (t == NULL)
1302 goto fail;
1303 switch (gntype) {
1304 case GEN_EMAIL:
1305 v = PyUnicode_FromString("email");
1306 as = name->d.rfc822Name;
1307 break;
1308 case GEN_DNS:
1309 v = PyUnicode_FromString("DNS");
1310 as = name->d.dNSName;
1311 break;
1312 case GEN_URI:
1313 v = PyUnicode_FromString("URI");
1314 as = name->d.uniformResourceIdentifier;
1315 break;
1316 }
1317 if (v == NULL) {
1318 Py_DECREF(t);
1319 goto fail;
1320 }
1321 PyTuple_SET_ITEM(t, 0, v);
1322 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1323 ASN1_STRING_length(as));
1324 if (v == NULL) {
1325 Py_DECREF(t);
1326 goto fail;
1327 }
1328 PyTuple_SET_ITEM(t, 1, v);
1329 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Christian Heimes1c03abd2016-09-06 23:25:35 +02001331 case GEN_RID:
1332 t = PyTuple_New(2);
1333 if (t == NULL)
1334 goto fail;
1335
1336 v = PyUnicode_FromString("Registered ID");
1337 if (v == NULL) {
1338 Py_DECREF(t);
1339 goto fail;
1340 }
1341 PyTuple_SET_ITEM(t, 0, v);
1342
1343 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1344 if (len < 0) {
1345 Py_DECREF(t);
1346 _setSSLError(NULL, 0, __FILE__, __LINE__);
1347 goto fail;
1348 } else if (len >= (int)sizeof(buf)) {
1349 v = PyUnicode_FromString("<INVALID>");
1350 } else {
1351 v = PyUnicode_FromStringAndSize(buf, len);
1352 }
1353 if (v == NULL) {
1354 Py_DECREF(t);
1355 goto fail;
1356 }
1357 PyTuple_SET_ITEM(t, 1, v);
1358 break;
1359
Christian Heimes824f7f32013-08-17 00:54:47 +02001360 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001362 switch (gntype) {
1363 /* check for new general name type */
1364 case GEN_OTHERNAME:
1365 case GEN_X400:
1366 case GEN_EDIPARTY:
1367 case GEN_IPADD:
1368 case GEN_RID:
1369 break;
1370 default:
1371 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1372 "Unknown general name type %d",
1373 gntype) == -1) {
1374 goto fail;
1375 }
1376 break;
1377 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 (void) BIO_reset(biobuf);
1379 GENERAL_NAME_print(biobuf, name);
1380 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1381 if (len < 0) {
1382 _setSSLError(NULL, 0, __FILE__, __LINE__);
1383 goto fail;
1384 }
1385 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001386 if (vptr == NULL) {
1387 PyErr_Format(PyExc_ValueError,
1388 "Invalid value %.200s",
1389 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001391 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 t = PyTuple_New(2);
1393 if (t == NULL)
1394 goto fail;
1395 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1396 if (v == NULL) {
1397 Py_DECREF(t);
1398 goto fail;
1399 }
1400 PyTuple_SET_ITEM(t, 0, v);
1401 v = PyUnicode_FromStringAndSize((vptr + 1),
1402 (len - (vptr - buf + 1)));
1403 if (v == NULL) {
1404 Py_DECREF(t);
1405 goto fail;
1406 }
1407 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001408 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 if (PyList_Append(peer_alt_names, t) < 0) {
1414 Py_DECREF(t);
1415 goto fail;
1416 }
1417 Py_DECREF(t);
1418 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001419 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 }
1421 BIO_free(biobuf);
1422 if (peer_alt_names != Py_None) {
1423 v = PyList_AsTuple(peer_alt_names);
1424 Py_DECREF(peer_alt_names);
1425 return v;
1426 } else {
1427 return peer_alt_names;
1428 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001429
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001430
1431 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001432 if (biobuf != NULL)
1433 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001434
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 if (peer_alt_names != Py_None) {
1436 Py_XDECREF(peer_alt_names);
1437 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440}
1441
1442static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001443_get_aia_uri(X509 *certificate, int nid) {
1444 PyObject *lst = NULL, *ostr = NULL;
1445 int i, result;
1446 AUTHORITY_INFO_ACCESS *info;
1447
1448 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001449 if (info == NULL)
1450 return Py_None;
1451 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1452 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001453 return Py_None;
1454 }
1455
1456 if ((lst = PyList_New(0)) == NULL) {
1457 goto fail;
1458 }
1459
1460 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1461 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1462 ASN1_IA5STRING *uri;
1463
1464 if ((OBJ_obj2nid(ad->method) != nid) ||
1465 (ad->location->type != GEN_URI)) {
1466 continue;
1467 }
1468 uri = ad->location->d.uniformResourceIdentifier;
1469 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1470 uri->length);
1471 if (ostr == NULL) {
1472 goto fail;
1473 }
1474 result = PyList_Append(lst, ostr);
1475 Py_DECREF(ostr);
1476 if (result < 0) {
1477 goto fail;
1478 }
1479 }
1480 AUTHORITY_INFO_ACCESS_free(info);
1481
1482 /* convert to tuple or None */
1483 if (PyList_Size(lst) == 0) {
1484 Py_DECREF(lst);
1485 return Py_None;
1486 } else {
1487 PyObject *tup;
1488 tup = PyList_AsTuple(lst);
1489 Py_DECREF(lst);
1490 return tup;
1491 }
1492
1493 fail:
1494 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001495 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001496 return NULL;
1497}
1498
1499static PyObject *
1500_get_crl_dp(X509 *certificate) {
1501 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001502 int i, j;
1503 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504
Christian Heimes598894f2016-09-05 23:19:05 +02001505 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001506
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001507 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001508 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001509
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001510 lst = PyList_New(0);
1511 if (lst == NULL)
1512 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001513
1514 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1515 DIST_POINT *dp;
1516 STACK_OF(GENERAL_NAME) *gns;
1517
1518 dp = sk_DIST_POINT_value(dps, i);
Miss Islington (bot)be5de952019-01-15 15:03:36 -08001519 if (dp->distpoint == NULL) {
1520 /* Ignore empty DP value, CVE-2019-5010 */
1521 continue;
1522 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001523 gns = dp->distpoint->name.fullname;
1524
1525 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1526 GENERAL_NAME *gn;
1527 ASN1_IA5STRING *uri;
1528 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001529 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001530
1531 gn = sk_GENERAL_NAME_value(gns, j);
1532 if (gn->type != GEN_URI) {
1533 continue;
1534 }
1535 uri = gn->d.uniformResourceIdentifier;
1536 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1537 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001538 if (ouri == NULL)
1539 goto done;
1540
1541 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001542 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001543 if (err < 0)
1544 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001545 }
1546 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001547
1548 /* Convert to tuple. */
1549 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1550
1551 done:
1552 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001553 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001554 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001555}
1556
1557static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001558_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560 PyObject *retval = NULL;
1561 BIO *biobuf = NULL;
1562 PyObject *peer;
1563 PyObject *peer_alt_names = NULL;
1564 PyObject *issuer;
1565 PyObject *version;
1566 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001567 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 ASN1_INTEGER *serialNumber;
1569 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001570 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 ASN1_TIME *notBefore, *notAfter;
1572 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 retval = PyDict_New();
1575 if (retval == NULL)
1576 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001577
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578 peer = _create_tuple_for_X509_NAME(
1579 X509_get_subject_name(certificate));
1580 if (peer == NULL)
1581 goto fail0;
1582 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1583 Py_DECREF(peer);
1584 goto fail0;
1585 }
1586 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001587
Antoine Pitroufb046912010-11-09 20:21:19 +00001588 issuer = _create_tuple_for_X509_NAME(
1589 X509_get_issuer_name(certificate));
1590 if (issuer == NULL)
1591 goto fail0;
1592 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001594 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001595 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001596 Py_DECREF(issuer);
1597
1598 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001599 if (version == NULL)
1600 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001601 if (PyDict_SetItemString(retval, "version", version) < 0) {
1602 Py_DECREF(version);
1603 goto fail0;
1604 }
1605 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 /* get a memory buffer */
1608 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz602d3072018-12-07 05:17:43 -07001609 if (biobuf == NULL) {
1610 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1611 goto fail0;
1612 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001613
Antoine Pitroufb046912010-11-09 20:21:19 +00001614 (void) BIO_reset(biobuf);
1615 serialNumber = X509_get_serialNumber(certificate);
1616 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1617 i2a_ASN1_INTEGER(biobuf, serialNumber);
1618 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1619 if (len < 0) {
1620 _setSSLError(NULL, 0, __FILE__, __LINE__);
1621 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001622 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001623 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1624 if (sn_obj == NULL)
1625 goto fail1;
1626 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1627 Py_DECREF(sn_obj);
1628 goto fail1;
1629 }
1630 Py_DECREF(sn_obj);
1631
1632 (void) BIO_reset(biobuf);
1633 notBefore = X509_get_notBefore(certificate);
1634 ASN1_TIME_print(biobuf, notBefore);
1635 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1636 if (len < 0) {
1637 _setSSLError(NULL, 0, __FILE__, __LINE__);
1638 goto fail1;
1639 }
1640 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1641 if (pnotBefore == NULL)
1642 goto fail1;
1643 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1644 Py_DECREF(pnotBefore);
1645 goto fail1;
1646 }
1647 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001649 (void) BIO_reset(biobuf);
1650 notAfter = X509_get_notAfter(certificate);
1651 ASN1_TIME_print(biobuf, notAfter);
1652 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1653 if (len < 0) {
1654 _setSSLError(NULL, 0, __FILE__, __LINE__);
1655 goto fail1;
1656 }
1657 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1658 if (pnotAfter == NULL)
1659 goto fail1;
1660 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1661 Py_DECREF(pnotAfter);
1662 goto fail1;
1663 }
1664 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001668 peer_alt_names = _get_peer_alt_names(certificate);
1669 if (peer_alt_names == NULL)
1670 goto fail1;
1671 else if (peer_alt_names != Py_None) {
1672 if (PyDict_SetItemString(retval, "subjectAltName",
1673 peer_alt_names) < 0) {
1674 Py_DECREF(peer_alt_names);
1675 goto fail1;
1676 }
1677 Py_DECREF(peer_alt_names);
1678 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001679
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001680 /* Authority Information Access: OCSP URIs */
1681 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1682 if (obj == NULL) {
1683 goto fail1;
1684 } else if (obj != Py_None) {
1685 result = PyDict_SetItemString(retval, "OCSP", obj);
1686 Py_DECREF(obj);
1687 if (result < 0) {
1688 goto fail1;
1689 }
1690 }
1691
1692 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1693 if (obj == NULL) {
1694 goto fail1;
1695 } else if (obj != Py_None) {
1696 result = PyDict_SetItemString(retval, "caIssuers", obj);
1697 Py_DECREF(obj);
1698 if (result < 0) {
1699 goto fail1;
1700 }
1701 }
1702
1703 /* CDP (CRL distribution points) */
1704 obj = _get_crl_dp(certificate);
1705 if (obj == NULL) {
1706 goto fail1;
1707 } else if (obj != Py_None) {
1708 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1709 Py_DECREF(obj);
1710 if (result < 0) {
1711 goto fail1;
1712 }
1713 }
1714
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 BIO_free(biobuf);
1716 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001717
1718 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 if (biobuf != NULL)
1720 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001721 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 Py_XDECREF(retval);
1723 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001724}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001725
Christian Heimes9a5395a2013-06-17 15:44:12 +02001726static PyObject *
1727_certificate_to_der(X509 *certificate)
1728{
1729 unsigned char *bytes_buf = NULL;
1730 int len;
1731 PyObject *retval;
1732
1733 bytes_buf = NULL;
1734 len = i2d_X509(certificate, &bytes_buf);
1735 if (len < 0) {
1736 _setSSLError(NULL, 0, __FILE__, __LINE__);
1737 return NULL;
1738 }
1739 /* this is actually an immutable bytes sequence */
1740 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1741 OPENSSL_free(bytes_buf);
1742 return retval;
1743}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745/*[clinic input]
1746_ssl._test_decode_cert
1747 path: object(converter="PyUnicode_FSConverter")
1748 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001750[clinic start generated code]*/
1751
1752static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001753_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1754/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001755{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 X509 *x=NULL;
1758 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1761 PyErr_SetString(PySSLErrorObject,
1762 "Can't malloc memory to read file");
1763 goto fail0;
1764 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001766 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001767 PyErr_SetString(PySSLErrorObject,
1768 "Can't open file");
1769 goto fail0;
1770 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001771
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1773 if (x == NULL) {
1774 PyErr_SetString(PySSLErrorObject,
1775 "Error decoding PEM-encoded file");
1776 goto fail0;
1777 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001778
Antoine Pitroufb046912010-11-09 20:21:19 +00001779 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001780 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781
1782 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001783 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001784 if (cert != NULL) BIO_free(cert);
1785 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001786}
1787
1788
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001789/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001790_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001791 der as binary_mode: bool = False
1792 /
1793
1794Returns the certificate for the peer.
1795
1796If no certificate was provided, returns None. If a certificate was
1797provided, but not validated, returns an empty dictionary. Otherwise
1798returns a dict containing information about the peer certificate.
1799
1800If the optional argument is True, returns a DER-encoded copy of the
1801peer certificate, or None if no certificate was provided. This will
1802return the certificate even if it wasn't validated.
1803[clinic start generated code]*/
1804
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001805static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001806_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1807/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001808{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001810 X509 *peer_cert;
1811 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001812
Christian Heimes66dc33b2017-05-23 16:02:02 -07001813 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001814 PyErr_SetString(PyExc_ValueError,
1815 "handshake not done yet");
1816 return NULL;
1817 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001818 peer_cert = SSL_get_peer_certificate(self->ssl);
1819 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001821
Antoine Pitrou721738f2012-08-15 23:20:39 +02001822 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001824 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001826 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001828 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001830 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001832 X509_free(peer_cert);
1833 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001834}
1835
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001836static PyObject *
1837cipher_to_tuple(const SSL_CIPHER *cipher)
1838{
1839 const char *cipher_name, *cipher_protocol;
1840 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 if (retval == NULL)
1842 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001843
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001844 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001846 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 PyTuple_SET_ITEM(retval, 0, Py_None);
1848 } else {
1849 v = PyUnicode_FromString(cipher_name);
1850 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001851 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 PyTuple_SET_ITEM(retval, 0, v);
1853 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001854
1855 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001857 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 PyTuple_SET_ITEM(retval, 1, Py_None);
1859 } else {
1860 v = PyUnicode_FromString(cipher_protocol);
1861 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001862 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 PyTuple_SET_ITEM(retval, 1, v);
1864 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001865
1866 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001868 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001870
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001872
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001873 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 Py_DECREF(retval);
1875 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001876}
1877
Christian Heimes25bfcd52016-09-06 00:04:45 +02001878#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1879static PyObject *
1880cipher_to_dict(const SSL_CIPHER *cipher)
1881{
1882 const char *cipher_name, *cipher_protocol;
1883
1884 unsigned long cipher_id;
1885 int alg_bits, strength_bits, len;
1886 char buf[512] = {0};
1887#if OPENSSL_VERSION_1_1
1888 int aead, nid;
1889 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1890#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001891
1892 /* can be NULL */
1893 cipher_name = SSL_CIPHER_get_name(cipher);
1894 cipher_protocol = SSL_CIPHER_get_version(cipher);
1895 cipher_id = SSL_CIPHER_get_id(cipher);
1896 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001897 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1898 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001899 if (len > 1 && buf[len-1] == '\n')
1900 buf[len-1] = '\0';
1901 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1902
1903#if OPENSSL_VERSION_1_1
1904 aead = SSL_CIPHER_is_aead(cipher);
1905 nid = SSL_CIPHER_get_cipher_nid(cipher);
1906 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1907 nid = SSL_CIPHER_get_digest_nid(cipher);
1908 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1909 nid = SSL_CIPHER_get_kx_nid(cipher);
1910 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1911 nid = SSL_CIPHER_get_auth_nid(cipher);
1912 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1913#endif
1914
Victor Stinner410b9882016-09-12 12:00:23 +02001915 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001916 "{sksssssssisi"
1917#if OPENSSL_VERSION_1_1
1918 "sOssssssss"
1919#endif
1920 "}",
1921 "id", cipher_id,
1922 "name", cipher_name,
1923 "protocol", cipher_protocol,
1924 "description", buf,
1925 "strength_bits", strength_bits,
1926 "alg_bits", alg_bits
1927#if OPENSSL_VERSION_1_1
1928 ,"aead", aead ? Py_True : Py_False,
1929 "symmetric", skcipher,
1930 "digest", digest,
1931 "kea", kx,
1932 "auth", auth
1933#endif
1934 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001935}
1936#endif
1937
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001938/*[clinic input]
1939_ssl._SSLSocket.shared_ciphers
1940[clinic start generated code]*/
1941
1942static PyObject *
1943_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1944/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001945{
1946 STACK_OF(SSL_CIPHER) *ciphers;
1947 int i;
1948 PyObject *res;
1949
Christian Heimes598894f2016-09-05 23:19:05 +02001950 ciphers = SSL_get_ciphers(self->ssl);
1951 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001952 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001953 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1954 if (!res)
1955 return NULL;
1956 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1957 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1958 if (!tup) {
1959 Py_DECREF(res);
1960 return NULL;
1961 }
1962 PyList_SET_ITEM(res, i, tup);
1963 }
1964 return res;
1965}
1966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001967/*[clinic input]
1968_ssl._SSLSocket.cipher
1969[clinic start generated code]*/
1970
1971static PyObject *
1972_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1973/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001974{
1975 const SSL_CIPHER *current;
1976
1977 if (self->ssl == NULL)
1978 Py_RETURN_NONE;
1979 current = SSL_get_current_cipher(self->ssl);
1980 if (current == NULL)
1981 Py_RETURN_NONE;
1982 return cipher_to_tuple(current);
1983}
1984
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001985/*[clinic input]
1986_ssl._SSLSocket.version
1987[clinic start generated code]*/
1988
1989static PyObject *
1990_ssl__SSLSocket_version_impl(PySSLSocket *self)
1991/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001992{
1993 const char *version;
1994
1995 if (self->ssl == NULL)
1996 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001997 if (!SSL_is_init_finished(self->ssl)) {
1998 /* handshake not finished */
1999 Py_RETURN_NONE;
2000 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002001 version = SSL_get_version(self->ssl);
2002 if (!strcmp(version, "unknown"))
2003 Py_RETURN_NONE;
2004 return PyUnicode_FromString(version);
2005}
2006
Miss Islington (bot)96177412018-02-25 04:18:43 -08002007#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002008/*[clinic input]
2009_ssl._SSLSocket.selected_npn_protocol
2010[clinic start generated code]*/
2011
2012static PyObject *
2013_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2014/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2015{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002016 const unsigned char *out;
2017 unsigned int outlen;
2018
Victor Stinner4569cd52013-06-23 14:58:43 +02002019 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002020 &out, &outlen);
2021
2022 if (out == NULL)
2023 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002024 return PyUnicode_FromStringAndSize((char *)out, outlen);
2025}
2026#endif
2027
Miss Islington (bot)96177412018-02-25 04:18:43 -08002028#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029/*[clinic input]
2030_ssl._SSLSocket.selected_alpn_protocol
2031[clinic start generated code]*/
2032
2033static PyObject *
2034_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2035/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2036{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002037 const unsigned char *out;
2038 unsigned int outlen;
2039
2040 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2041
2042 if (out == NULL)
2043 Py_RETURN_NONE;
2044 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002045}
2046#endif
2047
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002048/*[clinic input]
2049_ssl._SSLSocket.compression
2050[clinic start generated code]*/
2051
2052static PyObject *
2053_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2054/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2055{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002056#ifdef OPENSSL_NO_COMP
2057 Py_RETURN_NONE;
2058#else
2059 const COMP_METHOD *comp_method;
2060 const char *short_name;
2061
2062 if (self->ssl == NULL)
2063 Py_RETURN_NONE;
2064 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002065 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002066 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002067 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002068 if (short_name == NULL)
2069 Py_RETURN_NONE;
2070 return PyUnicode_DecodeFSDefault(short_name);
2071#endif
2072}
2073
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002074static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2075 Py_INCREF(self->ctx);
2076 return self->ctx;
2077}
2078
2079static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2080 void *closure) {
2081
2082 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002083#if !HAVE_SNI
2084 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2085 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002086 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002087#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002088 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002089 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002090 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002091#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002092 } else {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002093 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002094 return -1;
2095 }
2096
2097 return 0;
2098}
2099
2100PyDoc_STRVAR(PySSL_set_context_doc,
2101"_setter_context(ctx)\n\
2102\
2103This changes the context associated with the SSLSocket. This is typically\n\
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002104used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002105on the SSLContext to change the certificate information associated with the\n\
2106SSLSocket before the cryptographic exchange handshake messages\n");
2107
2108
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002109static PyObject *
2110PySSL_get_server_side(PySSLSocket *self, void *c)
2111{
2112 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2113}
2114
2115PyDoc_STRVAR(PySSL_get_server_side_doc,
2116"Whether this is a server-side socket.");
2117
2118static PyObject *
2119PySSL_get_server_hostname(PySSLSocket *self, void *c)
2120{
2121 if (self->server_hostname == NULL)
2122 Py_RETURN_NONE;
2123 Py_INCREF(self->server_hostname);
2124 return self->server_hostname;
2125}
2126
2127PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2128"The currently set server hostname (for SNI).");
2129
2130static PyObject *
2131PySSL_get_owner(PySSLSocket *self, void *c)
2132{
2133 PyObject *owner;
2134
2135 if (self->owner == NULL)
2136 Py_RETURN_NONE;
2137
2138 owner = PyWeakref_GetObject(self->owner);
2139 Py_INCREF(owner);
2140 return owner;
2141}
2142
2143static int
2144PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2145{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002146 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002147 if (self->owner == NULL)
2148 return -1;
2149 return 0;
2150}
2151
2152PyDoc_STRVAR(PySSL_get_owner_doc,
2153"The Python-level owner of this object.\
2154Passed as \"self\" in servername callback.");
2155
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002156
Antoine Pitrou152efa22010-05-16 18:19:27 +00002157static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002158{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 if (self->ssl)
2160 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002162 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002163 Py_XDECREF(self->server_hostname);
2164 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002166}
2167
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002168/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002169 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002170 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002171 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002172
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002173static int
Victor Stinner14690702015-04-06 22:46:13 +02002174PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002175{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002176 int rc;
2177#ifdef HAVE_POLL
2178 struct pollfd pollfd;
2179 _PyTime_t ms;
2180#else
2181 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002182 fd_set fds;
2183 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002184#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002187 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002189 else if (timeout < 0) {
2190 if (s->sock_timeout > 0)
2191 return SOCKET_HAS_TIMED_OUT;
2192 else
2193 return SOCKET_IS_BLOCKING;
2194 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002197 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 /* Prefer poll, if available, since you can poll() any fd
2201 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002202#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002203 pollfd.fd = s->sock_fd;
2204 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002205
Victor Stinner14690702015-04-06 22:46:13 +02002206 /* timeout is in seconds, poll() uses milliseconds */
2207 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002208 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002209
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002210 PySSL_BEGIN_ALLOW_THREADS
2211 rc = poll(&pollfd, 1, (int)ms);
2212 PySSL_END_ALLOW_THREADS
2213#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002215 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002217
Victor Stinner14690702015-04-06 22:46:13 +02002218 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 FD_ZERO(&fds);
2221 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002222
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002223 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002225 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002227 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002229 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002231#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002232
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2234 (when we are able to write or when there's something to read) */
2235 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002236}
2237
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002238/*[clinic input]
2239_ssl._SSLSocket.write
2240 b: Py_buffer
2241 /
2242
2243Writes the bytes-like object b into the SSL object.
2244
2245Returns the number of bytes written.
2246[clinic start generated code]*/
2247
2248static PyObject *
2249_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2250/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002251{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 int len;
2253 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002254 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002255 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002256 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002257 _PyTime_t timeout, deadline = 0;
2258 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002259
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002260 if (sock != NULL) {
2261 if (((PyObject*)sock) == Py_None) {
2262 _setSSLError("Underlying socket connection gone",
2263 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2264 return NULL;
2265 }
2266 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 }
2268
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002269 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002270 PyErr_Format(PyExc_OverflowError,
2271 "string longer than %d bytes", INT_MAX);
2272 goto error;
2273 }
2274
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002275 if (sock != NULL) {
2276 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002277 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002278 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2279 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2280 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281
Victor Stinner14690702015-04-06 22:46:13 +02002282 timeout = GET_SOCKET_TIMEOUT(sock);
2283 has_timeout = (timeout > 0);
2284 if (has_timeout)
2285 deadline = _PyTime_GetMonotonicClock() + timeout;
2286
2287 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002289 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 "The write operation timed out");
2291 goto error;
2292 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2293 PyErr_SetString(PySSLErrorObject,
2294 "Underlying socket has been closed.");
2295 goto error;
2296 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2297 PyErr_SetString(PySSLErrorObject,
2298 "Underlying socket too large for select().");
2299 goto error;
2300 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002304 len = SSL_write(self->ssl, b->buf, (int)b->len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002305 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002307 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002308
2309 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002310 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002311
Victor Stinner14690702015-04-06 22:46:13 +02002312 if (has_timeout)
2313 timeout = deadline - _PyTime_GetMonotonicClock();
2314
Miss Islington (bot)12296642018-09-17 12:12:13 -07002315 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002316 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002317 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002318 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 } else {
2320 sockstate = SOCKET_OPERATION_OK;
2321 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002324 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002325 "The write operation timed out");
2326 goto error;
2327 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2328 PyErr_SetString(PySSLErrorObject,
2329 "Underlying socket has been closed.");
2330 goto error;
2331 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2332 break;
2333 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002334 } while (err.ssl == SSL_ERROR_WANT_READ ||
2335 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002336
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002337 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 if (len > 0)
2339 return PyLong_FromLong(len);
2340 else
2341 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002342
2343error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002344 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002346}
2347
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002348/*[clinic input]
2349_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002350
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002351Returns the number of already decrypted bytes available for read, pending on the connection.
2352[clinic start generated code]*/
2353
2354static PyObject *
2355_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2356/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002357{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 int count = 0;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002359 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 PySSL_BEGIN_ALLOW_THREADS
2362 count = SSL_pending(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002363 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002365 self->err = err;
2366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002367 if (count < 0)
2368 return PySSL_SetError(self, count, __FILE__, __LINE__);
2369 else
2370 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002371}
2372
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002373/*[clinic input]
2374_ssl._SSLSocket.read
2375 size as len: int
2376 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002377 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002378 ]
2379 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002380
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002381Read up to size bytes from the SSL socket.
2382[clinic start generated code]*/
2383
2384static PyObject *
2385_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2386 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002387/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002388{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002389 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002391 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002393 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002395 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002396 _PyTime_t timeout, deadline = 0;
2397 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002398
Martin Panter5503d472016-03-27 05:35:19 +00002399 if (!group_right_1 && len < 0) {
2400 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2401 return NULL;
2402 }
2403
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002404 if (sock != NULL) {
2405 if (((PyObject*)sock) == Py_None) {
2406 _setSSLError("Underlying socket connection gone",
2407 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2408 return NULL;
2409 }
2410 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002411 }
2412
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002413 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002414 dest = PyBytes_FromStringAndSize(NULL, len);
2415 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002416 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002417 if (len == 0) {
2418 Py_XDECREF(sock);
2419 return dest;
2420 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002421 mem = PyBytes_AS_STRING(dest);
2422 }
2423 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002424 mem = buffer->buf;
2425 if (len <= 0 || len > buffer->len) {
2426 len = (int) buffer->len;
2427 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002428 PyErr_SetString(PyExc_OverflowError,
2429 "maximum length can't fit in a C 'int'");
2430 goto error;
2431 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002432 if (len == 0) {
2433 count = 0;
2434 goto done;
2435 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002436 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 }
2438
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002439 if (sock != NULL) {
2440 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002441 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002442 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2443 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2444 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445
Victor Stinner14690702015-04-06 22:46:13 +02002446 timeout = GET_SOCKET_TIMEOUT(sock);
2447 has_timeout = (timeout > 0);
2448 if (has_timeout)
2449 deadline = _PyTime_GetMonotonicClock() + timeout;
2450
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 PySSL_BEGIN_ALLOW_THREADS
2453 count = SSL_read(self->ssl, mem, len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002454 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002456 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002457
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002458 if (PyErr_CheckSignals())
2459 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002460
Victor Stinner14690702015-04-06 22:46:13 +02002461 if (has_timeout)
2462 timeout = deadline - _PyTime_GetMonotonicClock();
2463
Miss Islington (bot)12296642018-09-17 12:12:13 -07002464 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002465 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002466 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002467 sockstate = PySSL_select(sock, 1, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002468 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002469 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 {
2471 count = 0;
2472 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002473 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002474 else
2475 sockstate = SOCKET_OPERATION_OK;
2476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002478 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 "The read operation timed out");
2480 goto error;
2481 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2482 break;
2483 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002484 } while (err.ssl == SSL_ERROR_WANT_READ ||
2485 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 if (count <= 0) {
2488 PySSL_SetError(self, count, __FILE__, __LINE__);
2489 goto error;
2490 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002491
2492done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002493 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002494 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002495 _PyBytes_Resize(&dest, count);
2496 return dest;
2497 }
2498 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002499 return PyLong_FromLong(count);
2500 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002501
2502error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002503 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002504 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002505 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002507}
2508
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002509/*[clinic input]
2510_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002511
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002512Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002513[clinic start generated code]*/
2514
2515static PyObject *
2516_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002517/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002518{
Miss Islington (bot)12296642018-09-17 12:12:13 -07002519 _PySSLError err;
2520 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002522 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002523 _PyTime_t timeout, deadline = 0;
2524 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002525
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002526 if (sock != NULL) {
2527 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002528 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002529 _setSSLError("Underlying socket connection gone",
2530 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2531 return NULL;
2532 }
2533 Py_INCREF(sock);
2534
2535 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002536 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002537 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2538 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540
Victor Stinner14690702015-04-06 22:46:13 +02002541 timeout = GET_SOCKET_TIMEOUT(sock);
2542 has_timeout = (timeout > 0);
2543 if (has_timeout)
2544 deadline = _PyTime_GetMonotonicClock() + timeout;
2545
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002546 while (1) {
2547 PySSL_BEGIN_ALLOW_THREADS
2548 /* Disable read-ahead so that unwrap can work correctly.
2549 * Otherwise OpenSSL might read in too much data,
2550 * eating clear text data that happens to be
2551 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002552 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 * function is used and the shutdown_seen_zero != 0
2554 * condition is met.
2555 */
2556 if (self->shutdown_seen_zero)
2557 SSL_set_read_ahead(self->ssl, 0);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002558 ret = SSL_shutdown(self->ssl);
2559 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002561 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002564 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 break;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002566 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002567 /* Don't loop endlessly; instead preserve legacy
2568 behaviour of trying SSL_shutdown() only twice.
2569 This looks necessary for OpenSSL < 0.9.8m */
2570 if (++zeros > 1)
2571 break;
2572 /* Shutdown was sent, now try receiving */
2573 self->shutdown_seen_zero = 1;
2574 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002575 }
2576
Victor Stinner14690702015-04-06 22:46:13 +02002577 if (has_timeout)
2578 timeout = deadline - _PyTime_GetMonotonicClock();
2579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 /* Possibly retry shutdown until timeout or failure */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002581 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002582 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002583 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002584 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 else
2586 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002588 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Miss Islington (bot)12296642018-09-17 12:12:13 -07002589 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002590 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 "The read operation timed out");
2592 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002593 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002594 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002595 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 }
2597 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2598 PyErr_SetString(PySSLErrorObject,
2599 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002600 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 }
2602 else if (sockstate != SOCKET_OPERATION_OK)
2603 /* Retain the SSL error code */
2604 break;
2605 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002606
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002607 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002608 Py_XDECREF(sock);
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002609 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002610 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002611 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002612 /* It's already INCREF'ed */
2613 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002614 else
2615 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002616
2617error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002618 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002619 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002620}
2621
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002622/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002623_ssl._SSLSocket.get_channel_binding
2624 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002625
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002626Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002627
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002628Raise ValueError if the requested `cb_type` is not supported. Return bytes
2629of the data or None if the data is not available (e.g. before the handshake).
2630Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002631[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002632
Antoine Pitroud6494802011-07-21 01:11:30 +02002633static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002634_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2635 const char *cb_type)
2636/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002637{
Antoine Pitroud6494802011-07-21 01:11:30 +02002638 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002639 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002640
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002641 if (strcmp(cb_type, "tls-unique") == 0) {
2642 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2643 /* if session is resumed XOR we are the client */
2644 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2645 }
2646 else {
2647 /* if a new session XOR we are the server */
2648 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2649 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002650 }
2651 else {
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002652 PyErr_Format(
2653 PyExc_ValueError,
2654 "'%s' channel binding type not implemented",
2655 cb_type
2656 );
2657 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002658 }
2659
2660 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002661 if (len == 0)
2662 Py_RETURN_NONE;
2663
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002664 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002665}
2666
Christian Heimes2756ef32018-09-23 09:22:52 +02002667/*[clinic input]
2668_ssl._SSLSocket.verify_client_post_handshake
2669
2670Initiate TLS 1.3 post-handshake authentication
2671[clinic start generated code]*/
2672
2673static PyObject *
2674_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2675/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2676{
2677#ifdef TLS1_3_VERSION
2678 int err = SSL_verify_client_post_handshake(self->ssl);
2679 if (err == 0)
2680 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2681 else
2682 Py_RETURN_NONE;
2683#else
2684 PyErr_SetString(PyExc_NotImplementedError,
2685 "Post-handshake auth is not supported by your "
2686 "OpenSSL version.");
2687 return NULL;
2688#endif
2689}
2690
Christian Heimes99a65702016-09-10 23:44:53 +02002691#ifdef OPENSSL_VERSION_1_1
2692
2693static SSL_SESSION*
2694_ssl_session_dup(SSL_SESSION *session) {
2695 SSL_SESSION *newsession = NULL;
2696 int slen;
2697 unsigned char *senc = NULL, *p;
2698 const unsigned char *const_p;
2699
2700 if (session == NULL) {
2701 PyErr_SetString(PyExc_ValueError, "Invalid session");
2702 goto error;
2703 }
2704
2705 /* get length */
2706 slen = i2d_SSL_SESSION(session, NULL);
2707 if (slen == 0 || slen > 0xFF00) {
2708 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2709 goto error;
2710 }
2711 if ((senc = PyMem_Malloc(slen)) == NULL) {
2712 PyErr_NoMemory();
2713 goto error;
2714 }
2715 p = senc;
2716 if (!i2d_SSL_SESSION(session, &p)) {
2717 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2718 goto error;
2719 }
2720 const_p = senc;
2721 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2722 if (session == NULL) {
2723 goto error;
2724 }
2725 PyMem_Free(senc);
2726 return newsession;
2727 error:
2728 if (senc != NULL) {
2729 PyMem_Free(senc);
2730 }
2731 return NULL;
2732}
2733#endif
2734
2735static PyObject *
2736PySSL_get_session(PySSLSocket *self, void *closure) {
2737 /* get_session can return sessions from a server-side connection,
2738 * it does not check for handshake done or client socket. */
2739 PySSLSession *pysess;
2740 SSL_SESSION *session;
2741
2742#ifdef OPENSSL_VERSION_1_1
2743 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2744 * https://github.com/openssl/openssl/issues/1550 */
2745 session = SSL_get0_session(self->ssl); /* borrowed reference */
2746 if (session == NULL) {
2747 Py_RETURN_NONE;
2748 }
2749 if ((session = _ssl_session_dup(session)) == NULL) {
2750 return NULL;
2751 }
2752#else
2753 session = SSL_get1_session(self->ssl);
2754 if (session == NULL) {
2755 Py_RETURN_NONE;
2756 }
2757#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002758 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002759 if (pysess == NULL) {
2760 SSL_SESSION_free(session);
2761 return NULL;
2762 }
2763
2764 assert(self->ctx);
2765 pysess->ctx = self->ctx;
2766 Py_INCREF(pysess->ctx);
2767 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002768 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002769 return (PyObject *)pysess;
2770}
2771
2772static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2773 void *closure)
2774 {
2775 PySSLSession *pysess;
2776#ifdef OPENSSL_VERSION_1_1
2777 SSL_SESSION *session;
2778#endif
2779 int result;
2780
2781 if (!PySSLSession_Check(value)) {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002782 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002783 return -1;
2784 }
2785 pysess = (PySSLSession *)value;
2786
2787 if (self->ctx->ctx != pysess->ctx->ctx) {
2788 PyErr_SetString(PyExc_ValueError,
2789 "Session refers to a different SSLContext.");
2790 return -1;
2791 }
2792 if (self->socket_type != PY_SSL_CLIENT) {
2793 PyErr_SetString(PyExc_ValueError,
2794 "Cannot set session for server-side SSLSocket.");
2795 return -1;
2796 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002797 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002798 PyErr_SetString(PyExc_ValueError,
2799 "Cannot set session after handshake.");
2800 return -1;
2801 }
2802#ifdef OPENSSL_VERSION_1_1
2803 /* duplicate session */
2804 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2805 return -1;
2806 }
2807 result = SSL_set_session(self->ssl, session);
2808 /* free duplicate, SSL_set_session() bumps ref count */
2809 SSL_SESSION_free(session);
2810#else
2811 result = SSL_set_session(self->ssl, pysess->session);
2812#endif
2813 if (result == 0) {
2814 _setSSLError(NULL, 0, __FILE__, __LINE__);
2815 return -1;
2816 }
2817 return 0;
2818}
2819
2820PyDoc_STRVAR(PySSL_set_session_doc,
2821"_setter_session(session)\n\
2822\
2823Get / set SSLSession.");
2824
2825static PyObject *
2826PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2827 if (SSL_session_reused(self->ssl)) {
2828 Py_RETURN_TRUE;
2829 } else {
2830 Py_RETURN_FALSE;
2831 }
2832}
2833
2834PyDoc_STRVAR(PySSL_get_session_reused_doc,
2835"Was the client session reused during handshake?");
2836
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002837static PyGetSetDef ssl_getsetlist[] = {
2838 {"context", (getter) PySSL_get_context,
2839 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002840 {"server_side", (getter) PySSL_get_server_side, NULL,
2841 PySSL_get_server_side_doc},
2842 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2843 PySSL_get_server_hostname_doc},
2844 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2845 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002846 {"session", (getter) PySSL_get_session,
2847 (setter) PySSL_set_session, PySSL_set_session_doc},
2848 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2849 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002850 {NULL}, /* sentinel */
2851};
2852
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002853static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002854 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2855 _SSL__SSLSOCKET_WRITE_METHODDEF
2856 _SSL__SSLSOCKET_READ_METHODDEF
2857 _SSL__SSLSOCKET_PENDING_METHODDEF
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002858 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2859 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002860 _SSL__SSLSOCKET_CIPHER_METHODDEF
2861 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2862 _SSL__SSLSOCKET_VERSION_METHODDEF
2863 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2864 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2865 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2866 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes2756ef32018-09-23 09:22:52 +02002867 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002868 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002869};
2870
Antoine Pitrou152efa22010-05-16 18:19:27 +00002871static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002872 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873 "_ssl._SSLSocket", /*tp_name*/
2874 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002875 0, /*tp_itemsize*/
2876 /* methods */
2877 (destructor)PySSL_dealloc, /*tp_dealloc*/
2878 0, /*tp_print*/
2879 0, /*tp_getattr*/
2880 0, /*tp_setattr*/
2881 0, /*tp_reserved*/
2882 0, /*tp_repr*/
2883 0, /*tp_as_number*/
2884 0, /*tp_as_sequence*/
2885 0, /*tp_as_mapping*/
2886 0, /*tp_hash*/
2887 0, /*tp_call*/
2888 0, /*tp_str*/
2889 0, /*tp_getattro*/
2890 0, /*tp_setattro*/
2891 0, /*tp_as_buffer*/
2892 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2893 0, /*tp_doc*/
2894 0, /*tp_traverse*/
2895 0, /*tp_clear*/
2896 0, /*tp_richcompare*/
2897 0, /*tp_weaklistoffset*/
2898 0, /*tp_iter*/
2899 0, /*tp_iternext*/
2900 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002901 0, /*tp_members*/
2902 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002903};
2904
Antoine Pitrou152efa22010-05-16 18:19:27 +00002905
2906/*
2907 * _SSLContext objects
2908 */
2909
Christian Heimes5fe668c2016-09-12 00:01:11 +02002910static int
Christian Heimes2756ef32018-09-23 09:22:52 +02002911_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002912{
2913 int mode;
2914 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2915
2916 switch(n) {
2917 case PY_SSL_CERT_NONE:
2918 mode = SSL_VERIFY_NONE;
2919 break;
2920 case PY_SSL_CERT_OPTIONAL:
2921 mode = SSL_VERIFY_PEER;
2922 break;
2923 case PY_SSL_CERT_REQUIRED:
2924 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2925 break;
2926 default:
2927 PyErr_SetString(PyExc_ValueError,
2928 "invalid value for verify_mode");
2929 return -1;
2930 }
Christian Heimes2756ef32018-09-23 09:22:52 +02002931#ifdef TLS1_3_VERSION
2932 if (self->post_handshake_auth)
2933 mode |= SSL_VERIFY_POST_HANDSHAKE;
2934#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002935 /* keep current verify cb */
Christian Heimes2756ef32018-09-23 09:22:52 +02002936 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2937 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002938 return 0;
2939}
2940
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002941/*[clinic input]
2942@classmethod
2943_ssl._SSLContext.__new__
2944 protocol as proto_version: int
2945 /
2946[clinic start generated code]*/
2947
Antoine Pitrou152efa22010-05-16 18:19:27 +00002948static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002949_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2950/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002951{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002952 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002953 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002954 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002955 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002956 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002957#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002958 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002959#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002960
Antoine Pitrou152efa22010-05-16 18:19:27 +00002961 PySSL_BEGIN_ALLOW_THREADS
2962 if (proto_version == PY_SSL_VERSION_TLS1)
2963 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002964#if HAVE_TLSv1_2
2965 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2966 ctx = SSL_CTX_new(TLSv1_1_method());
2967 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2968 ctx = SSL_CTX_new(TLSv1_2_method());
2969#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002970#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002971 else if (proto_version == PY_SSL_VERSION_SSL3)
2972 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002973#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002974#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002975 else if (proto_version == PY_SSL_VERSION_SSL2)
2976 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002977#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002978 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002979 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002980 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2981 ctx = SSL_CTX_new(TLS_client_method());
2982 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2983 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002984 else
2985 proto_version = -1;
2986 PySSL_END_ALLOW_THREADS
2987
2988 if (proto_version == -1) {
2989 PyErr_SetString(PyExc_ValueError,
2990 "invalid protocol version");
2991 return NULL;
2992 }
2993 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002994 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002995 return NULL;
2996 }
2997
2998 assert(type != NULL && type->tp_alloc != NULL);
2999 self = (PySSLContext *) type->tp_alloc(type, 0);
3000 if (self == NULL) {
3001 SSL_CTX_free(ctx);
3002 return NULL;
3003 }
3004 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003005 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003006 self->protocol = proto_version;
Miss Islington (bot)96177412018-02-25 04:18:43 -08003007#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003008 self->npn_protocols = NULL;
3009#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08003010#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003011 self->alpn_protocols = NULL;
3012#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003013#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003014 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003015#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003016 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003017 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3018 self->check_hostname = 1;
Christian Heimes2756ef32018-09-23 09:22:52 +02003019 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003020 Py_DECREF(self);
3021 return NULL;
3022 }
3023 } else {
3024 self->check_hostname = 0;
Christian Heimes2756ef32018-09-23 09:22:52 +02003025 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003026 Py_DECREF(self);
3027 return NULL;
3028 }
3029 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003031 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3032 if (proto_version != PY_SSL_VERSION_SSL2)
3033 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003034 if (proto_version != PY_SSL_VERSION_SSL3)
3035 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003036 /* Minimal security flags for server and client side context.
3037 * Client sockets ignore server-side parameters. */
3038#ifdef SSL_OP_NO_COMPRESSION
3039 options |= SSL_OP_NO_COMPRESSION;
3040#endif
3041#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3042 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3043#endif
3044#ifdef SSL_OP_SINGLE_DH_USE
3045 options |= SSL_OP_SINGLE_DH_USE;
3046#endif
3047#ifdef SSL_OP_SINGLE_ECDH_USE
3048 options |= SSL_OP_SINGLE_ECDH_USE;
3049#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003050 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003051
Semen Zhydenko1295e112017-10-15 21:28:31 +02003052 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003053 * It's far from perfect but gives users a better head start. */
3054 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003055#if PY_SSL_DEFAULT_CIPHERS == 2
3056 /* stick to OpenSSL's default settings */
3057 result = 1;
3058#else
3059 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3060#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003061 } else {
3062 /* SSLv2 needs MD5 */
3063 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3064 }
3065 if (result == 0) {
3066 Py_DECREF(self);
3067 ERR_clear_error();
3068 PyErr_SetString(PySSLErrorObject,
3069 "No cipher can be selected.");
3070 return NULL;
3071 }
3072
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003073#if defined(SSL_MODE_RELEASE_BUFFERS)
3074 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3075 usage for no cost at all. However, don't do this for OpenSSL versions
3076 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3077 2014-0198. I can't find exactly which beta fixed this CVE, so be
3078 conservative and assume it wasn't fixed until release. We do this check
3079 at runtime to avoid problems from the dynamic linker.
3080 See #25672 for more on this. */
3081 libver = SSLeay();
3082 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3083 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3084 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3085 }
3086#endif
3087
3088
Donald Stufft8ae264c2017-03-02 11:45:29 -05003089#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003090 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3091 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003092 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3093 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003094#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003095 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3096#else
3097 {
3098 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3099 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3100 EC_KEY_free(key);
3101 }
3102#endif
3103#endif
3104
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003105#define SID_CTX "Python"
3106 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3107 sizeof(SID_CTX));
3108#undef SID_CTX
3109
Christian Heimes61d478c2018-01-27 15:51:38 +01003110 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003111#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003112 /* Improve trust chain building when cross-signed intermediate
3113 certificates are present. See https://bugs.python.org/issue23476. */
3114 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003115#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003116 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003117
Christian Heimes2756ef32018-09-23 09:22:52 +02003118#ifdef TLS1_3_VERSION
3119 self->post_handshake_auth = 0;
3120 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3121#endif
3122
Antoine Pitrou152efa22010-05-16 18:19:27 +00003123 return (PyObject *)self;
3124}
3125
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003126static int
3127context_traverse(PySSLContext *self, visitproc visit, void *arg)
3128{
3129#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003130 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003131#endif
3132 return 0;
3133}
3134
3135static int
3136context_clear(PySSLContext *self)
3137{
3138#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003139 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003140#endif
3141 return 0;
3142}
3143
Antoine Pitrou152efa22010-05-16 18:19:27 +00003144static void
3145context_dealloc(PySSLContext *self)
3146{
INADA Naokia6296d32017-08-24 14:55:17 +09003147 /* bpo-31095: UnTrack is needed before calling any callbacks */
3148 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003149 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003150 SSL_CTX_free(self->ctx);
Miss Islington (bot)96177412018-02-25 04:18:43 -08003151#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003152 PyMem_FREE(self->npn_protocols);
3153#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08003154#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003155 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003156#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003157 Py_TYPE(self)->tp_free(self);
3158}
3159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003160/*[clinic input]
3161_ssl._SSLContext.set_ciphers
3162 cipherlist: str
3163 /
3164[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003165
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003166static PyObject *
3167_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3168/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3169{
3170 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003171 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003172 /* Clearing the error queue is necessary on some OpenSSL versions,
3173 otherwise the error will be reported again when another SSL call
3174 is done. */
3175 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003176 PyErr_SetString(PySSLErrorObject,
3177 "No cipher can be selected.");
3178 return NULL;
3179 }
3180 Py_RETURN_NONE;
3181}
3182
Christian Heimes25bfcd52016-09-06 00:04:45 +02003183#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3184/*[clinic input]
3185_ssl._SSLContext.get_ciphers
3186[clinic start generated code]*/
3187
3188static PyObject *
3189_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3190/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3191{
3192 SSL *ssl = NULL;
3193 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003194 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003195 int i=0;
3196 PyObject *result = NULL, *dct;
3197
3198 ssl = SSL_new(self->ctx);
3199 if (ssl == NULL) {
3200 _setSSLError(NULL, 0, __FILE__, __LINE__);
3201 goto exit;
3202 }
3203 sk = SSL_get_ciphers(ssl);
3204
3205 result = PyList_New(sk_SSL_CIPHER_num(sk));
3206 if (result == NULL) {
3207 goto exit;
3208 }
3209
3210 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3211 cipher = sk_SSL_CIPHER_value(sk, i);
3212 dct = cipher_to_dict(cipher);
3213 if (dct == NULL) {
3214 Py_CLEAR(result);
3215 goto exit;
3216 }
3217 PyList_SET_ITEM(result, i, dct);
3218 }
3219
3220 exit:
3221 if (ssl != NULL)
3222 SSL_free(ssl);
3223 return result;
3224
3225}
3226#endif
3227
3228
Miss Islington (bot)96177412018-02-25 04:18:43 -08003229#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003230static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003231do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3232 const unsigned char *server_protocols, unsigned int server_protocols_len,
3233 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003234{
Benjamin Peterson88615022015-01-23 17:30:26 -05003235 int ret;
3236 if (client_protocols == NULL) {
3237 client_protocols = (unsigned char *)"";
3238 client_protocols_len = 0;
3239 }
3240 if (server_protocols == NULL) {
3241 server_protocols = (unsigned char *)"";
3242 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003243 }
3244
Benjamin Peterson88615022015-01-23 17:30:26 -05003245 ret = SSL_select_next_proto(out, outlen,
3246 server_protocols, server_protocols_len,
3247 client_protocols, client_protocols_len);
3248 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3249 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003250
3251 return SSL_TLSEXT_ERR_OK;
3252}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003253#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003254
Miss Islington (bot)96177412018-02-25 04:18:43 -08003255#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003256/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3257static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003258_advertiseNPN_cb(SSL *s,
3259 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003260 void *args)
3261{
3262 PySSLContext *ssl_ctx = (PySSLContext *) args;
3263
3264 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003265 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003266 *len = 0;
3267 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003268 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003269 *len = ssl_ctx->npn_protocols_len;
3270 }
3271
3272 return SSL_TLSEXT_ERR_OK;
3273}
3274/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3275static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003276_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003277 unsigned char **out, unsigned char *outlen,
3278 const unsigned char *server, unsigned int server_len,
3279 void *args)
3280{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003281 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003282 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003283 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003284}
3285#endif
3286
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003287/*[clinic input]
3288_ssl._SSLContext._set_npn_protocols
3289 protos: Py_buffer
3290 /
3291[clinic start generated code]*/
3292
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003293static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003294_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3295 Py_buffer *protos)
3296/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003297{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003298#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003299 PyMem_Free(self->npn_protocols);
3300 self->npn_protocols = PyMem_Malloc(protos->len);
3301 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003302 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003303 memcpy(self->npn_protocols, protos->buf, protos->len);
3304 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003305
3306 /* set both server and client callbacks, because the context can
3307 * be used to create both types of sockets */
3308 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3309 _advertiseNPN_cb,
3310 self);
3311 SSL_CTX_set_next_proto_select_cb(self->ctx,
3312 _selectNPN_cb,
3313 self);
3314
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003315 Py_RETURN_NONE;
3316#else
3317 PyErr_SetString(PyExc_NotImplementedError,
3318 "The NPN extension requires OpenSSL 1.0.1 or later.");
3319 return NULL;
3320#endif
3321}
3322
Miss Islington (bot)96177412018-02-25 04:18:43 -08003323#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003324static int
3325_selectALPN_cb(SSL *s,
3326 const unsigned char **out, unsigned char *outlen,
3327 const unsigned char *client_protocols, unsigned int client_protocols_len,
3328 void *args)
3329{
3330 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003331 return do_protocol_selection(1, (unsigned char **)out, outlen,
3332 ctx->alpn_protocols, ctx->alpn_protocols_len,
3333 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003334}
3335#endif
3336
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003337/*[clinic input]
3338_ssl._SSLContext._set_alpn_protocols
3339 protos: Py_buffer
3340 /
3341[clinic start generated code]*/
3342
Benjamin Petersoncca27322015-01-23 16:35:37 -05003343static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003344_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3345 Py_buffer *protos)
3346/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003347{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003348#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003349 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003350 PyErr_Format(PyExc_OverflowError,
Serhiy Storchaka783bed42019-03-14 10:47:27 +02003351 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003352 return NULL;
3353 }
3354
Benjamin Petersoncca27322015-01-23 16:35:37 -05003355 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003356 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003357 if (!self->alpn_protocols)
3358 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003359 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003360 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003361
3362 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3363 return PyErr_NoMemory();
3364 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3365
Benjamin Petersoncca27322015-01-23 16:35:37 -05003366 Py_RETURN_NONE;
3367#else
3368 PyErr_SetString(PyExc_NotImplementedError,
3369 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3370 return NULL;
3371#endif
3372}
3373
Antoine Pitrou152efa22010-05-16 18:19:27 +00003374static PyObject *
3375get_verify_mode(PySSLContext *self, void *c)
3376{
Christian Heimes2756ef32018-09-23 09:22:52 +02003377 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3378 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3379 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3380 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003381 case SSL_VERIFY_NONE:
3382 return PyLong_FromLong(PY_SSL_CERT_NONE);
3383 case SSL_VERIFY_PEER:
3384 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3385 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3386 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3387 }
3388 PyErr_SetString(PySSLErrorObject,
3389 "invalid return value from SSL_CTX_get_verify_mode");
3390 return NULL;
3391}
3392
3393static int
3394set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3395{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003396 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003397 if (!PyArg_Parse(arg, "i", &n))
3398 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003399 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003400 PyErr_SetString(PyExc_ValueError,
3401 "Cannot set verify_mode to CERT_NONE when "
3402 "check_hostname is enabled.");
3403 return -1;
3404 }
Christian Heimes2756ef32018-09-23 09:22:52 +02003405 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003406}
3407
3408static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003409get_verify_flags(PySSLContext *self, void *c)
3410{
Christian Heimes598894f2016-09-05 23:19:05 +02003411 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003412 unsigned long flags;
3413
Christian Heimes61d478c2018-01-27 15:51:38 +01003414 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003415 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003416 return PyLong_FromUnsignedLong(flags);
3417}
3418
3419static int
3420set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3421{
Christian Heimes598894f2016-09-05 23:19:05 +02003422 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003423 unsigned long new_flags, flags, set, clear;
3424
3425 if (!PyArg_Parse(arg, "k", &new_flags))
3426 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003427 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003428 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003429 clear = flags & ~new_flags;
3430 set = ~flags & new_flags;
3431 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003432 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003433 _setSSLError(NULL, 0, __FILE__, __LINE__);
3434 return -1;
3435 }
3436 }
3437 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003438 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003439 _setSSLError(NULL, 0, __FILE__, __LINE__);
3440 return -1;
3441 }
3442 }
3443 return 0;
3444}
3445
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08003446/* Getter and setter for protocol version */
3447#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3448
3449
3450static int
3451set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3452{
3453 long v;
3454 int result;
3455
3456 if (!PyArg_Parse(arg, "l", &v))
3457 return -1;
3458 if (v > INT_MAX) {
3459 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3460 return -1;
3461 }
3462
3463 switch(self->protocol) {
3464 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3465 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3466 case PY_SSL_VERSION_TLS:
3467 break;
3468 default:
3469 PyErr_SetString(
3470 PyExc_ValueError,
3471 "The context's protocol doesn't support modification of "
3472 "highest and lowest version."
3473 );
3474 return -1;
3475 }
3476
3477 if (what == 0) {
3478 switch(v) {
3479 case PY_PROTO_MINIMUM_SUPPORTED:
3480 v = 0;
3481 break;
3482 case PY_PROTO_MAXIMUM_SUPPORTED:
3483 /* Emulate max for set_min_proto_version */
3484 v = PY_PROTO_MAXIMUM_AVAILABLE;
3485 break;
3486 default:
3487 break;
3488 }
3489 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3490 }
3491 else {
3492 switch(v) {
3493 case PY_PROTO_MAXIMUM_SUPPORTED:
3494 v = 0;
3495 break;
3496 case PY_PROTO_MINIMUM_SUPPORTED:
3497 /* Emulate max for set_min_proto_version */
3498 v = PY_PROTO_MINIMUM_AVAILABLE;
3499 break;
3500 default:
3501 break;
3502 }
3503 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3504 }
3505 if (result == 0) {
3506 PyErr_Format(PyExc_ValueError,
3507 "Unsupported protocol version 0x%x", v);
3508 return -1;
3509 }
3510 return 0;
3511}
3512
3513static PyObject *
3514get_minimum_version(PySSLContext *self, void *c)
3515{
3516 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3517 if (v == 0) {
3518 v = PY_PROTO_MINIMUM_SUPPORTED;
3519 }
3520 return PyLong_FromLong(v);
3521}
3522
3523static int
3524set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3525{
3526 return set_min_max_proto_version(self, arg, 0);
3527}
3528
3529static PyObject *
3530get_maximum_version(PySSLContext *self, void *c)
3531{
3532 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3533 if (v == 0) {
3534 v = PY_PROTO_MAXIMUM_SUPPORTED;
3535 }
3536 return PyLong_FromLong(v);
3537}
3538
3539static int
3540set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3541{
3542 return set_min_max_proto_version(self, arg, 1);
3543}
3544#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3545
Christian Heimes22587792013-11-21 23:56:13 +01003546static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003547get_options(PySSLContext *self, void *c)
3548{
3549 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3550}
3551
3552static int
3553set_options(PySSLContext *self, PyObject *arg, void *c)
3554{
3555 long new_opts, opts, set, clear;
3556 if (!PyArg_Parse(arg, "l", &new_opts))
3557 return -1;
3558 opts = SSL_CTX_get_options(self->ctx);
3559 clear = opts & ~new_opts;
3560 set = ~opts & new_opts;
3561 if (clear) {
3562#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3563 SSL_CTX_clear_options(self->ctx, clear);
3564#else
3565 PyErr_SetString(PyExc_ValueError,
3566 "can't clear options before OpenSSL 0.9.8m");
3567 return -1;
3568#endif
3569 }
3570 if (set)
3571 SSL_CTX_set_options(self->ctx, set);
3572 return 0;
3573}
3574
Christian Heimes1aa9a752013-12-02 02:41:19 +01003575static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003576get_host_flags(PySSLContext *self, void *c)
3577{
3578 return PyLong_FromUnsignedLong(self->hostflags);
3579}
3580
3581static int
3582set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3583{
3584 X509_VERIFY_PARAM *param;
3585 unsigned int new_flags = 0;
3586
3587 if (!PyArg_Parse(arg, "I", &new_flags))
3588 return -1;
3589
3590 param = SSL_CTX_get0_param(self->ctx);
3591 self->hostflags = new_flags;
3592 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3593 return 0;
3594}
3595
3596static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003597get_check_hostname(PySSLContext *self, void *c)
3598{
3599 return PyBool_FromLong(self->check_hostname);
3600}
3601
3602static int
3603set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3604{
3605 int check_hostname;
3606 if (!PyArg_Parse(arg, "p", &check_hostname))
3607 return -1;
3608 if (check_hostname &&
3609 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003610 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes2756ef32018-09-23 09:22:52 +02003611 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003612 return -1;
3613 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003614 }
3615 self->check_hostname = check_hostname;
3616 return 0;
3617}
3618
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003619static PyObject *
Christian Heimes2756ef32018-09-23 09:22:52 +02003620get_post_handshake_auth(PySSLContext *self, void *c) {
3621#if TLS1_3_VERSION
3622 return PyBool_FromLong(self->post_handshake_auth);
3623#else
3624 Py_RETURN_NONE;
3625#endif
3626}
3627
3628#if TLS1_3_VERSION
3629static int
3630set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3631 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3632 int mode = SSL_CTX_get_verify_mode(self->ctx);
Miss Islington (bot)cb272842018-12-17 07:10:20 -08003633 if (arg == NULL) {
3634 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3635 return -1;
3636 }
Christian Heimes2756ef32018-09-23 09:22:52 +02003637 int pha = PyObject_IsTrue(arg);
3638
3639 if (pha == -1) {
3640 return -1;
3641 }
3642 self->post_handshake_auth = pha;
3643
3644 /* client-side socket setting, ignored by server-side */
3645 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3646
3647 /* server-side socket setting, ignored by client-side */
3648 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3649 if (pha) {
3650 mode |= SSL_VERIFY_POST_HANDSHAKE;
3651 } else {
3652 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3653 }
3654 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3655
3656 return 0;
3657}
3658#endif
3659
3660static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003661get_protocol(PySSLContext *self, void *c) {
3662 return PyLong_FromLong(self->protocol);
3663}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003664
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003665typedef struct {
3666 PyThreadState *thread_state;
3667 PyObject *callable;
3668 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003669 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003670 int error;
3671} _PySSLPasswordInfo;
3672
3673static int
3674_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3675 const char *bad_type_error)
3676{
3677 /* Set the password and size fields of a _PySSLPasswordInfo struct
3678 from a unicode, bytes, or byte array object.
3679 The password field will be dynamically allocated and must be freed
3680 by the caller */
3681 PyObject *password_bytes = NULL;
3682 const char *data = NULL;
3683 Py_ssize_t size;
3684
3685 if (PyUnicode_Check(password)) {
3686 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3687 if (!password_bytes) {
3688 goto error;
3689 }
3690 data = PyBytes_AS_STRING(password_bytes);
3691 size = PyBytes_GET_SIZE(password_bytes);
3692 } else if (PyBytes_Check(password)) {
3693 data = PyBytes_AS_STRING(password);
3694 size = PyBytes_GET_SIZE(password);
3695 } else if (PyByteArray_Check(password)) {
3696 data = PyByteArray_AS_STRING(password);
3697 size = PyByteArray_GET_SIZE(password);
3698 } else {
3699 PyErr_SetString(PyExc_TypeError, bad_type_error);
3700 goto error;
3701 }
3702
Victor Stinner9ee02032013-06-23 15:08:23 +02003703 if (size > (Py_ssize_t)INT_MAX) {
3704 PyErr_Format(PyExc_ValueError,
3705 "password cannot be longer than %d bytes", INT_MAX);
3706 goto error;
3707 }
3708
Victor Stinner11ebff22013-07-07 17:07:52 +02003709 PyMem_Free(pw_info->password);
3710 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003711 if (!pw_info->password) {
3712 PyErr_SetString(PyExc_MemoryError,
3713 "unable to allocate password buffer");
3714 goto error;
3715 }
3716 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003717 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003718
3719 Py_XDECREF(password_bytes);
3720 return 1;
3721
3722error:
3723 Py_XDECREF(password_bytes);
3724 return 0;
3725}
3726
3727static int
3728_password_callback(char *buf, int size, int rwflag, void *userdata)
3729{
3730 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3731 PyObject *fn_ret = NULL;
3732
3733 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3734
3735 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003736 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003737 if (!fn_ret) {
3738 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3739 core python API, so we could use it to add a frame here */
3740 goto error;
3741 }
3742
3743 if (!_pwinfo_set(pw_info, fn_ret,
3744 "password callback must return a string")) {
3745 goto error;
3746 }
3747 Py_CLEAR(fn_ret);
3748 }
3749
3750 if (pw_info->size > size) {
3751 PyErr_Format(PyExc_ValueError,
3752 "password cannot be longer than %d bytes", size);
3753 goto error;
3754 }
3755
3756 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3757 memcpy(buf, pw_info->password, pw_info->size);
3758 return pw_info->size;
3759
3760error:
3761 Py_XDECREF(fn_ret);
3762 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3763 pw_info->error = 1;
3764 return -1;
3765}
3766
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003767/*[clinic input]
3768_ssl._SSLContext.load_cert_chain
3769 certfile: object
3770 keyfile: object = NULL
3771 password: object = NULL
3772
3773[clinic start generated code]*/
3774
Antoine Pitroub5218772010-05-21 09:56:06 +00003775static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003776_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3777 PyObject *keyfile, PyObject *password)
3778/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003779{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003780 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003781 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3782 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003783 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003784 int r;
3785
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003786 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003787 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003788 if (keyfile == Py_None)
3789 keyfile = NULL;
3790 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3791 PyErr_SetString(PyExc_TypeError,
3792 "certfile should be a valid filesystem path");
3793 return NULL;
3794 }
3795 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3796 PyErr_SetString(PyExc_TypeError,
3797 "keyfile should be a valid filesystem path");
3798 goto error;
3799 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003800 if (password && password != Py_None) {
3801 if (PyCallable_Check(password)) {
3802 pw_info.callable = password;
3803 } else if (!_pwinfo_set(&pw_info, password,
3804 "password should be a string or callable")) {
3805 goto error;
3806 }
3807 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3808 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3809 }
3810 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003811 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3812 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003813 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003814 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003815 if (pw_info.error) {
3816 ERR_clear_error();
3817 /* the password callback has already set the error information */
3818 }
3819 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003820 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003821 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003822 }
3823 else {
3824 _setSSLError(NULL, 0, __FILE__, __LINE__);
3825 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003826 goto error;
3827 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003828 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003829 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003830 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3831 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003832 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3833 Py_CLEAR(keyfile_bytes);
3834 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003835 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003836 if (pw_info.error) {
3837 ERR_clear_error();
3838 /* the password callback has already set the error information */
3839 }
3840 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003841 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003842 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003843 }
3844 else {
3845 _setSSLError(NULL, 0, __FILE__, __LINE__);
3846 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003847 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003848 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003849 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003850 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003851 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003852 if (r != 1) {
3853 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003854 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003855 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003856 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3857 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003858 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003859 Py_RETURN_NONE;
3860
3861error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003862 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3863 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003864 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003865 Py_XDECREF(keyfile_bytes);
3866 Py_XDECREF(certfile_bytes);
3867 return NULL;
3868}
3869
Christian Heimesefff7062013-11-21 03:35:02 +01003870/* internal helper function, returns -1 on error
3871 */
3872static int
3873_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3874 int filetype)
3875{
3876 BIO *biobuf = NULL;
3877 X509_STORE *store;
3878 int retval = 0, err, loaded = 0;
3879
3880 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3881
3882 if (len <= 0) {
3883 PyErr_SetString(PyExc_ValueError,
3884 "Empty certificate data");
3885 return -1;
3886 } else if (len > INT_MAX) {
3887 PyErr_SetString(PyExc_OverflowError,
3888 "Certificate data is too long.");
3889 return -1;
3890 }
3891
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003892 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003893 if (biobuf == NULL) {
3894 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3895 return -1;
3896 }
3897
3898 store = SSL_CTX_get_cert_store(self->ctx);
3899 assert(store != NULL);
3900
3901 while (1) {
3902 X509 *cert = NULL;
3903 int r;
3904
3905 if (filetype == SSL_FILETYPE_ASN1) {
3906 cert = d2i_X509_bio(biobuf, NULL);
3907 } else {
3908 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003909 SSL_CTX_get_default_passwd_cb(self->ctx),
3910 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3911 );
Christian Heimesefff7062013-11-21 03:35:02 +01003912 }
3913 if (cert == NULL) {
3914 break;
3915 }
3916 r = X509_STORE_add_cert(store, cert);
3917 X509_free(cert);
3918 if (!r) {
3919 err = ERR_peek_last_error();
3920 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3921 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3922 /* cert already in hash table, not an error */
3923 ERR_clear_error();
3924 } else {
3925 break;
3926 }
3927 }
3928 loaded++;
3929 }
3930
3931 err = ERR_peek_last_error();
3932 if ((filetype == SSL_FILETYPE_ASN1) &&
3933 (loaded > 0) &&
3934 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3935 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3936 /* EOF ASN1 file, not an error */
3937 ERR_clear_error();
3938 retval = 0;
3939 } else if ((filetype == SSL_FILETYPE_PEM) &&
3940 (loaded > 0) &&
3941 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3942 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3943 /* EOF PEM file, not an error */
3944 ERR_clear_error();
3945 retval = 0;
3946 } else {
3947 _setSSLError(NULL, 0, __FILE__, __LINE__);
3948 retval = -1;
3949 }
3950
3951 BIO_free(biobuf);
3952 return retval;
3953}
3954
3955
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003956/*[clinic input]
3957_ssl._SSLContext.load_verify_locations
3958 cafile: object = NULL
3959 capath: object = NULL
3960 cadata: object = NULL
3961
3962[clinic start generated code]*/
3963
Antoine Pitrou152efa22010-05-16 18:19:27 +00003964static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003965_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3966 PyObject *cafile,
3967 PyObject *capath,
3968 PyObject *cadata)
3969/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003970{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003971 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3972 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003973 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003974
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003975 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976 if (cafile == Py_None)
3977 cafile = NULL;
3978 if (capath == Py_None)
3979 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003980 if (cadata == Py_None)
3981 cadata = NULL;
3982
3983 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003984 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003985 "cafile, capath and cadata cannot be all omitted");
3986 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003987 }
3988 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3989 PyErr_SetString(PyExc_TypeError,
3990 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003991 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003992 }
3993 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003994 PyErr_SetString(PyExc_TypeError,
3995 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003996 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997 }
Christian Heimesefff7062013-11-21 03:35:02 +01003998
3999 /* validata cadata type and load cadata */
4000 if (cadata) {
4001 Py_buffer buf;
4002 PyObject *cadata_ascii = NULL;
4003
4004 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
4005 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4006 PyBuffer_Release(&buf);
4007 PyErr_SetString(PyExc_TypeError,
4008 "cadata should be a contiguous buffer with "
4009 "a single dimension");
4010 goto error;
4011 }
4012 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4013 PyBuffer_Release(&buf);
4014 if (r == -1) {
4015 goto error;
4016 }
4017 } else {
4018 PyErr_Clear();
4019 cadata_ascii = PyUnicode_AsASCIIString(cadata);
4020 if (cadata_ascii == NULL) {
4021 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004022 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01004023 "bytes-like object");
4024 goto error;
4025 }
4026 r = _add_ca_certs(self,
4027 PyBytes_AS_STRING(cadata_ascii),
4028 PyBytes_GET_SIZE(cadata_ascii),
4029 SSL_FILETYPE_PEM);
4030 Py_DECREF(cadata_ascii);
4031 if (r == -1) {
4032 goto error;
4033 }
4034 }
4035 }
4036
4037 /* load cafile or capath */
4038 if (cafile || capath) {
4039 if (cafile)
4040 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4041 if (capath)
4042 capath_buf = PyBytes_AS_STRING(capath_bytes);
4043 PySSL_BEGIN_ALLOW_THREADS
4044 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4045 PySSL_END_ALLOW_THREADS
4046 if (r != 1) {
4047 ok = 0;
4048 if (errno != 0) {
4049 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004050 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004051 }
4052 else {
4053 _setSSLError(NULL, 0, __FILE__, __LINE__);
4054 }
4055 goto error;
4056 }
4057 }
4058 goto end;
4059
4060 error:
4061 ok = 0;
4062 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063 Py_XDECREF(cafile_bytes);
4064 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004065 if (ok) {
4066 Py_RETURN_NONE;
4067 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004068 return NULL;
4069 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004070}
4071
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004072/*[clinic input]
4073_ssl._SSLContext.load_dh_params
4074 path as filepath: object
4075 /
4076
4077[clinic start generated code]*/
4078
Antoine Pitrou152efa22010-05-16 18:19:27 +00004079static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004080_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4081/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004082{
4083 FILE *f;
4084 DH *dh;
4085
Victor Stinnerdaf45552013-08-28 00:53:59 +02004086 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004087 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004088 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004089
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004090 errno = 0;
4091 PySSL_BEGIN_ALLOW_THREADS
4092 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004093 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004094 PySSL_END_ALLOW_THREADS
4095 if (dh == NULL) {
4096 if (errno != 0) {
4097 ERR_clear_error();
4098 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4099 }
4100 else {
4101 _setSSLError(NULL, 0, __FILE__, __LINE__);
4102 }
4103 return NULL;
4104 }
4105 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4106 _setSSLError(NULL, 0, __FILE__, __LINE__);
4107 DH_free(dh);
4108 Py_RETURN_NONE;
4109}
4110
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004111/*[clinic input]
4112_ssl._SSLContext._wrap_socket
4113 sock: object(subclass_of="PySocketModule.Sock_Type")
4114 server_side: int
4115 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004116 *
4117 owner: object = None
4118 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004119
4120[clinic start generated code]*/
4121
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004122static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004123_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004124 int server_side, PyObject *hostname_obj,
4125 PyObject *owner, PyObject *session)
4126/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004127{
Antoine Pitroud5323212010-10-22 18:19:07 +00004128 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004130
Antoine Pitroud5323212010-10-22 18:19:07 +00004131 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004132 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004133 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004134 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004135 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004136 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004137
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4139 server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004140 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004141 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004142 if (hostname != NULL)
4143 PyMem_Free(hostname);
4144 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004145}
4146
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004147/*[clinic input]
4148_ssl._SSLContext._wrap_bio
4149 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4150 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4151 server_side: int
4152 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004153 *
4154 owner: object = None
4155 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004156
4157[clinic start generated code]*/
4158
Antoine Pitroub0182c82010-10-12 20:09:02 +00004159static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004160_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4161 PySSLMemoryBIO *outgoing, int server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004162 PyObject *hostname_obj, PyObject *owner,
4163 PyObject *session)
4164/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004165{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004166 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004167 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004168
4169 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004170 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004171 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004172 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004173 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004174 }
4175
4176 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004177 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004178 incoming, outgoing);
4179
4180 PyMem_Free(hostname);
4181 return res;
4182}
4183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004184/*[clinic input]
4185_ssl._SSLContext.session_stats
4186[clinic start generated code]*/
4187
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004189_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4190/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004191{
4192 int r;
4193 PyObject *value, *stats = PyDict_New();
4194 if (!stats)
4195 return NULL;
4196
4197#define ADD_STATS(SSL_NAME, KEY_NAME) \
4198 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4199 if (value == NULL) \
4200 goto error; \
4201 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4202 Py_DECREF(value); \
4203 if (r < 0) \
4204 goto error;
4205
4206 ADD_STATS(number, "number");
4207 ADD_STATS(connect, "connect");
4208 ADD_STATS(connect_good, "connect_good");
4209 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4210 ADD_STATS(accept, "accept");
4211 ADD_STATS(accept_good, "accept_good");
4212 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4213 ADD_STATS(accept, "accept");
4214 ADD_STATS(hits, "hits");
4215 ADD_STATS(misses, "misses");
4216 ADD_STATS(timeouts, "timeouts");
4217 ADD_STATS(cache_full, "cache_full");
4218
4219#undef ADD_STATS
4220
4221 return stats;
4222
4223error:
4224 Py_DECREF(stats);
4225 return NULL;
4226}
4227
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004228/*[clinic input]
4229_ssl._SSLContext.set_default_verify_paths
4230[clinic start generated code]*/
4231
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004232static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004233_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4234/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004235{
4236 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4237 _setSSLError(NULL, 0, __FILE__, __LINE__);
4238 return NULL;
4239 }
4240 Py_RETURN_NONE;
4241}
4242
Antoine Pitrou501da612011-12-21 09:27:41 +01004243#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004244/*[clinic input]
4245_ssl._SSLContext.set_ecdh_curve
4246 name: object
4247 /
4248
4249[clinic start generated code]*/
4250
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004251static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004252_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4253/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004254{
4255 PyObject *name_bytes;
4256 int nid;
4257 EC_KEY *key;
4258
4259 if (!PyUnicode_FSConverter(name, &name_bytes))
4260 return NULL;
4261 assert(PyBytes_Check(name_bytes));
4262 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4263 Py_DECREF(name_bytes);
4264 if (nid == 0) {
4265 PyErr_Format(PyExc_ValueError,
4266 "unknown elliptic curve name %R", name);
4267 return NULL;
4268 }
4269 key = EC_KEY_new_by_curve_name(nid);
4270 if (key == NULL) {
4271 _setSSLError(NULL, 0, __FILE__, __LINE__);
4272 return NULL;
4273 }
4274 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4275 EC_KEY_free(key);
4276 Py_RETURN_NONE;
4277}
Antoine Pitrou501da612011-12-21 09:27:41 +01004278#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004279
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004280#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004281static int
4282_servername_callback(SSL *s, int *al, void *args)
4283{
4284 int ret;
4285 PySSLContext *ssl_ctx = (PySSLContext *) args;
4286 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004287 PyObject *result;
4288 /* The high-level ssl.SSLSocket object */
4289 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004290 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004291 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004292
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004293 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004294 /* remove race condition in this the call back while if removing the
4295 * callback is in progress */
4296 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004297 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004298 }
4299
4300 ssl = SSL_get_app_data(s);
4301 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004302
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004303 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004304 * SSL connection and that has a .context attribute that can be changed to
4305 * identify the requested hostname. Since the official API is the Python
4306 * level API we want to pass the callback a Python level object rather than
4307 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4308 * SSLObject) that will be passed. Otherwise if there's a socket then that
4309 * will be passed. If both do not exist only then the C-level object is
4310 * passed. */
4311 if (ssl->owner)
4312 ssl_socket = PyWeakref_GetObject(ssl->owner);
4313 else if (ssl->Socket)
4314 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4315 else
4316 ssl_socket = (PyObject *) ssl;
4317
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004318 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004319 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004320 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004321
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004322 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004323 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004324 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004325 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004326 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004327 PyObject *servername_bytes;
4328 PyObject *servername_str;
4329
4330 servername_bytes = PyBytes_FromString(servername);
4331 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004332 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4333 goto error;
4334 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004335 /* server_hostname was encoded to an A-label by our caller; put it
4336 * back into a str object, but still as an A-label (bpo-28414)
4337 */
4338 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4339 Py_DECREF(servername_bytes);
4340 if (servername_str == NULL) {
4341 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004342 goto error;
4343 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004344 result = PyObject_CallFunctionObjArgs(
4345 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4346 ssl_ctx, NULL);
4347 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004348 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004349 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004350
4351 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004352 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004353 *al = SSL_AD_HANDSHAKE_FAILURE;
4354 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4355 }
4356 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004357 /* Result may be None, a SSLContext or an integer
4358 * None and SSLContext are OK, integer or other values are an error.
4359 */
4360 if (result == Py_None) {
4361 ret = SSL_TLSEXT_ERR_OK;
4362 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004363 *al = (int) PyLong_AsLong(result);
4364 if (PyErr_Occurred()) {
4365 PyErr_WriteUnraisable(result);
4366 *al = SSL_AD_INTERNAL_ERROR;
4367 }
4368 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4369 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004370 Py_DECREF(result);
4371 }
4372
4373 PyGILState_Release(gstate);
4374 return ret;
4375
4376error:
4377 Py_DECREF(ssl_socket);
4378 *al = SSL_AD_INTERNAL_ERROR;
4379 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4380 PyGILState_Release(gstate);
4381 return ret;
4382}
Antoine Pitroua5963382013-03-30 16:39:00 +01004383#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004384
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004385static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004386get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004387{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004388 PyObject *cb = self->set_sni_cb;
4389 if (cb == NULL) {
4390 Py_RETURN_NONE;
4391 }
4392 Py_INCREF(cb);
4393 return cb;
4394}
4395
4396static int
4397set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4398{
4399 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4400 PyErr_SetString(PyExc_ValueError,
4401 "sni_callback cannot be set on TLS_CLIENT context");
4402 return -1;
4403 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004404#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004405 Py_CLEAR(self->set_sni_cb);
4406 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004407 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4408 }
4409 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004410 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004411 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4412 PyErr_SetString(PyExc_TypeError,
4413 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004414 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004415 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004416 Py_INCREF(arg);
4417 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004418 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4419 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4420 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004421 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004422#else
4423 PyErr_SetString(PyExc_NotImplementedError,
4424 "The TLS extension servername callback, "
4425 "SSL_CTX_set_tlsext_servername_callback, "
4426 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004427 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004428#endif
4429}
4430
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004431PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4432"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4433\n\
4434If the argument is None then the callback is disabled. The method is called\n\
4435with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4436See RFC 6066 for details of the SNI extension.");
4437
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004438/*[clinic input]
4439_ssl._SSLContext.cert_store_stats
4440
4441Returns quantities of loaded X.509 certificates.
4442
4443X.509 certificates with a CA extension and certificate revocation lists
4444inside the context's cert store.
4445
4446NOTE: Certificates in a capath directory aren't loaded unless they have
4447been used at least once.
4448[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004449
4450static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004451_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4452/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004453{
4454 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004455 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004456 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004457 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004458
4459 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004460 objs = X509_STORE_get0_objects(store);
4461 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4462 obj = sk_X509_OBJECT_value(objs, i);
4463 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004464 case X509_LU_X509:
4465 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004466 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004467 ca++;
4468 }
4469 break;
4470 case X509_LU_CRL:
4471 crl++;
4472 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004473 default:
4474 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4475 * As far as I can tell they are internal states and never
4476 * stored in a cert store */
4477 break;
4478 }
4479 }
4480 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4481 "x509_ca", ca);
4482}
4483
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004484/*[clinic input]
4485_ssl._SSLContext.get_ca_certs
4486 binary_form: bool = False
4487
4488Returns a list of dicts with information of loaded CA certs.
4489
4490If the optional argument is True, returns a DER-encoded copy of the CA
4491certificate.
4492
4493NOTE: Certificates in a capath directory aren't loaded unless they have
4494been used at least once.
4495[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004496
4497static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004498_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4499/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004500{
4501 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004502 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004503 PyObject *ci = NULL, *rlist = NULL;
4504 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004505
4506 if ((rlist = PyList_New(0)) == NULL) {
4507 return NULL;
4508 }
4509
4510 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004511 objs = X509_STORE_get0_objects(store);
4512 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004513 X509_OBJECT *obj;
4514 X509 *cert;
4515
Christian Heimes598894f2016-09-05 23:19:05 +02004516 obj = sk_X509_OBJECT_value(objs, i);
4517 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004518 /* not a x509 cert */
4519 continue;
4520 }
4521 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004522 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004523 if (!X509_check_ca(cert)) {
4524 continue;
4525 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004526 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004527 ci = _certificate_to_der(cert);
4528 } else {
4529 ci = _decode_certificate(cert);
4530 }
4531 if (ci == NULL) {
4532 goto error;
4533 }
4534 if (PyList_Append(rlist, ci) == -1) {
4535 goto error;
4536 }
4537 Py_CLEAR(ci);
4538 }
4539 return rlist;
4540
4541 error:
4542 Py_XDECREF(ci);
4543 Py_XDECREF(rlist);
4544 return NULL;
4545}
4546
4547
Antoine Pitrou152efa22010-05-16 18:19:27 +00004548static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004549 {"check_hostname", (getter) get_check_hostname,
4550 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004551 {"_host_flags", (getter) get_host_flags,
4552 (setter) set_host_flags, NULL},
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004553#if SSL_CTRL_GET_MAX_PROTO_VERSION
4554 {"minimum_version", (getter) get_minimum_version,
4555 (setter) set_minimum_version, NULL},
4556 {"maximum_version", (getter) get_maximum_version,
4557 (setter) set_maximum_version, NULL},
4558#endif
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004559 {"sni_callback", (getter) get_sni_callback,
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004560 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004561 {"options", (getter) get_options,
4562 (setter) set_options, NULL},
Christian Heimes2756ef32018-09-23 09:22:52 +02004563 {"post_handshake_auth", (getter) get_post_handshake_auth,
4564#ifdef TLS1_3_VERSION
4565 (setter) set_post_handshake_auth,
4566#else
4567 NULL,
4568#endif
4569 NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004570 {"protocol", (getter) get_protocol,
4571 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004572 {"verify_flags", (getter) get_verify_flags,
4573 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004574 {"verify_mode", (getter) get_verify_mode,
4575 (setter) set_verify_mode, NULL},
4576 {NULL}, /* sentinel */
4577};
4578
4579static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004580 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4581 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4582 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4583 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4584 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4585 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4586 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4587 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4588 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4589 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4590 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004591 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4592 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004593 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004594 {NULL, NULL} /* sentinel */
4595};
4596
4597static PyTypeObject PySSLContext_Type = {
4598 PyVarObject_HEAD_INIT(NULL, 0)
4599 "_ssl._SSLContext", /*tp_name*/
4600 sizeof(PySSLContext), /*tp_basicsize*/
4601 0, /*tp_itemsize*/
4602 (destructor)context_dealloc, /*tp_dealloc*/
4603 0, /*tp_print*/
4604 0, /*tp_getattr*/
4605 0, /*tp_setattr*/
4606 0, /*tp_reserved*/
4607 0, /*tp_repr*/
4608 0, /*tp_as_number*/
4609 0, /*tp_as_sequence*/
4610 0, /*tp_as_mapping*/
4611 0, /*tp_hash*/
4612 0, /*tp_call*/
4613 0, /*tp_str*/
4614 0, /*tp_getattro*/
4615 0, /*tp_setattro*/
4616 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004617 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004618 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004619 (traverseproc) context_traverse, /*tp_traverse*/
4620 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004621 0, /*tp_richcompare*/
4622 0, /*tp_weaklistoffset*/
4623 0, /*tp_iter*/
4624 0, /*tp_iternext*/
4625 context_methods, /*tp_methods*/
4626 0, /*tp_members*/
4627 context_getsetlist, /*tp_getset*/
4628 0, /*tp_base*/
4629 0, /*tp_dict*/
4630 0, /*tp_descr_get*/
4631 0, /*tp_descr_set*/
4632 0, /*tp_dictoffset*/
4633 0, /*tp_init*/
4634 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004635 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004636};
4637
4638
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004639/*
4640 * MemoryBIO objects
4641 */
4642
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004643/*[clinic input]
4644@classmethod
4645_ssl.MemoryBIO.__new__
4646
4647[clinic start generated code]*/
4648
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004649static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004650_ssl_MemoryBIO_impl(PyTypeObject *type)
4651/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004652{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004653 BIO *bio;
4654 PySSLMemoryBIO *self;
4655
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004656 bio = BIO_new(BIO_s_mem());
4657 if (bio == NULL) {
4658 PyErr_SetString(PySSLErrorObject,
4659 "failed to allocate BIO");
4660 return NULL;
4661 }
4662 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4663 * just that no data is currently available. The SSL routines should retry
4664 * the read, which we can achieve by calling BIO_set_retry_read(). */
4665 BIO_set_retry_read(bio);
4666 BIO_set_mem_eof_return(bio, -1);
4667
4668 assert(type != NULL && type->tp_alloc != NULL);
4669 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4670 if (self == NULL) {
4671 BIO_free(bio);
4672 return NULL;
4673 }
4674 self->bio = bio;
4675 self->eof_written = 0;
4676
4677 return (PyObject *) self;
4678}
4679
4680static void
4681memory_bio_dealloc(PySSLMemoryBIO *self)
4682{
4683 BIO_free(self->bio);
4684 Py_TYPE(self)->tp_free(self);
4685}
4686
4687static PyObject *
4688memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4689{
Segev Finer5cff6372017-07-27 01:19:17 +03004690 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004691}
4692
4693PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4694"The number of bytes pending in the memory BIO.");
4695
4696static PyObject *
4697memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4698{
4699 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4700 && self->eof_written);
4701}
4702
4703PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4704"Whether the memory BIO is at EOF.");
4705
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004706/*[clinic input]
4707_ssl.MemoryBIO.read
4708 size as len: int = -1
4709 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004710
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004711Read up to size bytes from the memory BIO.
4712
4713If size is not specified, read the entire buffer.
4714If the return value is an empty bytes instance, this means either
4715EOF or that no data is available. Use the "eof" property to
4716distinguish between the two.
4717[clinic start generated code]*/
4718
4719static PyObject *
4720_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4721/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4722{
4723 int avail, nbytes;
4724 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004725
Segev Finer5cff6372017-07-27 01:19:17 +03004726 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004727 if ((len < 0) || (len > avail))
4728 len = avail;
4729
4730 result = PyBytes_FromStringAndSize(NULL, len);
4731 if ((result == NULL) || (len == 0))
4732 return result;
4733
4734 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004735 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004736 Py_DECREF(result);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004737 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004738 return NULL;
4739 }
4740
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004741 /* There should never be any short reads but check anyway. */
4742 if (nbytes < len) {
4743 _PyBytes_Resize(&result, nbytes);
4744 }
4745
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004746 return result;
4747}
4748
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004749/*[clinic input]
4750_ssl.MemoryBIO.write
4751 b: Py_buffer
4752 /
4753
4754Writes the bytes b into the memory BIO.
4755
4756Returns the number of bytes written.
4757[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004758
4759static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004760_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4761/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004762{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004763 int nbytes;
4764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004765 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004766 PyErr_Format(PyExc_OverflowError,
4767 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004768 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004769 }
4770
4771 if (self->eof_written) {
4772 PyErr_SetString(PySSLErrorObject,
4773 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004774 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004775 }
4776
Segev Finer5cff6372017-07-27 01:19:17 +03004777 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004778 if (nbytes < 0) {
4779 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004780 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004781 }
4782
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004783 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004784}
4785
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004786/*[clinic input]
4787_ssl.MemoryBIO.write_eof
4788
4789Write an EOF marker to the memory BIO.
4790
4791When all data has been read, the "eof" property will be True.
4792[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004793
4794static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004795_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4796/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004797{
4798 self->eof_written = 1;
4799 /* After an EOF is written, a zero return from read() should be a real EOF
4800 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4801 BIO_clear_retry_flags(self->bio);
4802 BIO_set_mem_eof_return(self->bio, 0);
4803
4804 Py_RETURN_NONE;
4805}
4806
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004807static PyGetSetDef memory_bio_getsetlist[] = {
4808 {"pending", (getter) memory_bio_get_pending, NULL,
4809 PySSL_memory_bio_pending_doc},
4810 {"eof", (getter) memory_bio_get_eof, NULL,
4811 PySSL_memory_bio_eof_doc},
4812 {NULL}, /* sentinel */
4813};
4814
4815static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004816 _SSL_MEMORYBIO_READ_METHODDEF
4817 _SSL_MEMORYBIO_WRITE_METHODDEF
4818 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004819 {NULL, NULL} /* sentinel */
4820};
4821
4822static PyTypeObject PySSLMemoryBIO_Type = {
4823 PyVarObject_HEAD_INIT(NULL, 0)
4824 "_ssl.MemoryBIO", /*tp_name*/
4825 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4826 0, /*tp_itemsize*/
4827 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4828 0, /*tp_print*/
4829 0, /*tp_getattr*/
4830 0, /*tp_setattr*/
4831 0, /*tp_reserved*/
4832 0, /*tp_repr*/
4833 0, /*tp_as_number*/
4834 0, /*tp_as_sequence*/
4835 0, /*tp_as_mapping*/
4836 0, /*tp_hash*/
4837 0, /*tp_call*/
4838 0, /*tp_str*/
4839 0, /*tp_getattro*/
4840 0, /*tp_setattro*/
4841 0, /*tp_as_buffer*/
4842 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4843 0, /*tp_doc*/
4844 0, /*tp_traverse*/
4845 0, /*tp_clear*/
4846 0, /*tp_richcompare*/
4847 0, /*tp_weaklistoffset*/
4848 0, /*tp_iter*/
4849 0, /*tp_iternext*/
4850 memory_bio_methods, /*tp_methods*/
4851 0, /*tp_members*/
4852 memory_bio_getsetlist, /*tp_getset*/
4853 0, /*tp_base*/
4854 0, /*tp_dict*/
4855 0, /*tp_descr_get*/
4856 0, /*tp_descr_set*/
4857 0, /*tp_dictoffset*/
4858 0, /*tp_init*/
4859 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004860 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004861};
4862
Antoine Pitrou152efa22010-05-16 18:19:27 +00004863
Christian Heimes99a65702016-09-10 23:44:53 +02004864/*
4865 * SSL Session object
4866 */
4867
4868static void
4869PySSLSession_dealloc(PySSLSession *self)
4870{
INADA Naokia6296d32017-08-24 14:55:17 +09004871 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004872 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004873 Py_XDECREF(self->ctx);
4874 if (self->session != NULL) {
4875 SSL_SESSION_free(self->session);
4876 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004877 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004878}
4879
4880static PyObject *
4881PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4882{
4883 int result;
4884
4885 if (left == NULL || right == NULL) {
4886 PyErr_BadInternalCall();
4887 return NULL;
4888 }
4889
4890 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4891 Py_RETURN_NOTIMPLEMENTED;
4892 }
4893
4894 if (left == right) {
4895 result = 0;
4896 } else {
4897 const unsigned char *left_id, *right_id;
4898 unsigned int left_len, right_len;
4899 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4900 &left_len);
4901 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4902 &right_len);
4903 if (left_len == right_len) {
4904 result = memcmp(left_id, right_id, left_len);
4905 } else {
4906 result = 1;
4907 }
4908 }
4909
4910 switch (op) {
4911 case Py_EQ:
4912 if (result == 0) {
4913 Py_RETURN_TRUE;
4914 } else {
4915 Py_RETURN_FALSE;
4916 }
4917 break;
4918 case Py_NE:
4919 if (result != 0) {
4920 Py_RETURN_TRUE;
4921 } else {
4922 Py_RETURN_FALSE;
4923 }
4924 break;
4925 case Py_LT:
4926 case Py_LE:
4927 case Py_GT:
4928 case Py_GE:
4929 Py_RETURN_NOTIMPLEMENTED;
4930 break;
4931 default:
4932 PyErr_BadArgument();
4933 return NULL;
4934 }
4935}
4936
4937static int
4938PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4939{
4940 Py_VISIT(self->ctx);
4941 return 0;
4942}
4943
4944static int
4945PySSLSession_clear(PySSLSession *self)
4946{
4947 Py_CLEAR(self->ctx);
4948 return 0;
4949}
4950
4951
4952static PyObject *
4953PySSLSession_get_time(PySSLSession *self, void *closure) {
4954 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4955}
4956
4957PyDoc_STRVAR(PySSLSession_get_time_doc,
4958"Session creation time (seconds since epoch).");
4959
4960
4961static PyObject *
4962PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4963 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4964}
4965
4966PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4967"Session timeout (delta in seconds).");
4968
4969
4970static PyObject *
4971PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4972 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4973 return PyLong_FromUnsignedLong(hint);
4974}
4975
4976PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4977"Ticket life time hint.");
4978
4979
4980static PyObject *
4981PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4982 const unsigned char *id;
4983 unsigned int len;
4984 id = SSL_SESSION_get_id(self->session, &len);
4985 return PyBytes_FromStringAndSize((const char *)id, len);
4986}
4987
4988PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4989"Session id");
4990
4991
4992static PyObject *
4993PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4994 if (SSL_SESSION_has_ticket(self->session)) {
4995 Py_RETURN_TRUE;
4996 } else {
4997 Py_RETURN_FALSE;
4998 }
4999}
5000
5001PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5002"Does the session contain a ticket?");
5003
5004
5005static PyGetSetDef PySSLSession_getsetlist[] = {
5006 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5007 PySSLSession_get_has_ticket_doc},
5008 {"id", (getter) PySSLSession_get_session_id, NULL,
5009 PySSLSession_get_session_id_doc},
5010 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5011 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5012 {"time", (getter) PySSLSession_get_time, NULL,
5013 PySSLSession_get_time_doc},
5014 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5015 PySSLSession_get_timeout_doc},
5016 {NULL}, /* sentinel */
5017};
5018
5019static PyTypeObject PySSLSession_Type = {
5020 PyVarObject_HEAD_INIT(NULL, 0)
5021 "_ssl.Session", /*tp_name*/
5022 sizeof(PySSLSession), /*tp_basicsize*/
5023 0, /*tp_itemsize*/
5024 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
5025 0, /*tp_print*/
5026 0, /*tp_getattr*/
5027 0, /*tp_setattr*/
5028 0, /*tp_reserved*/
5029 0, /*tp_repr*/
5030 0, /*tp_as_number*/
5031 0, /*tp_as_sequence*/
5032 0, /*tp_as_mapping*/
5033 0, /*tp_hash*/
5034 0, /*tp_call*/
5035 0, /*tp_str*/
5036 0, /*tp_getattro*/
5037 0, /*tp_setattro*/
5038 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005039 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005040 0, /*tp_doc*/
5041 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5042 (inquiry)PySSLSession_clear, /*tp_clear*/
5043 PySSLSession_richcompare, /*tp_richcompare*/
5044 0, /*tp_weaklistoffset*/
5045 0, /*tp_iter*/
5046 0, /*tp_iternext*/
5047 0, /*tp_methods*/
5048 0, /*tp_members*/
5049 PySSLSession_getsetlist, /*tp_getset*/
5050};
5051
5052
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005053/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005054/*[clinic input]
5055_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005056 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005057 entropy: double
5058 /
5059
5060Mix string into the OpenSSL PRNG state.
5061
5062entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305063string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005064[clinic start generated code]*/
5065
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005067_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005068/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005069{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005070 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005071 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005072
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005073 buf = (const char *)view->buf;
5074 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005075 do {
5076 written = Py_MIN(len, INT_MAX);
5077 RAND_add(buf, (int)written, entropy);
5078 buf += written;
5079 len -= written;
5080 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005081 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005082}
5083
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005084static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005085PySSL_RAND(int len, int pseudo)
5086{
5087 int ok;
5088 PyObject *bytes;
5089 unsigned long err;
5090 const char *errstr;
5091 PyObject *v;
5092
Victor Stinner1e81a392013-12-19 16:47:04 +01005093 if (len < 0) {
5094 PyErr_SetString(PyExc_ValueError, "num must be positive");
5095 return NULL;
5096 }
5097
Victor Stinner99c8b162011-05-24 12:05:19 +02005098 bytes = PyBytes_FromStringAndSize(NULL, len);
5099 if (bytes == NULL)
5100 return NULL;
5101 if (pseudo) {
5102 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5103 if (ok == 0 || ok == 1)
5104 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5105 }
5106 else {
5107 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5108 if (ok == 1)
5109 return bytes;
5110 }
5111 Py_DECREF(bytes);
5112
5113 err = ERR_get_error();
5114 errstr = ERR_reason_error_string(err);
5115 v = Py_BuildValue("(ks)", err, errstr);
5116 if (v != NULL) {
5117 PyErr_SetObject(PySSLErrorObject, v);
5118 Py_DECREF(v);
5119 }
5120 return NULL;
5121}
5122
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005123/*[clinic input]
5124_ssl.RAND_bytes
5125 n: int
5126 /
5127
5128Generate n cryptographically strong pseudo-random bytes.
5129[clinic start generated code]*/
5130
Victor Stinner99c8b162011-05-24 12:05:19 +02005131static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005132_ssl_RAND_bytes_impl(PyObject *module, int n)
5133/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005134{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005135 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005136}
5137
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005138/*[clinic input]
5139_ssl.RAND_pseudo_bytes
5140 n: int
5141 /
5142
5143Generate n pseudo-random bytes.
5144
5145Return a pair (bytes, is_cryptographic). is_cryptographic is True
5146if the bytes generated are cryptographically strong.
5147[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005148
5149static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005150_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5151/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005152{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005153 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005154}
5155
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005156/*[clinic input]
5157_ssl.RAND_status
5158
5159Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5160
5161It is necessary to seed the PRNG with RAND_add() on some platforms before
5162using the ssl() function.
5163[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005164
5165static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005166_ssl_RAND_status_impl(PyObject *module)
5167/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005168{
Christian Heimes217cfd12007-12-02 14:31:20 +00005169 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005170}
5171
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005172#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005173/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005174/*[clinic input]
5175_ssl.RAND_egd
5176 path: object(converter="PyUnicode_FSConverter")
5177 /
5178
5179Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5180
5181Returns number of bytes read. Raises SSLError if connection to EGD
5182fails or if it does not provide enough data to seed PRNG.
5183[clinic start generated code]*/
5184
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005185static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005186_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5187/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005188{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005189 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005190 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005191 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005192 PyErr_SetString(PySSLErrorObject,
5193 "EGD connection failed or EGD did not return "
5194 "enough data to seed the PRNG");
5195 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005196 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005197 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005198}
Christian Heimesa5d07652016-09-24 10:48:05 +02005199/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005200#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005201
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005202
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005203
5204/*[clinic input]
5205_ssl.get_default_verify_paths
5206
5207Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5208
5209The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5210[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005211
5212static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005213_ssl_get_default_verify_paths_impl(PyObject *module)
5214/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005215{
5216 PyObject *ofile_env = NULL;
5217 PyObject *ofile = NULL;
5218 PyObject *odir_env = NULL;
5219 PyObject *odir = NULL;
5220
Benjamin Petersond113c962015-07-18 10:59:13 -07005221#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005222 const char *tmp = (info); \
5223 target = NULL; \
5224 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5225 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5226 target = PyBytes_FromString(tmp); } \
5227 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005228 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005229
Benjamin Petersond113c962015-07-18 10:59:13 -07005230 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5231 CONVERT(X509_get_default_cert_file(), ofile);
5232 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5233 CONVERT(X509_get_default_cert_dir(), odir);
5234#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005235
Christian Heimes200bb1b2013-06-14 15:14:29 +02005236 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005237
5238 error:
5239 Py_XDECREF(ofile_env);
5240 Py_XDECREF(ofile);
5241 Py_XDECREF(odir_env);
5242 Py_XDECREF(odir);
5243 return NULL;
5244}
5245
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005246static PyObject*
5247asn1obj2py(ASN1_OBJECT *obj)
5248{
5249 int nid;
5250 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005251
5252 nid = OBJ_obj2nid(obj);
5253 if (nid == NID_undef) {
5254 PyErr_Format(PyExc_ValueError, "Unknown object");
5255 return NULL;
5256 }
5257 sn = OBJ_nid2sn(nid);
5258 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005259 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005260}
5261
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005262/*[clinic input]
5263_ssl.txt2obj
5264 txt: str
5265 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005266
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005267Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5268
5269By default objects are looked up by OID. With name=True short and
5270long name are also matched.
5271[clinic start generated code]*/
5272
5273static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005274_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5275/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005276{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005277 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005278 ASN1_OBJECT *obj;
5279
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005280 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5281 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005282 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005283 return NULL;
5284 }
5285 result = asn1obj2py(obj);
5286 ASN1_OBJECT_free(obj);
5287 return result;
5288}
5289
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005290/*[clinic input]
5291_ssl.nid2obj
5292 nid: int
5293 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005294
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005295Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5296[clinic start generated code]*/
5297
5298static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005299_ssl_nid2obj_impl(PyObject *module, int nid)
5300/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005301{
5302 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005303 ASN1_OBJECT *obj;
5304
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005305 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005306 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005307 return NULL;
5308 }
5309 obj = OBJ_nid2obj(nid);
5310 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005311 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005312 return NULL;
5313 }
5314 result = asn1obj2py(obj);
5315 ASN1_OBJECT_free(obj);
5316 return result;
5317}
5318
Christian Heimes46bebee2013-06-09 19:03:31 +02005319#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005320
5321static PyObject*
5322certEncodingType(DWORD encodingType)
5323{
5324 static PyObject *x509_asn = NULL;
5325 static PyObject *pkcs_7_asn = NULL;
5326
5327 if (x509_asn == NULL) {
5328 x509_asn = PyUnicode_InternFromString("x509_asn");
5329 if (x509_asn == NULL)
5330 return NULL;
5331 }
5332 if (pkcs_7_asn == NULL) {
5333 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5334 if (pkcs_7_asn == NULL)
5335 return NULL;
5336 }
5337 switch(encodingType) {
5338 case X509_ASN_ENCODING:
5339 Py_INCREF(x509_asn);
5340 return x509_asn;
5341 case PKCS_7_ASN_ENCODING:
5342 Py_INCREF(pkcs_7_asn);
5343 return pkcs_7_asn;
5344 default:
5345 return PyLong_FromLong(encodingType);
5346 }
5347}
5348
5349static PyObject*
5350parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5351{
5352 CERT_ENHKEY_USAGE *usage;
5353 DWORD size, error, i;
5354 PyObject *retval;
5355
5356 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5357 error = GetLastError();
5358 if (error == CRYPT_E_NOT_FOUND) {
5359 Py_RETURN_TRUE;
5360 }
5361 return PyErr_SetFromWindowsErr(error);
5362 }
5363
5364 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5365 if (usage == NULL) {
5366 return PyErr_NoMemory();
5367 }
5368
5369 /* Now get the actual enhanced usage property */
5370 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5371 PyMem_Free(usage);
5372 error = GetLastError();
5373 if (error == CRYPT_E_NOT_FOUND) {
5374 Py_RETURN_TRUE;
5375 }
5376 return PyErr_SetFromWindowsErr(error);
5377 }
5378 retval = PySet_New(NULL);
5379 if (retval == NULL) {
5380 goto error;
5381 }
5382 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5383 if (usage->rgpszUsageIdentifier[i]) {
5384 PyObject *oid;
5385 int err;
5386 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5387 if (oid == NULL) {
5388 Py_CLEAR(retval);
5389 goto error;
5390 }
5391 err = PySet_Add(retval, oid);
5392 Py_DECREF(oid);
5393 if (err == -1) {
5394 Py_CLEAR(retval);
5395 goto error;
5396 }
5397 }
5398 }
5399 error:
5400 PyMem_Free(usage);
5401 return retval;
5402}
5403
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005404static HCERTSTORE
5405ssl_collect_certificates(const char *store_name)
5406{
5407/* this function collects the system certificate stores listed in
5408 * system_stores into a collection certificate store for being
5409 * enumerated. The store must be readable to be added to the
5410 * store collection.
5411 */
5412
5413 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5414 static DWORD system_stores[] = {
5415 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5416 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5417 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5418 CERT_SYSTEM_STORE_CURRENT_USER,
5419 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5420 CERT_SYSTEM_STORE_SERVICES,
5421 CERT_SYSTEM_STORE_USERS};
5422 size_t i, storesAdded;
5423 BOOL result;
5424
5425 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5426 (HCRYPTPROV)NULL, 0, NULL);
5427 if (!hCollectionStore) {
5428 return NULL;
5429 }
5430 storesAdded = 0;
5431 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5432 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5433 (HCRYPTPROV)NULL,
5434 CERT_STORE_READONLY_FLAG |
5435 system_stores[i], store_name);
5436 if (hSystemStore) {
5437 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5438 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5439 if (result) {
5440 ++storesAdded;
5441 }
5442 }
5443 }
5444 if (storesAdded == 0) {
5445 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5446 return NULL;
5447 }
5448
5449 return hCollectionStore;
5450}
5451
5452/* code from Objects/listobject.c */
5453
5454static int
5455list_contains(PyListObject *a, PyObject *el)
5456{
5457 Py_ssize_t i;
5458 int cmp;
5459
5460 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
5461 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
5462 Py_EQ);
5463 return cmp;
5464}
5465
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005466/*[clinic input]
5467_ssl.enum_certificates
5468 store_name: str
5469
5470Retrieve certificates from Windows' cert store.
5471
5472store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5473more cert storages, too. The function returns a list of (bytes,
5474encoding_type, trust) tuples. The encoding_type flag can be interpreted
5475with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5476a set of OIDs or the boolean True.
5477[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005478
Christian Heimes46bebee2013-06-09 19:03:31 +02005479static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005480_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5481/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005482{
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005483 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005484 PCCERT_CONTEXT pCertCtx = NULL;
5485 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005486 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005487
Christian Heimes44109d72013-11-22 01:51:30 +01005488 result = PyList_New(0);
5489 if (result == NULL) {
5490 return NULL;
5491 }
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005492 hCollectionStore = ssl_collect_certificates(store_name);
5493 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005494 Py_DECREF(result);
5495 return PyErr_SetFromWindowsErr(GetLastError());
5496 }
5497
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005498 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005499 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5500 pCertCtx->cbCertEncoded);
5501 if (!cert) {
5502 Py_CLEAR(result);
5503 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005504 }
Christian Heimes44109d72013-11-22 01:51:30 +01005505 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5506 Py_CLEAR(result);
5507 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005508 }
Christian Heimes44109d72013-11-22 01:51:30 +01005509 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5510 if (keyusage == Py_True) {
5511 Py_DECREF(keyusage);
5512 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005513 }
Christian Heimes44109d72013-11-22 01:51:30 +01005514 if (keyusage == NULL) {
5515 Py_CLEAR(result);
5516 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005517 }
Christian Heimes44109d72013-11-22 01:51:30 +01005518 if ((tup = PyTuple_New(3)) == NULL) {
5519 Py_CLEAR(result);
5520 break;
5521 }
5522 PyTuple_SET_ITEM(tup, 0, cert);
5523 cert = NULL;
5524 PyTuple_SET_ITEM(tup, 1, enc);
5525 enc = NULL;
5526 PyTuple_SET_ITEM(tup, 2, keyusage);
5527 keyusage = NULL;
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005528 if (!list_contains((PyListObject*)result, tup)) {
5529 if (PyList_Append(result, tup) < 0) {
5530 Py_CLEAR(result);
5531 break;
5532 }
Christian Heimes44109d72013-11-22 01:51:30 +01005533 }
5534 Py_CLEAR(tup);
5535 }
5536 if (pCertCtx) {
5537 /* loop ended with an error, need to clean up context manually */
5538 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005539 }
5540
5541 /* In error cases cert, enc and tup may not be NULL */
5542 Py_XDECREF(cert);
5543 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005544 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005545 Py_XDECREF(tup);
5546
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005547 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5548 associated with the store, in this case our collection store and the
5549 associated system stores. */
5550 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005551 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005552 Py_XDECREF(result);
5553 return PyErr_SetFromWindowsErr(GetLastError());
5554 }
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005555
Christian Heimes44109d72013-11-22 01:51:30 +01005556 return result;
5557}
5558
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005559/*[clinic input]
5560_ssl.enum_crls
5561 store_name: str
5562
5563Retrieve CRLs from Windows' cert store.
5564
5565store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5566more cert storages, too. The function returns a list of (bytes,
5567encoding_type) tuples. The encoding_type flag can be interpreted with
5568X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5569[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005570
5571static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005572_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5573/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005574{
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005575 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005576 PCCRL_CONTEXT pCrlCtx = NULL;
5577 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5578 PyObject *result = NULL;
5579
Christian Heimes44109d72013-11-22 01:51:30 +01005580 result = PyList_New(0);
5581 if (result == NULL) {
5582 return NULL;
5583 }
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005584 hCollectionStore = ssl_collect_certificates(store_name);
5585 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005586 Py_DECREF(result);
5587 return PyErr_SetFromWindowsErr(GetLastError());
5588 }
Christian Heimes44109d72013-11-22 01:51:30 +01005589
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005590 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005591 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5592 pCrlCtx->cbCrlEncoded);
5593 if (!crl) {
5594 Py_CLEAR(result);
5595 break;
5596 }
5597 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5598 Py_CLEAR(result);
5599 break;
5600 }
5601 if ((tup = PyTuple_New(2)) == NULL) {
5602 Py_CLEAR(result);
5603 break;
5604 }
5605 PyTuple_SET_ITEM(tup, 0, crl);
5606 crl = NULL;
5607 PyTuple_SET_ITEM(tup, 1, enc);
5608 enc = NULL;
5609
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005610 if (!list_contains((PyListObject*)result, tup)) {
5611 if (PyList_Append(result, tup) < 0) {
5612 Py_CLEAR(result);
5613 break;
5614 }
Christian Heimes44109d72013-11-22 01:51:30 +01005615 }
5616 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005617 }
Christian Heimes44109d72013-11-22 01:51:30 +01005618 if (pCrlCtx) {
5619 /* loop ended with an error, need to clean up context manually */
5620 CertFreeCRLContext(pCrlCtx);
5621 }
5622
5623 /* In error cases cert, enc and tup may not be NULL */
5624 Py_XDECREF(crl);
5625 Py_XDECREF(enc);
5626 Py_XDECREF(tup);
5627
Miss Islington (bot)e9868c52019-03-28 11:56:50 -07005628 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5629 associated with the store, in this case our collection store and the
5630 associated system stores. */
5631 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005632 /* This error case might shadow another exception.*/
5633 Py_XDECREF(result);
5634 return PyErr_SetFromWindowsErr(GetLastError());
5635 }
5636 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005637}
Christian Heimes44109d72013-11-22 01:51:30 +01005638
5639#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005640
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005641/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005642static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005643 _SSL__TEST_DECODE_CERT_METHODDEF
5644 _SSL_RAND_ADD_METHODDEF
5645 _SSL_RAND_BYTES_METHODDEF
5646 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5647 _SSL_RAND_EGD_METHODDEF
5648 _SSL_RAND_STATUS_METHODDEF
5649 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5650 _SSL_ENUM_CERTIFICATES_METHODDEF
5651 _SSL_ENUM_CRLS_METHODDEF
5652 _SSL_TXT2OBJ_METHODDEF
5653 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005654 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005655};
5656
5657
Christian Heimes598894f2016-09-05 23:19:05 +02005658#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005659
5660/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005661 * of the Python C thread library
5662 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5663 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005664
5665static PyThread_type_lock *_ssl_locks = NULL;
5666
Christian Heimes4d98ca92013-08-19 17:36:29 +02005667#if OPENSSL_VERSION_NUMBER >= 0x10000000
5668/* use new CRYPTO_THREADID API. */
5669static void
5670_ssl_threadid_callback(CRYPTO_THREADID *id)
5671{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005672 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005673}
5674#else
5675/* deprecated CRYPTO_set_id_callback() API. */
5676static unsigned long
5677_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005678 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005679}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005680#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005681
Bill Janssen6e027db2007-11-15 22:23:56 +00005682static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005683 (int mode, int n, const char *file, int line) {
5684 /* this function is needed to perform locking on shared data
5685 structures. (Note that OpenSSL uses a number of global data
5686 structures that will be implicitly shared whenever multiple
5687 threads use OpenSSL.) Multi-threaded applications will
5688 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005689
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005690 locking_function() must be able to handle up to
5691 CRYPTO_num_locks() different mutex locks. It sets the n-th
5692 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005694 file and line are the file number of the function setting the
5695 lock. They can be useful for debugging.
5696 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005698 if ((_ssl_locks == NULL) ||
5699 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5700 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005702 if (mode & CRYPTO_LOCK) {
5703 PyThread_acquire_lock(_ssl_locks[n], 1);
5704 } else {
5705 PyThread_release_lock(_ssl_locks[n]);
5706 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005707}
5708
5709static int _setup_ssl_threads(void) {
5710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005711 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005713 if (_ssl_locks == NULL) {
5714 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005715 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5716 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005717 if (_ssl_locks == NULL) {
5718 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005719 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005720 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005721 for (i = 0; i < _ssl_locks_count; i++) {
5722 _ssl_locks[i] = PyThread_allocate_lock();
5723 if (_ssl_locks[i] == NULL) {
5724 unsigned int j;
5725 for (j = 0; j < i; j++) {
5726 PyThread_free_lock(_ssl_locks[j]);
5727 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005728 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005729 return 0;
5730 }
5731 }
5732 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005733#if OPENSSL_VERSION_NUMBER >= 0x10000000
5734 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5735#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005736 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005737#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005738 }
5739 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005740}
5741
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005742#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005743
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005744PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005745"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005746for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005747
Martin v. Löwis1a214512008-06-11 05:26:20 +00005748
5749static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005750 PyModuleDef_HEAD_INIT,
5751 "_ssl",
5752 module_doc,
5753 -1,
5754 PySSL_methods,
5755 NULL,
5756 NULL,
5757 NULL,
5758 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005759};
5760
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005761
5762static void
5763parse_openssl_version(unsigned long libver,
5764 unsigned int *major, unsigned int *minor,
5765 unsigned int *fix, unsigned int *patch,
5766 unsigned int *status)
5767{
5768 *status = libver & 0xF;
5769 libver >>= 4;
5770 *patch = libver & 0xFF;
5771 libver >>= 8;
5772 *fix = libver & 0xFF;
5773 libver >>= 8;
5774 *minor = libver & 0xFF;
5775 libver >>= 8;
5776 *major = libver & 0xFF;
5777}
5778
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005779PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005780PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005781{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005782 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005783 unsigned long libver;
5784 unsigned int major, minor, fix, patch, status;
5785 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005786 struct py_ssl_error_code *errcode;
5787 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005788
Antoine Pitrou152efa22010-05-16 18:19:27 +00005789 if (PyType_Ready(&PySSLContext_Type) < 0)
5790 return NULL;
5791 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005792 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005793 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5794 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005795 if (PyType_Ready(&PySSLSession_Type) < 0)
5796 return NULL;
5797
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005799 m = PyModule_Create(&_sslmodule);
5800 if (m == NULL)
5801 return NULL;
5802 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005804 /* Load _socket module and its C API */
5805 socket_api = PySocketModule_ImportModuleAndAPI();
5806 if (!socket_api)
5807 return NULL;
5808 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005809
Christian Heimesc941e622017-09-05 15:47:11 +02005810#ifndef OPENSSL_VERSION_1_1
5811 /* Load all algorithms and initialize cpuid */
5812 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005813 /* Init OpenSSL */
5814 SSL_load_error_strings();
5815 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005816#endif
5817
Christian Heimes598894f2016-09-05 23:19:05 +02005818#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005819 /* note that this will start threading if not already started */
5820 if (!_setup_ssl_threads()) {
5821 return NULL;
5822 }
Christian Heimes598894f2016-09-05 23:19:05 +02005823#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5824 /* OpenSSL 1.1.0 builtin thread support is enabled */
5825 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005826#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005828 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005829 sslerror_type_slots[0].pfunc = PyExc_OSError;
5830 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005831 if (PySSLErrorObject == NULL)
5832 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005833
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005834 /* ssl.CertificateError used to be a subclass of ValueError */
5835 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5836 if (bases == NULL)
5837 return NULL;
5838 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5839 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5840 bases, NULL);
5841 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005842 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5843 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5844 PySSLErrorObject, NULL);
5845 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5846 "ssl.SSLWantReadError", SSLWantReadError_doc,
5847 PySSLErrorObject, NULL);
5848 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5849 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5850 PySSLErrorObject, NULL);
5851 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5852 "ssl.SSLSyscallError", SSLSyscallError_doc,
5853 PySSLErrorObject, NULL);
5854 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5855 "ssl.SSLEOFError", SSLEOFError_doc,
5856 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005857 if (PySSLCertVerificationErrorObject == NULL
5858 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005859 || PySSLWantReadErrorObject == NULL
5860 || PySSLWantWriteErrorObject == NULL
5861 || PySSLSyscallErrorObject == NULL
5862 || PySSLEOFErrorObject == NULL)
5863 return NULL;
5864 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005865 || PyDict_SetItemString(d, "SSLCertVerificationError",
5866 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005867 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5868 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5869 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5870 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5871 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005872 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005873 if (PyDict_SetItemString(d, "_SSLContext",
5874 (PyObject *)&PySSLContext_Type) != 0)
5875 return NULL;
5876 if (PyDict_SetItemString(d, "_SSLSocket",
5877 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005878 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005879 if (PyDict_SetItemString(d, "MemoryBIO",
5880 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5881 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005882 if (PyDict_SetItemString(d, "SSLSession",
5883 (PyObject *)&PySSLSession_Type) != 0)
5884 return NULL;
5885
Christian Heimes892d66e2018-01-29 14:10:18 +01005886 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5887 PY_SSL_DEFAULT_CIPHER_STRING);
5888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005889 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5890 PY_SSL_ERROR_ZERO_RETURN);
5891 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5892 PY_SSL_ERROR_WANT_READ);
5893 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5894 PY_SSL_ERROR_WANT_WRITE);
5895 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5896 PY_SSL_ERROR_WANT_X509_LOOKUP);
5897 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5898 PY_SSL_ERROR_SYSCALL);
5899 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5900 PY_SSL_ERROR_SSL);
5901 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5902 PY_SSL_ERROR_WANT_CONNECT);
5903 /* non ssl.h errorcodes */
5904 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5905 PY_SSL_ERROR_EOF);
5906 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5907 PY_SSL_ERROR_INVALID_ERROR_CODE);
5908 /* cert requirements */
5909 PyModule_AddIntConstant(m, "CERT_NONE",
5910 PY_SSL_CERT_NONE);
5911 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5912 PY_SSL_CERT_OPTIONAL);
5913 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5914 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005915 /* CRL verification for verification_flags */
5916 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5917 0);
5918 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5919 X509_V_FLAG_CRL_CHECK);
5920 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5921 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5922 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5923 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005924#ifdef X509_V_FLAG_TRUSTED_FIRST
5925 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5926 X509_V_FLAG_TRUSTED_FIRST);
5927#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005928
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005929 /* Alert Descriptions from ssl.h */
5930 /* note RESERVED constants no longer intended for use have been removed */
5931 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5932
5933#define ADD_AD_CONSTANT(s) \
5934 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5935 SSL_AD_##s)
5936
5937 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5938 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5939 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5940 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5941 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5942 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5943 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5944 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5945 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5946 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5947 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5948 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5949 ADD_AD_CONSTANT(UNKNOWN_CA);
5950 ADD_AD_CONSTANT(ACCESS_DENIED);
5951 ADD_AD_CONSTANT(DECODE_ERROR);
5952 ADD_AD_CONSTANT(DECRYPT_ERROR);
5953 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5954 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5955 ADD_AD_CONSTANT(INTERNAL_ERROR);
5956 ADD_AD_CONSTANT(USER_CANCELLED);
5957 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005958 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005959#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5960 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5961#endif
5962#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5963 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5964#endif
5965#ifdef SSL_AD_UNRECOGNIZED_NAME
5966 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5967#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005968#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5969 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5970#endif
5971#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5972 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5973#endif
5974#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5975 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5976#endif
5977
5978#undef ADD_AD_CONSTANT
5979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005980 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005981#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005982 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5983 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005984#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005985#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005986 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5987 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005988#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005989 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005990 PY_SSL_VERSION_TLS);
5991 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5992 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005993 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5994 PY_SSL_VERSION_TLS_CLIENT);
5995 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5996 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005997 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5998 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005999#if HAVE_TLSv1_2
6000 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6001 PY_SSL_VERSION_TLS1_1);
6002 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6003 PY_SSL_VERSION_TLS1_2);
6004#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006005
Antoine Pitroub5218772010-05-21 09:56:06 +00006006 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006007 PyModule_AddIntConstant(m, "OP_ALL",
6008 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006009 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6010 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6011 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006012#if HAVE_TLSv1_2
6013 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6014 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6015#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006016#ifdef SSL_OP_NO_TLSv1_3
6017 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6018#else
6019 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6020#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006021 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6022 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006023 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006024 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006025#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006026 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006027#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006028#ifdef SSL_OP_NO_COMPRESSION
6029 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6030 SSL_OP_NO_COMPRESSION);
6031#endif
Miss Islington (bot)2614ed42018-02-27 00:17:49 -08006032#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6033 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6034 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6035#endif
Miss Islington (bot)e2db6ad2018-05-16 07:26:19 -07006036#ifdef SSL_OP_NO_RENEGOTIATION
6037 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6038 SSL_OP_NO_RENEGOTIATION);
6039#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006040
Christian Heimes61d478c2018-01-27 15:51:38 +01006041#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6042 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6043 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6044#endif
6045#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6046 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6047 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6048#endif
6049#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6050 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6051 X509_CHECK_FLAG_NO_WILDCARDS);
6052#endif
6053#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6054 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6055 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6056#endif
6057#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6058 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6059 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6060#endif
6061#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6062 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6063 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6064#endif
6065
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006066 /* protocol versions */
6067 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6068 PY_PROTO_MINIMUM_SUPPORTED);
6069 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6070 PY_PROTO_MAXIMUM_SUPPORTED);
6071 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6072 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6073 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6074 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6075 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006076
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006077#define addbool(m, v, b) \
6078 Py_INCREF((b) ? Py_True : Py_False); \
6079 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
6080
6081#if HAVE_SNI
6082 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006083#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006084 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006085#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006086
6087 addbool(m, "HAS_TLS_UNIQUE", 1);
6088
6089#ifndef OPENSSL_NO_ECDH
6090 addbool(m, "HAS_ECDH", 1);
6091#else
6092 addbool(m, "HAS_ECDH", 0);
6093#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006094
Miss Islington (bot)96177412018-02-25 04:18:43 -08006095#if HAVE_NPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006096 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006097#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006098 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006099#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006100
Miss Islington (bot)96177412018-02-25 04:18:43 -08006101#if HAVE_ALPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006102 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006103#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006104 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006105#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006106
6107#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6108 addbool(m, "HAS_SSLv2", 1);
6109#else
6110 addbool(m, "HAS_SSLv2", 0);
6111#endif
6112
6113#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6114 addbool(m, "HAS_SSLv3", 1);
6115#else
6116 addbool(m, "HAS_SSLv3", 0);
6117#endif
6118
6119#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6120 addbool(m, "HAS_TLSv1", 1);
6121#else
6122 addbool(m, "HAS_TLSv1", 0);
6123#endif
6124
6125#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6126 addbool(m, "HAS_TLSv1_1", 1);
6127#else
6128 addbool(m, "HAS_TLSv1_1", 0);
6129#endif
6130
6131#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6132 addbool(m, "HAS_TLSv1_2", 1);
6133#else
6134 addbool(m, "HAS_TLSv1_2", 0);
6135#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006136
Christian Heimescb5b68a2017-09-07 18:07:00 -07006137#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006138 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006139#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006140 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006141#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006142
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006143 /* Mappings for error codes */
6144 err_codes_to_names = PyDict_New();
6145 err_names_to_codes = PyDict_New();
6146 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6147 return NULL;
6148 errcode = error_codes;
6149 while (errcode->mnemonic != NULL) {
6150 PyObject *mnemo, *key;
6151 mnemo = PyUnicode_FromString(errcode->mnemonic);
6152 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6153 if (mnemo == NULL || key == NULL)
6154 return NULL;
6155 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6156 return NULL;
6157 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6158 return NULL;
6159 Py_DECREF(key);
6160 Py_DECREF(mnemo);
6161 errcode++;
6162 }
6163 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6164 return NULL;
6165 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6166 return NULL;
6167
6168 lib_codes_to_names = PyDict_New();
6169 if (lib_codes_to_names == NULL)
6170 return NULL;
6171 libcode = library_codes;
6172 while (libcode->library != NULL) {
6173 PyObject *mnemo, *key;
6174 key = PyLong_FromLong(libcode->code);
6175 mnemo = PyUnicode_FromString(libcode->library);
6176 if (key == NULL || mnemo == NULL)
6177 return NULL;
6178 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6179 return NULL;
6180 Py_DECREF(key);
6181 Py_DECREF(mnemo);
6182 libcode++;
6183 }
6184 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6185 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006187 /* OpenSSL version */
6188 /* SSLeay() gives us the version of the library linked against,
6189 which could be different from the headers version.
6190 */
6191 libver = SSLeay();
6192 r = PyLong_FromUnsignedLong(libver);
6193 if (r == NULL)
6194 return NULL;
6195 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6196 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006197 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006198 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6199 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6200 return NULL;
6201 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6202 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6203 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006204
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006205 libver = OPENSSL_VERSION_NUMBER;
6206 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6207 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6208 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6209 return NULL;
6210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006211 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006212}