blob: f9d1b8c308770d37eaaf21cc4ac325fec3dd01db [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
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200915 SSL_set_app_data(self->ssl, self);
916 if (sock) {
917 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
918 } else {
919 /* BIOs are reference counted and SSL_set_bio borrows our reference.
920 * To prevent a double free in memory_bio_dealloc() we need to take an
921 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200922 BIO_up_ref(inbio->bio);
923 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200924 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
925 }
Miss Islington (bot)67d19682018-05-14 10:45:45 -0700926 SSL_set_mode(self->ssl,
927 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000928
Christian Heimes61d478c2018-01-27 15:51:38 +0100929 if (server_hostname != NULL) {
930 if (_ssl_configure_hostname(self, server_hostname) < 0) {
931 Py_DECREF(self);
932 return NULL;
933 }
934 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 /* If the socket is in non-blocking mode or timeout mode, set the BIO
936 * to non-blocking mode (blocking is the default)
937 */
Victor Stinnere2452312015-03-28 03:00:46 +0100938 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
940 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
941 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 PySSL_BEGIN_ALLOW_THREADS
944 if (socket_type == PY_SSL_CLIENT)
945 SSL_set_connect_state(self->ssl);
946 else
947 SSL_set_accept_state(self->ssl);
948 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000949
Antoine Pitroud6494802011-07-21 01:11:30 +0200950 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200951 if (sock != NULL) {
952 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
953 if (self->Socket == NULL) {
954 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200955 return NULL;
956 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100957 }
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800958 if (owner && owner != Py_None) {
959 if (PySSL_set_owner(self, owner, NULL) == -1) {
960 Py_DECREF(self);
961 return NULL;
962 }
963 }
964 if (session && session != Py_None) {
965 if (PySSL_set_session(self, session, NULL) == -1) {
966 Py_DECREF(self);
967 return NULL;
968 }
969 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000971}
972
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000973/* SSL object methods */
974
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300975/*[clinic input]
976_ssl._SSLSocket.do_handshake
977[clinic start generated code]*/
978
979static PyObject *
980_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
981/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000982{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 int ret;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700984 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200986 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200987 _PyTime_t timeout, deadline = 0;
988 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000989
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200990 if (sock) {
991 if (((PyObject*)sock) == Py_None) {
992 _setSSLError("Underlying socket connection gone",
993 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
994 return NULL;
995 }
996 Py_INCREF(sock);
997
998 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100999 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001000 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1001 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001003
Victor Stinner14690702015-04-06 22:46:13 +02001004 timeout = GET_SOCKET_TIMEOUT(sock);
1005 has_timeout = (timeout > 0);
1006 if (has_timeout)
1007 deadline = _PyTime_GetMonotonicClock() + timeout;
1008
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 /* Actually negotiate SSL connection */
1010 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001012 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 ret = SSL_do_handshake(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001014 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07001016 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001017
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001018 if (PyErr_CheckSignals())
1019 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001020
Victor Stinner14690702015-04-06 22:46:13 +02001021 if (has_timeout)
1022 timeout = deadline - _PyTime_GetMonotonicClock();
1023
Miss Islington (bot)12296642018-09-17 12:12:13 -07001024 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001025 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001026 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001027 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 } else {
1029 sockstate = SOCKET_OPERATION_OK;
1030 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001033 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001034 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001035 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1037 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001038 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001039 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1041 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001042 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001043 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1045 break;
1046 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07001047 } while (err.ssl == SSL_ERROR_WANT_READ ||
1048 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001049 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 if (ret < 1)
1051 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001052
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001053 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001054
1055error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001056 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001057 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001058}
1059
Thomas Woutersed03b412007-08-28 21:37:11 +00001060static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001061_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1062{
1063 char buf[X509_NAME_MAXLEN];
1064 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001066 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001067
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001068 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 if (buflen < 0) {
1070 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001071 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001073 /* initial buffer is too small for oid + terminating null byte */
1074 if (buflen > X509_NAME_MAXLEN - 1) {
1075 /* make OBJ_obj2txt() calculate the required buflen */
1076 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1077 /* allocate len + 1 for terminating NULL byte */
1078 namebuf = PyMem_Malloc(buflen + 1);
1079 if (namebuf == NULL) {
1080 PyErr_NoMemory();
1081 return NULL;
1082 }
1083 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1084 if (buflen < 0) {
1085 _setSSLError(NULL, 0, __FILE__, __LINE__);
1086 goto done;
1087 }
1088 }
1089 if (!buflen && no_name) {
1090 Py_INCREF(Py_None);
1091 name_obj = Py_None;
1092 }
1093 else {
1094 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1095 }
1096
1097 done:
1098 if (buf != namebuf) {
1099 PyMem_Free(namebuf);
1100 }
1101 return name_obj;
1102}
1103
1104static PyObject *
1105_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1106{
1107 Py_ssize_t buflen;
1108 unsigned char *valuebuf = NULL;
1109 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1112 if (buflen < 0) {
1113 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001114 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001116 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001119}
1120
1121static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001123{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1125 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1126 PyObject *rdnt;
1127 PyObject *attr = NULL; /* tuple to hold an attribute */
1128 int entry_count = X509_NAME_entry_count(xname);
1129 X509_NAME_ENTRY *entry;
1130 ASN1_OBJECT *name;
1131 ASN1_STRING *value;
1132 int index_counter;
1133 int rdn_level = -1;
1134 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001136 dn = PyList_New(0);
1137 if (dn == NULL)
1138 return NULL;
1139 /* now create another tuple to hold the top-level RDN */
1140 rdn = PyList_New(0);
1141 if (rdn == NULL)
1142 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 for (index_counter = 0;
1145 index_counter < entry_count;
1146 index_counter++)
1147 {
1148 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 /* check to see if we've gotten to a new RDN */
1151 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001152 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 /* yes, new RDN */
1154 /* add old RDN to DN */
1155 rdnt = PyList_AsTuple(rdn);
1156 Py_DECREF(rdn);
1157 if (rdnt == NULL)
1158 goto fail0;
1159 retcode = PyList_Append(dn, rdnt);
1160 Py_DECREF(rdnt);
1161 if (retcode < 0)
1162 goto fail0;
1163 /* create new RDN */
1164 rdn = PyList_New(0);
1165 if (rdn == NULL)
1166 goto fail0;
1167 }
1168 }
Christian Heimes598894f2016-09-05 23:19:05 +02001169 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 /* now add this attribute to the current RDN */
1172 name = X509_NAME_ENTRY_get_object(entry);
1173 value = X509_NAME_ENTRY_get_data(entry);
1174 attr = _create_tuple_for_attribute(name, value);
1175 /*
1176 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1177 entry->set,
1178 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1179 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1180 */
1181 if (attr == NULL)
1182 goto fail1;
1183 retcode = PyList_Append(rdn, attr);
1184 Py_DECREF(attr);
1185 if (retcode < 0)
1186 goto fail1;
1187 }
1188 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001189 if (rdn != NULL) {
1190 if (PyList_GET_SIZE(rdn) > 0) {
1191 rdnt = PyList_AsTuple(rdn);
1192 Py_DECREF(rdn);
1193 if (rdnt == NULL)
1194 goto fail0;
1195 retcode = PyList_Append(dn, rdnt);
1196 Py_DECREF(rdnt);
1197 if (retcode < 0)
1198 goto fail0;
1199 }
1200 else {
1201 Py_DECREF(rdn);
1202 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001205 /* convert list to tuple */
1206 rdnt = PyList_AsTuple(dn);
1207 Py_DECREF(dn);
1208 if (rdnt == NULL)
1209 return NULL;
1210 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211
1212 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001214
1215 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001216 Py_XDECREF(dn);
1217 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001218}
1219
1220static PyObject *
1221_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 /* this code follows the procedure outlined in
1224 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1225 function to extract the STACK_OF(GENERAL_NAME),
1226 then iterates through the stack to add the
1227 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001229 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001231 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001232 GENERAL_NAMES *names = NULL;
1233 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 BIO *biobuf = NULL;
1235 char buf[2048];
1236 char *vptr;
1237 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 if (certificate == NULL)
1240 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 /* get a memory buffer */
1243 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001244
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001245 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1246 certificate, NID_subject_alt_name, NULL, NULL);
1247 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 if (peer_alt_names == Py_None) {
1249 peer_alt_names = PyList_New(0);
1250 if (peer_alt_names == NULL)
1251 goto fail;
1252 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001253
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001256 int gntype;
1257 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001258
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001260 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001261 switch (gntype) {
1262 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 /* we special-case DirName as a tuple of
1264 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 t = PyTuple_New(2);
1267 if (t == NULL) {
1268 goto fail;
1269 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 v = PyUnicode_FromString("DirName");
1272 if (v == NULL) {
1273 Py_DECREF(t);
1274 goto fail;
1275 }
1276 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 v = _create_tuple_for_X509_NAME (name->d.dirn);
1279 if (v == NULL) {
1280 Py_DECREF(t);
1281 goto fail;
1282 }
1283 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001284 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001285
Christian Heimes824f7f32013-08-17 00:54:47 +02001286 case GEN_EMAIL:
1287 case GEN_DNS:
1288 case GEN_URI:
1289 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1290 correctly, CVE-2013-4238 */
1291 t = PyTuple_New(2);
1292 if (t == NULL)
1293 goto fail;
1294 switch (gntype) {
1295 case GEN_EMAIL:
1296 v = PyUnicode_FromString("email");
1297 as = name->d.rfc822Name;
1298 break;
1299 case GEN_DNS:
1300 v = PyUnicode_FromString("DNS");
1301 as = name->d.dNSName;
1302 break;
1303 case GEN_URI:
1304 v = PyUnicode_FromString("URI");
1305 as = name->d.uniformResourceIdentifier;
1306 break;
1307 }
1308 if (v == NULL) {
1309 Py_DECREF(t);
1310 goto fail;
1311 }
1312 PyTuple_SET_ITEM(t, 0, v);
1313 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1314 ASN1_STRING_length(as));
1315 if (v == NULL) {
1316 Py_DECREF(t);
1317 goto fail;
1318 }
1319 PyTuple_SET_ITEM(t, 1, v);
1320 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Christian Heimes1c03abd2016-09-06 23:25:35 +02001322 case GEN_RID:
1323 t = PyTuple_New(2);
1324 if (t == NULL)
1325 goto fail;
1326
1327 v = PyUnicode_FromString("Registered ID");
1328 if (v == NULL) {
1329 Py_DECREF(t);
1330 goto fail;
1331 }
1332 PyTuple_SET_ITEM(t, 0, v);
1333
1334 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1335 if (len < 0) {
1336 Py_DECREF(t);
1337 _setSSLError(NULL, 0, __FILE__, __LINE__);
1338 goto fail;
1339 } else if (len >= (int)sizeof(buf)) {
1340 v = PyUnicode_FromString("<INVALID>");
1341 } else {
1342 v = PyUnicode_FromStringAndSize(buf, len);
1343 }
1344 if (v == NULL) {
1345 Py_DECREF(t);
1346 goto fail;
1347 }
1348 PyTuple_SET_ITEM(t, 1, v);
1349 break;
1350
Christian Heimes824f7f32013-08-17 00:54:47 +02001351 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001353 switch (gntype) {
1354 /* check for new general name type */
1355 case GEN_OTHERNAME:
1356 case GEN_X400:
1357 case GEN_EDIPARTY:
1358 case GEN_IPADD:
1359 case GEN_RID:
1360 break;
1361 default:
1362 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1363 "Unknown general name type %d",
1364 gntype) == -1) {
1365 goto fail;
1366 }
1367 break;
1368 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001369 (void) BIO_reset(biobuf);
1370 GENERAL_NAME_print(biobuf, name);
1371 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1372 if (len < 0) {
1373 _setSSLError(NULL, 0, __FILE__, __LINE__);
1374 goto fail;
1375 }
1376 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001377 if (vptr == NULL) {
1378 PyErr_Format(PyExc_ValueError,
1379 "Invalid value %.200s",
1380 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001382 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001383 t = PyTuple_New(2);
1384 if (t == NULL)
1385 goto fail;
1386 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1387 if (v == NULL) {
1388 Py_DECREF(t);
1389 goto fail;
1390 }
1391 PyTuple_SET_ITEM(t, 0, v);
1392 v = PyUnicode_FromStringAndSize((vptr + 1),
1393 (len - (vptr - buf + 1)));
1394 if (v == NULL) {
1395 Py_DECREF(t);
1396 goto fail;
1397 }
1398 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001399 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 if (PyList_Append(peer_alt_names, t) < 0) {
1405 Py_DECREF(t);
1406 goto fail;
1407 }
1408 Py_DECREF(t);
1409 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001410 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 }
1412 BIO_free(biobuf);
1413 if (peer_alt_names != Py_None) {
1414 v = PyList_AsTuple(peer_alt_names);
1415 Py_DECREF(peer_alt_names);
1416 return v;
1417 } else {
1418 return peer_alt_names;
1419 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001420
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421
1422 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 if (biobuf != NULL)
1424 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 if (peer_alt_names != Py_None) {
1427 Py_XDECREF(peer_alt_names);
1428 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001431}
1432
1433static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001434_get_aia_uri(X509 *certificate, int nid) {
1435 PyObject *lst = NULL, *ostr = NULL;
1436 int i, result;
1437 AUTHORITY_INFO_ACCESS *info;
1438
1439 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001440 if (info == NULL)
1441 return Py_None;
1442 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1443 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001444 return Py_None;
1445 }
1446
1447 if ((lst = PyList_New(0)) == NULL) {
1448 goto fail;
1449 }
1450
1451 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1452 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1453 ASN1_IA5STRING *uri;
1454
1455 if ((OBJ_obj2nid(ad->method) != nid) ||
1456 (ad->location->type != GEN_URI)) {
1457 continue;
1458 }
1459 uri = ad->location->d.uniformResourceIdentifier;
1460 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1461 uri->length);
1462 if (ostr == NULL) {
1463 goto fail;
1464 }
1465 result = PyList_Append(lst, ostr);
1466 Py_DECREF(ostr);
1467 if (result < 0) {
1468 goto fail;
1469 }
1470 }
1471 AUTHORITY_INFO_ACCESS_free(info);
1472
1473 /* convert to tuple or None */
1474 if (PyList_Size(lst) == 0) {
1475 Py_DECREF(lst);
1476 return Py_None;
1477 } else {
1478 PyObject *tup;
1479 tup = PyList_AsTuple(lst);
1480 Py_DECREF(lst);
1481 return tup;
1482 }
1483
1484 fail:
1485 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001486 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001487 return NULL;
1488}
1489
1490static PyObject *
1491_get_crl_dp(X509 *certificate) {
1492 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001493 int i, j;
1494 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001495
Christian Heimes598894f2016-09-05 23:19:05 +02001496 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001497
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001498 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001499 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001500
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001501 lst = PyList_New(0);
1502 if (lst == NULL)
1503 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504
1505 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1506 DIST_POINT *dp;
1507 STACK_OF(GENERAL_NAME) *gns;
1508
1509 dp = sk_DIST_POINT_value(dps, i);
1510 gns = dp->distpoint->name.fullname;
1511
1512 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1513 GENERAL_NAME *gn;
1514 ASN1_IA5STRING *uri;
1515 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001516 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001517
1518 gn = sk_GENERAL_NAME_value(gns, j);
1519 if (gn->type != GEN_URI) {
1520 continue;
1521 }
1522 uri = gn->d.uniformResourceIdentifier;
1523 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1524 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001525 if (ouri == NULL)
1526 goto done;
1527
1528 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001530 if (err < 0)
1531 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001532 }
1533 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001534
1535 /* Convert to tuple. */
1536 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1537
1538 done:
1539 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001540 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001541 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001542}
1543
1544static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001545_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001546
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001547 PyObject *retval = NULL;
1548 BIO *biobuf = NULL;
1549 PyObject *peer;
1550 PyObject *peer_alt_names = NULL;
1551 PyObject *issuer;
1552 PyObject *version;
1553 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001554 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 ASN1_INTEGER *serialNumber;
1556 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001557 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 ASN1_TIME *notBefore, *notAfter;
1559 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 retval = PyDict_New();
1562 if (retval == NULL)
1563 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001564
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001565 peer = _create_tuple_for_X509_NAME(
1566 X509_get_subject_name(certificate));
1567 if (peer == NULL)
1568 goto fail0;
1569 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1570 Py_DECREF(peer);
1571 goto fail0;
1572 }
1573 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001574
Antoine Pitroufb046912010-11-09 20:21:19 +00001575 issuer = _create_tuple_for_X509_NAME(
1576 X509_get_issuer_name(certificate));
1577 if (issuer == NULL)
1578 goto fail0;
1579 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001581 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001583 Py_DECREF(issuer);
1584
1585 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001586 if (version == NULL)
1587 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001588 if (PyDict_SetItemString(retval, "version", version) < 0) {
1589 Py_DECREF(version);
1590 goto fail0;
1591 }
1592 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001593
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001594 /* get a memory buffer */
1595 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001596
Antoine Pitroufb046912010-11-09 20:21:19 +00001597 (void) BIO_reset(biobuf);
1598 serialNumber = X509_get_serialNumber(certificate);
1599 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1600 i2a_ASN1_INTEGER(biobuf, serialNumber);
1601 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1602 if (len < 0) {
1603 _setSSLError(NULL, 0, __FILE__, __LINE__);
1604 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001606 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1607 if (sn_obj == NULL)
1608 goto fail1;
1609 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1610 Py_DECREF(sn_obj);
1611 goto fail1;
1612 }
1613 Py_DECREF(sn_obj);
1614
1615 (void) BIO_reset(biobuf);
1616 notBefore = X509_get_notBefore(certificate);
1617 ASN1_TIME_print(biobuf, notBefore);
1618 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1619 if (len < 0) {
1620 _setSSLError(NULL, 0, __FILE__, __LINE__);
1621 goto fail1;
1622 }
1623 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1624 if (pnotBefore == NULL)
1625 goto fail1;
1626 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1627 Py_DECREF(pnotBefore);
1628 goto fail1;
1629 }
1630 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 (void) BIO_reset(biobuf);
1633 notAfter = X509_get_notAfter(certificate);
1634 ASN1_TIME_print(biobuf, notAfter);
1635 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1636 if (len < 0) {
1637 _setSSLError(NULL, 0, __FILE__, __LINE__);
1638 goto fail1;
1639 }
1640 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1641 if (pnotAfter == NULL)
1642 goto fail1;
1643 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1644 Py_DECREF(pnotAfter);
1645 goto fail1;
1646 }
1647 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001649 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001651 peer_alt_names = _get_peer_alt_names(certificate);
1652 if (peer_alt_names == NULL)
1653 goto fail1;
1654 else if (peer_alt_names != Py_None) {
1655 if (PyDict_SetItemString(retval, "subjectAltName",
1656 peer_alt_names) < 0) {
1657 Py_DECREF(peer_alt_names);
1658 goto fail1;
1659 }
1660 Py_DECREF(peer_alt_names);
1661 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001662
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001663 /* Authority Information Access: OCSP URIs */
1664 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1665 if (obj == NULL) {
1666 goto fail1;
1667 } else if (obj != Py_None) {
1668 result = PyDict_SetItemString(retval, "OCSP", obj);
1669 Py_DECREF(obj);
1670 if (result < 0) {
1671 goto fail1;
1672 }
1673 }
1674
1675 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1676 if (obj == NULL) {
1677 goto fail1;
1678 } else if (obj != Py_None) {
1679 result = PyDict_SetItemString(retval, "caIssuers", obj);
1680 Py_DECREF(obj);
1681 if (result < 0) {
1682 goto fail1;
1683 }
1684 }
1685
1686 /* CDP (CRL distribution points) */
1687 obj = _get_crl_dp(certificate);
1688 if (obj == NULL) {
1689 goto fail1;
1690 } else if (obj != Py_None) {
1691 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1692 Py_DECREF(obj);
1693 if (result < 0) {
1694 goto fail1;
1695 }
1696 }
1697
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 BIO_free(biobuf);
1699 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001700
1701 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 if (biobuf != NULL)
1703 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001704 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 Py_XDECREF(retval);
1706 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001707}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001708
Christian Heimes9a5395a2013-06-17 15:44:12 +02001709static PyObject *
1710_certificate_to_der(X509 *certificate)
1711{
1712 unsigned char *bytes_buf = NULL;
1713 int len;
1714 PyObject *retval;
1715
1716 bytes_buf = NULL;
1717 len = i2d_X509(certificate, &bytes_buf);
1718 if (len < 0) {
1719 _setSSLError(NULL, 0, __FILE__, __LINE__);
1720 return NULL;
1721 }
1722 /* this is actually an immutable bytes sequence */
1723 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1724 OPENSSL_free(bytes_buf);
1725 return retval;
1726}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001728/*[clinic input]
1729_ssl._test_decode_cert
1730 path: object(converter="PyUnicode_FSConverter")
1731 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001732
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001733[clinic start generated code]*/
1734
1735static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001736_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1737/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001738{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 X509 *x=NULL;
1741 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1744 PyErr_SetString(PySSLErrorObject,
1745 "Can't malloc memory to read file");
1746 goto fail0;
1747 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001749 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 PyErr_SetString(PySSLErrorObject,
1751 "Can't open file");
1752 goto fail0;
1753 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1756 if (x == NULL) {
1757 PyErr_SetString(PySSLErrorObject,
1758 "Error decoding PEM-encoded file");
1759 goto fail0;
1760 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
Antoine Pitroufb046912010-11-09 20:21:19 +00001762 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001763 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764
1765 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001766 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001767 if (cert != NULL) BIO_free(cert);
1768 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769}
1770
1771
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001772/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001773_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001774 der as binary_mode: bool = False
1775 /
1776
1777Returns the certificate for the peer.
1778
1779If no certificate was provided, returns None. If a certificate was
1780provided, but not validated, returns an empty dictionary. Otherwise
1781returns a dict containing information about the peer certificate.
1782
1783If the optional argument is True, returns a DER-encoded copy of the
1784peer certificate, or None if no certificate was provided. This will
1785return the certificate even if it wasn't validated.
1786[clinic start generated code]*/
1787
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001789_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1790/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001792 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001793 X509 *peer_cert;
1794 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001795
Christian Heimes66dc33b2017-05-23 16:02:02 -07001796 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001797 PyErr_SetString(PyExc_ValueError,
1798 "handshake not done yet");
1799 return NULL;
1800 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001801 peer_cert = SSL_get_peer_certificate(self->ssl);
1802 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804
Antoine Pitrou721738f2012-08-15 23:20:39 +02001805 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001807 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001809 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001811 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001813 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001814 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001815 X509_free(peer_cert);
1816 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001817}
1818
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001819static PyObject *
1820cipher_to_tuple(const SSL_CIPHER *cipher)
1821{
1822 const char *cipher_name, *cipher_protocol;
1823 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 if (retval == NULL)
1825 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001826
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001827 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001829 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 PyTuple_SET_ITEM(retval, 0, Py_None);
1831 } else {
1832 v = PyUnicode_FromString(cipher_name);
1833 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001834 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 PyTuple_SET_ITEM(retval, 0, v);
1836 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001837
1838 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001840 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 PyTuple_SET_ITEM(retval, 1, Py_None);
1842 } else {
1843 v = PyUnicode_FromString(cipher_protocol);
1844 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001845 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001846 PyTuple_SET_ITEM(retval, 1, v);
1847 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001848
1849 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 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, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001855
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001856 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 Py_DECREF(retval);
1858 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001859}
1860
Christian Heimes25bfcd52016-09-06 00:04:45 +02001861#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1862static PyObject *
1863cipher_to_dict(const SSL_CIPHER *cipher)
1864{
1865 const char *cipher_name, *cipher_protocol;
1866
1867 unsigned long cipher_id;
1868 int alg_bits, strength_bits, len;
1869 char buf[512] = {0};
1870#if OPENSSL_VERSION_1_1
1871 int aead, nid;
1872 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1873#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001874
1875 /* can be NULL */
1876 cipher_name = SSL_CIPHER_get_name(cipher);
1877 cipher_protocol = SSL_CIPHER_get_version(cipher);
1878 cipher_id = SSL_CIPHER_get_id(cipher);
1879 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001880 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1881 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001882 if (len > 1 && buf[len-1] == '\n')
1883 buf[len-1] = '\0';
1884 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1885
1886#if OPENSSL_VERSION_1_1
1887 aead = SSL_CIPHER_is_aead(cipher);
1888 nid = SSL_CIPHER_get_cipher_nid(cipher);
1889 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1890 nid = SSL_CIPHER_get_digest_nid(cipher);
1891 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1892 nid = SSL_CIPHER_get_kx_nid(cipher);
1893 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1894 nid = SSL_CIPHER_get_auth_nid(cipher);
1895 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1896#endif
1897
Victor Stinner410b9882016-09-12 12:00:23 +02001898 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001899 "{sksssssssisi"
1900#if OPENSSL_VERSION_1_1
1901 "sOssssssss"
1902#endif
1903 "}",
1904 "id", cipher_id,
1905 "name", cipher_name,
1906 "protocol", cipher_protocol,
1907 "description", buf,
1908 "strength_bits", strength_bits,
1909 "alg_bits", alg_bits
1910#if OPENSSL_VERSION_1_1
1911 ,"aead", aead ? Py_True : Py_False,
1912 "symmetric", skcipher,
1913 "digest", digest,
1914 "kea", kx,
1915 "auth", auth
1916#endif
1917 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001918}
1919#endif
1920
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001921/*[clinic input]
1922_ssl._SSLSocket.shared_ciphers
1923[clinic start generated code]*/
1924
1925static PyObject *
1926_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1927/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001928{
1929 STACK_OF(SSL_CIPHER) *ciphers;
1930 int i;
1931 PyObject *res;
1932
Christian Heimes598894f2016-09-05 23:19:05 +02001933 ciphers = SSL_get_ciphers(self->ssl);
1934 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001935 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001936 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1937 if (!res)
1938 return NULL;
1939 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1940 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1941 if (!tup) {
1942 Py_DECREF(res);
1943 return NULL;
1944 }
1945 PyList_SET_ITEM(res, i, tup);
1946 }
1947 return res;
1948}
1949
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001950/*[clinic input]
1951_ssl._SSLSocket.cipher
1952[clinic start generated code]*/
1953
1954static PyObject *
1955_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1956/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001957{
1958 const SSL_CIPHER *current;
1959
1960 if (self->ssl == NULL)
1961 Py_RETURN_NONE;
1962 current = SSL_get_current_cipher(self->ssl);
1963 if (current == NULL)
1964 Py_RETURN_NONE;
1965 return cipher_to_tuple(current);
1966}
1967
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001968/*[clinic input]
1969_ssl._SSLSocket.version
1970[clinic start generated code]*/
1971
1972static PyObject *
1973_ssl__SSLSocket_version_impl(PySSLSocket *self)
1974/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001975{
1976 const char *version;
1977
1978 if (self->ssl == NULL)
1979 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001980 if (!SSL_is_init_finished(self->ssl)) {
1981 /* handshake not finished */
1982 Py_RETURN_NONE;
1983 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001984 version = SSL_get_version(self->ssl);
1985 if (!strcmp(version, "unknown"))
1986 Py_RETURN_NONE;
1987 return PyUnicode_FromString(version);
1988}
1989
Miss Islington (bot)96177412018-02-25 04:18:43 -08001990#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001991/*[clinic input]
1992_ssl._SSLSocket.selected_npn_protocol
1993[clinic start generated code]*/
1994
1995static PyObject *
1996_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1997/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1998{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001999 const unsigned char *out;
2000 unsigned int outlen;
2001
Victor Stinner4569cd52013-06-23 14:58:43 +02002002 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002003 &out, &outlen);
2004
2005 if (out == NULL)
2006 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002007 return PyUnicode_FromStringAndSize((char *)out, outlen);
2008}
2009#endif
2010
Miss Islington (bot)96177412018-02-25 04:18:43 -08002011#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002012/*[clinic input]
2013_ssl._SSLSocket.selected_alpn_protocol
2014[clinic start generated code]*/
2015
2016static PyObject *
2017_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2018/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2019{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002020 const unsigned char *out;
2021 unsigned int outlen;
2022
2023 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2024
2025 if (out == NULL)
2026 Py_RETURN_NONE;
2027 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002028}
2029#endif
2030
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002031/*[clinic input]
2032_ssl._SSLSocket.compression
2033[clinic start generated code]*/
2034
2035static PyObject *
2036_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2037/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2038{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002039#ifdef OPENSSL_NO_COMP
2040 Py_RETURN_NONE;
2041#else
2042 const COMP_METHOD *comp_method;
2043 const char *short_name;
2044
2045 if (self->ssl == NULL)
2046 Py_RETURN_NONE;
2047 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002048 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002049 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002050 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002051 if (short_name == NULL)
2052 Py_RETURN_NONE;
2053 return PyUnicode_DecodeFSDefault(short_name);
2054#endif
2055}
2056
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002057static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2058 Py_INCREF(self->ctx);
2059 return self->ctx;
2060}
2061
2062static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2063 void *closure) {
2064
2065 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002066#if !HAVE_SNI
2067 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2068 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002069 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002070#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002071 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002072 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002073 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002074#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002075 } else {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002076 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002077 return -1;
2078 }
2079
2080 return 0;
2081}
2082
2083PyDoc_STRVAR(PySSL_set_context_doc,
2084"_setter_context(ctx)\n\
2085\
2086This changes the context associated with the SSLSocket. This is typically\n\
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002087used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002088on the SSLContext to change the certificate information associated with the\n\
2089SSLSocket before the cryptographic exchange handshake messages\n");
2090
2091
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002092static PyObject *
2093PySSL_get_server_side(PySSLSocket *self, void *c)
2094{
2095 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2096}
2097
2098PyDoc_STRVAR(PySSL_get_server_side_doc,
2099"Whether this is a server-side socket.");
2100
2101static PyObject *
2102PySSL_get_server_hostname(PySSLSocket *self, void *c)
2103{
2104 if (self->server_hostname == NULL)
2105 Py_RETURN_NONE;
2106 Py_INCREF(self->server_hostname);
2107 return self->server_hostname;
2108}
2109
2110PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2111"The currently set server hostname (for SNI).");
2112
2113static PyObject *
2114PySSL_get_owner(PySSLSocket *self, void *c)
2115{
2116 PyObject *owner;
2117
2118 if (self->owner == NULL)
2119 Py_RETURN_NONE;
2120
2121 owner = PyWeakref_GetObject(self->owner);
2122 Py_INCREF(owner);
2123 return owner;
2124}
2125
2126static int
2127PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2128{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002129 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002130 if (self->owner == NULL)
2131 return -1;
2132 return 0;
2133}
2134
2135PyDoc_STRVAR(PySSL_get_owner_doc,
2136"The Python-level owner of this object.\
2137Passed as \"self\" in servername callback.");
2138
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002139
Antoine Pitrou152efa22010-05-16 18:19:27 +00002140static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002141{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 if (self->ssl)
2143 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002145 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002146 Py_XDECREF(self->server_hostname);
2147 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002149}
2150
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002151/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002152 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002153 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002154 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002155
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002156static int
Victor Stinner14690702015-04-06 22:46:13 +02002157PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002158{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002159 int rc;
2160#ifdef HAVE_POLL
2161 struct pollfd pollfd;
2162 _PyTime_t ms;
2163#else
2164 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 fd_set fds;
2166 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002167#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002169 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002170 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002172 else if (timeout < 0) {
2173 if (s->sock_timeout > 0)
2174 return SOCKET_HAS_TIMED_OUT;
2175 else
2176 return SOCKET_IS_BLOCKING;
2177 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002180 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 /* Prefer poll, if available, since you can poll() any fd
2184 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002185#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002186 pollfd.fd = s->sock_fd;
2187 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002188
Victor Stinner14690702015-04-06 22:46:13 +02002189 /* timeout is in seconds, poll() uses milliseconds */
2190 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002191 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002192
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002193 PySSL_BEGIN_ALLOW_THREADS
2194 rc = poll(&pollfd, 1, (int)ms);
2195 PySSL_END_ALLOW_THREADS
2196#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002197 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002198 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002199 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002200
Victor Stinner14690702015-04-06 22:46:13 +02002201 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002202
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 FD_ZERO(&fds);
2204 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002205
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002208 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002210 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002212 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002214#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2217 (when we are able to write or when there's something to read) */
2218 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002219}
2220
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002221/*[clinic input]
2222_ssl._SSLSocket.write
2223 b: Py_buffer
2224 /
2225
2226Writes the bytes-like object b into the SSL object.
2227
2228Returns the number of bytes written.
2229[clinic start generated code]*/
2230
2231static PyObject *
2232_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2233/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002234{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 int len;
2236 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002237 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002238 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002239 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002240 _PyTime_t timeout, deadline = 0;
2241 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002242
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002243 if (sock != NULL) {
2244 if (((PyObject*)sock) == Py_None) {
2245 _setSSLError("Underlying socket connection gone",
2246 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2247 return NULL;
2248 }
2249 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 }
2251
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002252 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002253 PyErr_Format(PyExc_OverflowError,
2254 "string longer than %d bytes", INT_MAX);
2255 goto error;
2256 }
2257
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002258 if (sock != NULL) {
2259 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002260 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002261 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2262 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2263 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002264
Victor Stinner14690702015-04-06 22:46:13 +02002265 timeout = GET_SOCKET_TIMEOUT(sock);
2266 has_timeout = (timeout > 0);
2267 if (has_timeout)
2268 deadline = _PyTime_GetMonotonicClock() + timeout;
2269
2270 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002272 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 "The write operation timed out");
2274 goto error;
2275 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2276 PyErr_SetString(PySSLErrorObject,
2277 "Underlying socket has been closed.");
2278 goto error;
2279 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2280 PyErr_SetString(PySSLErrorObject,
2281 "Underlying socket too large for select().");
2282 goto error;
2283 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002287 len = SSL_write(self->ssl, b->buf, (int)b->len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002288 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002290 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002291
2292 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002294
Victor Stinner14690702015-04-06 22:46:13 +02002295 if (has_timeout)
2296 timeout = deadline - _PyTime_GetMonotonicClock();
2297
Miss Islington (bot)12296642018-09-17 12:12:13 -07002298 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002299 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002300 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002301 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 } else {
2303 sockstate = SOCKET_OPERATION_OK;
2304 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002307 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 "The write operation timed out");
2309 goto error;
2310 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2311 PyErr_SetString(PySSLErrorObject,
2312 "Underlying socket has been closed.");
2313 goto error;
2314 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2315 break;
2316 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002317 } while (err.ssl == SSL_ERROR_WANT_READ ||
2318 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002319
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002320 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 if (len > 0)
2322 return PyLong_FromLong(len);
2323 else
2324 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002325
2326error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002327 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002329}
2330
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002331/*[clinic input]
2332_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002333
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002334Returns the number of already decrypted bytes available for read, pending on the connection.
2335[clinic start generated code]*/
2336
2337static PyObject *
2338_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2339/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002340{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 int count = 0;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002342 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002344 PySSL_BEGIN_ALLOW_THREADS
2345 count = SSL_pending(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002346 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002348 self->err = err;
2349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 if (count < 0)
2351 return PySSL_SetError(self, count, __FILE__, __LINE__);
2352 else
2353 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002354}
2355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002356/*[clinic input]
2357_ssl._SSLSocket.read
2358 size as len: int
2359 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002360 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002361 ]
2362 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002363
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002364Read up to size bytes from the SSL socket.
2365[clinic start generated code]*/
2366
2367static PyObject *
2368_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2369 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002370/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002371{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002372 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002374 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002375 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002376 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002378 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002379 _PyTime_t timeout, deadline = 0;
2380 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002381
Martin Panter5503d472016-03-27 05:35:19 +00002382 if (!group_right_1 && len < 0) {
2383 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2384 return NULL;
2385 }
2386
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002387 if (sock != NULL) {
2388 if (((PyObject*)sock) == Py_None) {
2389 _setSSLError("Underlying socket connection gone",
2390 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2391 return NULL;
2392 }
2393 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 }
2395
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002396 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002397 dest = PyBytes_FromStringAndSize(NULL, len);
2398 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002399 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002400 if (len == 0) {
2401 Py_XDECREF(sock);
2402 return dest;
2403 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002404 mem = PyBytes_AS_STRING(dest);
2405 }
2406 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002407 mem = buffer->buf;
2408 if (len <= 0 || len > buffer->len) {
2409 len = (int) buffer->len;
2410 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002411 PyErr_SetString(PyExc_OverflowError,
2412 "maximum length can't fit in a C 'int'");
2413 goto error;
2414 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002415 if (len == 0) {
2416 count = 0;
2417 goto done;
2418 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002419 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 }
2421
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002422 if (sock != NULL) {
2423 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002424 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002425 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2426 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2427 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428
Victor Stinner14690702015-04-06 22:46:13 +02002429 timeout = GET_SOCKET_TIMEOUT(sock);
2430 has_timeout = (timeout > 0);
2431 if (has_timeout)
2432 deadline = _PyTime_GetMonotonicClock() + timeout;
2433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 PySSL_BEGIN_ALLOW_THREADS
2436 count = SSL_read(self->ssl, mem, len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002437 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002439 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002440
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 if (PyErr_CheckSignals())
2442 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002443
Victor Stinner14690702015-04-06 22:46:13 +02002444 if (has_timeout)
2445 timeout = deadline - _PyTime_GetMonotonicClock();
2446
Miss Islington (bot)12296642018-09-17 12:12:13 -07002447 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002448 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002449 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002450 sockstate = PySSL_select(sock, 1, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002451 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002452 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 {
2454 count = 0;
2455 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002457 else
2458 sockstate = SOCKET_OPERATION_OK;
2459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002460 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002461 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002462 "The read operation timed out");
2463 goto error;
2464 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2465 break;
2466 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002467 } while (err.ssl == SSL_ERROR_WANT_READ ||
2468 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002469
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 if (count <= 0) {
2471 PySSL_SetError(self, count, __FILE__, __LINE__);
2472 goto error;
2473 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002474
2475done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002476 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002477 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002478 _PyBytes_Resize(&dest, count);
2479 return dest;
2480 }
2481 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002482 return PyLong_FromLong(count);
2483 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002484
2485error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002486 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002487 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002488 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002489 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002490}
2491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492/*[clinic input]
2493_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002494
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002495Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002496[clinic start generated code]*/
2497
2498static PyObject *
2499_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002500/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002501{
Miss Islington (bot)12296642018-09-17 12:12:13 -07002502 _PySSLError err;
2503 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002505 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002506 _PyTime_t timeout, deadline = 0;
2507 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002508
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002509 if (sock != NULL) {
2510 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002511 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002512 _setSSLError("Underlying socket connection gone",
2513 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2514 return NULL;
2515 }
2516 Py_INCREF(sock);
2517
2518 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002519 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002520 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2521 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523
Victor Stinner14690702015-04-06 22:46:13 +02002524 timeout = GET_SOCKET_TIMEOUT(sock);
2525 has_timeout = (timeout > 0);
2526 if (has_timeout)
2527 deadline = _PyTime_GetMonotonicClock() + timeout;
2528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 while (1) {
2530 PySSL_BEGIN_ALLOW_THREADS
2531 /* Disable read-ahead so that unwrap can work correctly.
2532 * Otherwise OpenSSL might read in too much data,
2533 * eating clear text data that happens to be
2534 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002535 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 * function is used and the shutdown_seen_zero != 0
2537 * condition is met.
2538 */
2539 if (self->shutdown_seen_zero)
2540 SSL_set_read_ahead(self->ssl, 0);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002541 ret = SSL_shutdown(self->ssl);
2542 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002544 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002545
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002546 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002547 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002548 break;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002549 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 /* Don't loop endlessly; instead preserve legacy
2551 behaviour of trying SSL_shutdown() only twice.
2552 This looks necessary for OpenSSL < 0.9.8m */
2553 if (++zeros > 1)
2554 break;
2555 /* Shutdown was sent, now try receiving */
2556 self->shutdown_seen_zero = 1;
2557 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002558 }
2559
Victor Stinner14690702015-04-06 22:46:13 +02002560 if (has_timeout)
2561 timeout = deadline - _PyTime_GetMonotonicClock();
2562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 /* Possibly retry shutdown until timeout or failure */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002564 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002565 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002566 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002567 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 else
2569 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Miss Islington (bot)12296642018-09-17 12:12:13 -07002572 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002573 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002574 "The read operation timed out");
2575 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002576 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002577 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002578 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579 }
2580 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2581 PyErr_SetString(PySSLErrorObject,
2582 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002583 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 }
2585 else if (sockstate != SOCKET_OPERATION_OK)
2586 /* Retain the SSL error code */
2587 break;
2588 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002589
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002590 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002591 Py_XDECREF(sock);
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002592 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002593 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002594 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002595 /* It's already INCREF'ed */
2596 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002597 else
2598 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002599
2600error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002601 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002602 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002603}
2604
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002605/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002606_ssl._SSLSocket.get_channel_binding
2607 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002608
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002609Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002610
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002611Raise ValueError if the requested `cb_type` is not supported. Return bytes
2612of the data or None if the data is not available (e.g. before the handshake).
2613Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002614[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002615
Antoine Pitroud6494802011-07-21 01:11:30 +02002616static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002617_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2618 const char *cb_type)
2619/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002620{
Antoine Pitroud6494802011-07-21 01:11:30 +02002621 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002622 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002623
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002624 if (strcmp(cb_type, "tls-unique") == 0) {
2625 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2626 /* if session is resumed XOR we are the client */
2627 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2628 }
2629 else {
2630 /* if a new session XOR we are the server */
2631 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2632 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002633 }
2634 else {
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002635 PyErr_Format(
2636 PyExc_ValueError,
2637 "'%s' channel binding type not implemented",
2638 cb_type
2639 );
2640 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002641 }
2642
2643 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002644 if (len == 0)
2645 Py_RETURN_NONE;
2646
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002647 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002648}
2649
Christian Heimes2756ef32018-09-23 09:22:52 +02002650/*[clinic input]
2651_ssl._SSLSocket.verify_client_post_handshake
2652
2653Initiate TLS 1.3 post-handshake authentication
2654[clinic start generated code]*/
2655
2656static PyObject *
2657_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2658/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2659{
2660#ifdef TLS1_3_VERSION
2661 int err = SSL_verify_client_post_handshake(self->ssl);
2662 if (err == 0)
2663 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2664 else
2665 Py_RETURN_NONE;
2666#else
2667 PyErr_SetString(PyExc_NotImplementedError,
2668 "Post-handshake auth is not supported by your "
2669 "OpenSSL version.");
2670 return NULL;
2671#endif
2672}
2673
Christian Heimes99a65702016-09-10 23:44:53 +02002674#ifdef OPENSSL_VERSION_1_1
2675
2676static SSL_SESSION*
2677_ssl_session_dup(SSL_SESSION *session) {
2678 SSL_SESSION *newsession = NULL;
2679 int slen;
2680 unsigned char *senc = NULL, *p;
2681 const unsigned char *const_p;
2682
2683 if (session == NULL) {
2684 PyErr_SetString(PyExc_ValueError, "Invalid session");
2685 goto error;
2686 }
2687
2688 /* get length */
2689 slen = i2d_SSL_SESSION(session, NULL);
2690 if (slen == 0 || slen > 0xFF00) {
2691 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2692 goto error;
2693 }
2694 if ((senc = PyMem_Malloc(slen)) == NULL) {
2695 PyErr_NoMemory();
2696 goto error;
2697 }
2698 p = senc;
2699 if (!i2d_SSL_SESSION(session, &p)) {
2700 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2701 goto error;
2702 }
2703 const_p = senc;
2704 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2705 if (session == NULL) {
2706 goto error;
2707 }
2708 PyMem_Free(senc);
2709 return newsession;
2710 error:
2711 if (senc != NULL) {
2712 PyMem_Free(senc);
2713 }
2714 return NULL;
2715}
2716#endif
2717
2718static PyObject *
2719PySSL_get_session(PySSLSocket *self, void *closure) {
2720 /* get_session can return sessions from a server-side connection,
2721 * it does not check for handshake done or client socket. */
2722 PySSLSession *pysess;
2723 SSL_SESSION *session;
2724
2725#ifdef OPENSSL_VERSION_1_1
2726 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2727 * https://github.com/openssl/openssl/issues/1550 */
2728 session = SSL_get0_session(self->ssl); /* borrowed reference */
2729 if (session == NULL) {
2730 Py_RETURN_NONE;
2731 }
2732 if ((session = _ssl_session_dup(session)) == NULL) {
2733 return NULL;
2734 }
2735#else
2736 session = SSL_get1_session(self->ssl);
2737 if (session == NULL) {
2738 Py_RETURN_NONE;
2739 }
2740#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002741 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002742 if (pysess == NULL) {
2743 SSL_SESSION_free(session);
2744 return NULL;
2745 }
2746
2747 assert(self->ctx);
2748 pysess->ctx = self->ctx;
2749 Py_INCREF(pysess->ctx);
2750 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002751 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002752 return (PyObject *)pysess;
2753}
2754
2755static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2756 void *closure)
2757 {
2758 PySSLSession *pysess;
2759#ifdef OPENSSL_VERSION_1_1
2760 SSL_SESSION *session;
2761#endif
2762 int result;
2763
2764 if (!PySSLSession_Check(value)) {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002765 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002766 return -1;
2767 }
2768 pysess = (PySSLSession *)value;
2769
2770 if (self->ctx->ctx != pysess->ctx->ctx) {
2771 PyErr_SetString(PyExc_ValueError,
2772 "Session refers to a different SSLContext.");
2773 return -1;
2774 }
2775 if (self->socket_type != PY_SSL_CLIENT) {
2776 PyErr_SetString(PyExc_ValueError,
2777 "Cannot set session for server-side SSLSocket.");
2778 return -1;
2779 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002780 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002781 PyErr_SetString(PyExc_ValueError,
2782 "Cannot set session after handshake.");
2783 return -1;
2784 }
2785#ifdef OPENSSL_VERSION_1_1
2786 /* duplicate session */
2787 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2788 return -1;
2789 }
2790 result = SSL_set_session(self->ssl, session);
2791 /* free duplicate, SSL_set_session() bumps ref count */
2792 SSL_SESSION_free(session);
2793#else
2794 result = SSL_set_session(self->ssl, pysess->session);
2795#endif
2796 if (result == 0) {
2797 _setSSLError(NULL, 0, __FILE__, __LINE__);
2798 return -1;
2799 }
2800 return 0;
2801}
2802
2803PyDoc_STRVAR(PySSL_set_session_doc,
2804"_setter_session(session)\n\
2805\
2806Get / set SSLSession.");
2807
2808static PyObject *
2809PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2810 if (SSL_session_reused(self->ssl)) {
2811 Py_RETURN_TRUE;
2812 } else {
2813 Py_RETURN_FALSE;
2814 }
2815}
2816
2817PyDoc_STRVAR(PySSL_get_session_reused_doc,
2818"Was the client session reused during handshake?");
2819
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002820static PyGetSetDef ssl_getsetlist[] = {
2821 {"context", (getter) PySSL_get_context,
2822 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002823 {"server_side", (getter) PySSL_get_server_side, NULL,
2824 PySSL_get_server_side_doc},
2825 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2826 PySSL_get_server_hostname_doc},
2827 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2828 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002829 {"session", (getter) PySSL_get_session,
2830 (setter) PySSL_set_session, PySSL_set_session_doc},
2831 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2832 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002833 {NULL}, /* sentinel */
2834};
2835
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002836static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002837 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2838 _SSL__SSLSOCKET_WRITE_METHODDEF
2839 _SSL__SSLSOCKET_READ_METHODDEF
2840 _SSL__SSLSOCKET_PENDING_METHODDEF
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002841 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2842 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002843 _SSL__SSLSOCKET_CIPHER_METHODDEF
2844 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2845 _SSL__SSLSOCKET_VERSION_METHODDEF
2846 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2847 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2848 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2849 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes2756ef32018-09-23 09:22:52 +02002850 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002851 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002852};
2853
Antoine Pitrou152efa22010-05-16 18:19:27 +00002854static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002855 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002856 "_ssl._SSLSocket", /*tp_name*/
2857 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002858 0, /*tp_itemsize*/
2859 /* methods */
2860 (destructor)PySSL_dealloc, /*tp_dealloc*/
2861 0, /*tp_print*/
2862 0, /*tp_getattr*/
2863 0, /*tp_setattr*/
2864 0, /*tp_reserved*/
2865 0, /*tp_repr*/
2866 0, /*tp_as_number*/
2867 0, /*tp_as_sequence*/
2868 0, /*tp_as_mapping*/
2869 0, /*tp_hash*/
2870 0, /*tp_call*/
2871 0, /*tp_str*/
2872 0, /*tp_getattro*/
2873 0, /*tp_setattro*/
2874 0, /*tp_as_buffer*/
2875 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2876 0, /*tp_doc*/
2877 0, /*tp_traverse*/
2878 0, /*tp_clear*/
2879 0, /*tp_richcompare*/
2880 0, /*tp_weaklistoffset*/
2881 0, /*tp_iter*/
2882 0, /*tp_iternext*/
2883 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002884 0, /*tp_members*/
2885 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002886};
2887
Antoine Pitrou152efa22010-05-16 18:19:27 +00002888
2889/*
2890 * _SSLContext objects
2891 */
2892
Christian Heimes5fe668c2016-09-12 00:01:11 +02002893static int
Christian Heimes2756ef32018-09-23 09:22:52 +02002894_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002895{
2896 int mode;
2897 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2898
2899 switch(n) {
2900 case PY_SSL_CERT_NONE:
2901 mode = SSL_VERIFY_NONE;
2902 break;
2903 case PY_SSL_CERT_OPTIONAL:
2904 mode = SSL_VERIFY_PEER;
2905 break;
2906 case PY_SSL_CERT_REQUIRED:
2907 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2908 break;
2909 default:
2910 PyErr_SetString(PyExc_ValueError,
2911 "invalid value for verify_mode");
2912 return -1;
2913 }
Christian Heimes2756ef32018-09-23 09:22:52 +02002914#ifdef TLS1_3_VERSION
2915 if (self->post_handshake_auth)
2916 mode |= SSL_VERIFY_POST_HANDSHAKE;
2917#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002918 /* keep current verify cb */
Christian Heimes2756ef32018-09-23 09:22:52 +02002919 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2920 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002921 return 0;
2922}
2923
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002924/*[clinic input]
2925@classmethod
2926_ssl._SSLContext.__new__
2927 protocol as proto_version: int
2928 /
2929[clinic start generated code]*/
2930
Antoine Pitrou152efa22010-05-16 18:19:27 +00002931static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002932_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2933/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002934{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002935 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002936 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002937 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002938 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002939 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002940#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002941 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002942#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002943
Antoine Pitrou152efa22010-05-16 18:19:27 +00002944 PySSL_BEGIN_ALLOW_THREADS
2945 if (proto_version == PY_SSL_VERSION_TLS1)
2946 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002947#if HAVE_TLSv1_2
2948 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2949 ctx = SSL_CTX_new(TLSv1_1_method());
2950 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2951 ctx = SSL_CTX_new(TLSv1_2_method());
2952#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002953#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002954 else if (proto_version == PY_SSL_VERSION_SSL3)
2955 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002956#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002957#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002958 else if (proto_version == PY_SSL_VERSION_SSL2)
2959 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002960#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002961 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002962 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002963 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2964 ctx = SSL_CTX_new(TLS_client_method());
2965 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2966 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002967 else
2968 proto_version = -1;
2969 PySSL_END_ALLOW_THREADS
2970
2971 if (proto_version == -1) {
2972 PyErr_SetString(PyExc_ValueError,
2973 "invalid protocol version");
2974 return NULL;
2975 }
2976 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002977 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002978 return NULL;
2979 }
2980
2981 assert(type != NULL && type->tp_alloc != NULL);
2982 self = (PySSLContext *) type->tp_alloc(type, 0);
2983 if (self == NULL) {
2984 SSL_CTX_free(ctx);
2985 return NULL;
2986 }
2987 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002988 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002989 self->protocol = proto_version;
Miss Islington (bot)96177412018-02-25 04:18:43 -08002990#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002991 self->npn_protocols = NULL;
2992#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08002993#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002994 self->alpn_protocols = NULL;
2995#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002996#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002997 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002998#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002999 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003000 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3001 self->check_hostname = 1;
Christian Heimes2756ef32018-09-23 09:22:52 +02003002 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003003 Py_DECREF(self);
3004 return NULL;
3005 }
3006 } else {
3007 self->check_hostname = 0;
Christian Heimes2756ef32018-09-23 09:22:52 +02003008 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003009 Py_DECREF(self);
3010 return NULL;
3011 }
3012 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003013 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003014 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3015 if (proto_version != PY_SSL_VERSION_SSL2)
3016 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003017 if (proto_version != PY_SSL_VERSION_SSL3)
3018 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003019 /* Minimal security flags for server and client side context.
3020 * Client sockets ignore server-side parameters. */
3021#ifdef SSL_OP_NO_COMPRESSION
3022 options |= SSL_OP_NO_COMPRESSION;
3023#endif
3024#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3025 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3026#endif
3027#ifdef SSL_OP_SINGLE_DH_USE
3028 options |= SSL_OP_SINGLE_DH_USE;
3029#endif
3030#ifdef SSL_OP_SINGLE_ECDH_USE
3031 options |= SSL_OP_SINGLE_ECDH_USE;
3032#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003033 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003034
Semen Zhydenko1295e112017-10-15 21:28:31 +02003035 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003036 * It's far from perfect but gives users a better head start. */
3037 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003038#if PY_SSL_DEFAULT_CIPHERS == 2
3039 /* stick to OpenSSL's default settings */
3040 result = 1;
3041#else
3042 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3043#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003044 } else {
3045 /* SSLv2 needs MD5 */
3046 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3047 }
3048 if (result == 0) {
3049 Py_DECREF(self);
3050 ERR_clear_error();
3051 PyErr_SetString(PySSLErrorObject,
3052 "No cipher can be selected.");
3053 return NULL;
3054 }
3055
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003056#if defined(SSL_MODE_RELEASE_BUFFERS)
3057 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3058 usage for no cost at all. However, don't do this for OpenSSL versions
3059 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3060 2014-0198. I can't find exactly which beta fixed this CVE, so be
3061 conservative and assume it wasn't fixed until release. We do this check
3062 at runtime to avoid problems from the dynamic linker.
3063 See #25672 for more on this. */
3064 libver = SSLeay();
3065 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3066 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3067 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3068 }
3069#endif
3070
3071
Donald Stufft8ae264c2017-03-02 11:45:29 -05003072#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003073 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3074 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003075 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3076 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003077#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003078 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3079#else
3080 {
3081 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3082 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3083 EC_KEY_free(key);
3084 }
3085#endif
3086#endif
3087
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003088#define SID_CTX "Python"
3089 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3090 sizeof(SID_CTX));
3091#undef SID_CTX
3092
Christian Heimes61d478c2018-01-27 15:51:38 +01003093 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003094#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003095 /* Improve trust chain building when cross-signed intermediate
3096 certificates are present. See https://bugs.python.org/issue23476. */
3097 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003098#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003099 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003100
Christian Heimes2756ef32018-09-23 09:22:52 +02003101#ifdef TLS1_3_VERSION
3102 self->post_handshake_auth = 0;
3103 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3104#endif
3105
Antoine Pitrou152efa22010-05-16 18:19:27 +00003106 return (PyObject *)self;
3107}
3108
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003109static int
3110context_traverse(PySSLContext *self, visitproc visit, void *arg)
3111{
3112#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003113 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003114#endif
3115 return 0;
3116}
3117
3118static int
3119context_clear(PySSLContext *self)
3120{
3121#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003122 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003123#endif
3124 return 0;
3125}
3126
Antoine Pitrou152efa22010-05-16 18:19:27 +00003127static void
3128context_dealloc(PySSLContext *self)
3129{
INADA Naokia6296d32017-08-24 14:55:17 +09003130 /* bpo-31095: UnTrack is needed before calling any callbacks */
3131 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003132 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003133 SSL_CTX_free(self->ctx);
Miss Islington (bot)96177412018-02-25 04:18:43 -08003134#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003135 PyMem_FREE(self->npn_protocols);
3136#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08003137#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003138 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003139#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003140 Py_TYPE(self)->tp_free(self);
3141}
3142
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003143/*[clinic input]
3144_ssl._SSLContext.set_ciphers
3145 cipherlist: str
3146 /
3147[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003148
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003149static PyObject *
3150_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3151/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3152{
3153 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003154 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003155 /* Clearing the error queue is necessary on some OpenSSL versions,
3156 otherwise the error will be reported again when another SSL call
3157 is done. */
3158 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003159 PyErr_SetString(PySSLErrorObject,
3160 "No cipher can be selected.");
3161 return NULL;
3162 }
3163 Py_RETURN_NONE;
3164}
3165
Christian Heimes25bfcd52016-09-06 00:04:45 +02003166#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3167/*[clinic input]
3168_ssl._SSLContext.get_ciphers
3169[clinic start generated code]*/
3170
3171static PyObject *
3172_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3173/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3174{
3175 SSL *ssl = NULL;
3176 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003177 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003178 int i=0;
3179 PyObject *result = NULL, *dct;
3180
3181 ssl = SSL_new(self->ctx);
3182 if (ssl == NULL) {
3183 _setSSLError(NULL, 0, __FILE__, __LINE__);
3184 goto exit;
3185 }
3186 sk = SSL_get_ciphers(ssl);
3187
3188 result = PyList_New(sk_SSL_CIPHER_num(sk));
3189 if (result == NULL) {
3190 goto exit;
3191 }
3192
3193 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3194 cipher = sk_SSL_CIPHER_value(sk, i);
3195 dct = cipher_to_dict(cipher);
3196 if (dct == NULL) {
3197 Py_CLEAR(result);
3198 goto exit;
3199 }
3200 PyList_SET_ITEM(result, i, dct);
3201 }
3202
3203 exit:
3204 if (ssl != NULL)
3205 SSL_free(ssl);
3206 return result;
3207
3208}
3209#endif
3210
3211
Miss Islington (bot)96177412018-02-25 04:18:43 -08003212#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003213static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003214do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3215 const unsigned char *server_protocols, unsigned int server_protocols_len,
3216 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003217{
Benjamin Peterson88615022015-01-23 17:30:26 -05003218 int ret;
3219 if (client_protocols == NULL) {
3220 client_protocols = (unsigned char *)"";
3221 client_protocols_len = 0;
3222 }
3223 if (server_protocols == NULL) {
3224 server_protocols = (unsigned char *)"";
3225 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226 }
3227
Benjamin Peterson88615022015-01-23 17:30:26 -05003228 ret = SSL_select_next_proto(out, outlen,
3229 server_protocols, server_protocols_len,
3230 client_protocols, client_protocols_len);
3231 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3232 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003233
3234 return SSL_TLSEXT_ERR_OK;
3235}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003236#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003237
Miss Islington (bot)96177412018-02-25 04:18:43 -08003238#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003239/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3240static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003241_advertiseNPN_cb(SSL *s,
3242 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003243 void *args)
3244{
3245 PySSLContext *ssl_ctx = (PySSLContext *) args;
3246
3247 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003248 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003249 *len = 0;
3250 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003251 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003252 *len = ssl_ctx->npn_protocols_len;
3253 }
3254
3255 return SSL_TLSEXT_ERR_OK;
3256}
3257/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3258static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003259_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003260 unsigned char **out, unsigned char *outlen,
3261 const unsigned char *server, unsigned int server_len,
3262 void *args)
3263{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003264 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003265 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003266 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003267}
3268#endif
3269
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003270/*[clinic input]
3271_ssl._SSLContext._set_npn_protocols
3272 protos: Py_buffer
3273 /
3274[clinic start generated code]*/
3275
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003276static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003277_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3278 Py_buffer *protos)
3279/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003280{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003281#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003282 PyMem_Free(self->npn_protocols);
3283 self->npn_protocols = PyMem_Malloc(protos->len);
3284 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003285 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003286 memcpy(self->npn_protocols, protos->buf, protos->len);
3287 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003288
3289 /* set both server and client callbacks, because the context can
3290 * be used to create both types of sockets */
3291 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3292 _advertiseNPN_cb,
3293 self);
3294 SSL_CTX_set_next_proto_select_cb(self->ctx,
3295 _selectNPN_cb,
3296 self);
3297
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003298 Py_RETURN_NONE;
3299#else
3300 PyErr_SetString(PyExc_NotImplementedError,
3301 "The NPN extension requires OpenSSL 1.0.1 or later.");
3302 return NULL;
3303#endif
3304}
3305
Miss Islington (bot)96177412018-02-25 04:18:43 -08003306#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003307static int
3308_selectALPN_cb(SSL *s,
3309 const unsigned char **out, unsigned char *outlen,
3310 const unsigned char *client_protocols, unsigned int client_protocols_len,
3311 void *args)
3312{
3313 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003314 return do_protocol_selection(1, (unsigned char **)out, outlen,
3315 ctx->alpn_protocols, ctx->alpn_protocols_len,
3316 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003317}
3318#endif
3319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003320/*[clinic input]
3321_ssl._SSLContext._set_alpn_protocols
3322 protos: Py_buffer
3323 /
3324[clinic start generated code]*/
3325
Benjamin Petersoncca27322015-01-23 16:35:37 -05003326static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003327_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3328 Py_buffer *protos)
3329/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003330{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003331#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003332 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003333 PyErr_Format(PyExc_OverflowError,
3334 "protocols longer than %d bytes", UINT_MAX);
3335 return NULL;
3336 }
3337
Benjamin Petersoncca27322015-01-23 16:35:37 -05003338 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003339 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003340 if (!self->alpn_protocols)
3341 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003342 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003343 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003344
3345 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3346 return PyErr_NoMemory();
3347 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3348
Benjamin Petersoncca27322015-01-23 16:35:37 -05003349 Py_RETURN_NONE;
3350#else
3351 PyErr_SetString(PyExc_NotImplementedError,
3352 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3353 return NULL;
3354#endif
3355}
3356
Antoine Pitrou152efa22010-05-16 18:19:27 +00003357static PyObject *
3358get_verify_mode(PySSLContext *self, void *c)
3359{
Christian Heimes2756ef32018-09-23 09:22:52 +02003360 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3361 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3362 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3363 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003364 case SSL_VERIFY_NONE:
3365 return PyLong_FromLong(PY_SSL_CERT_NONE);
3366 case SSL_VERIFY_PEER:
3367 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3368 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3369 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3370 }
3371 PyErr_SetString(PySSLErrorObject,
3372 "invalid return value from SSL_CTX_get_verify_mode");
3373 return NULL;
3374}
3375
3376static int
3377set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3378{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003379 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003380 if (!PyArg_Parse(arg, "i", &n))
3381 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003382 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003383 PyErr_SetString(PyExc_ValueError,
3384 "Cannot set verify_mode to CERT_NONE when "
3385 "check_hostname is enabled.");
3386 return -1;
3387 }
Christian Heimes2756ef32018-09-23 09:22:52 +02003388 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003389}
3390
3391static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003392get_verify_flags(PySSLContext *self, void *c)
3393{
Christian Heimes598894f2016-09-05 23:19:05 +02003394 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003395 unsigned long flags;
3396
Christian Heimes61d478c2018-01-27 15:51:38 +01003397 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003398 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003399 return PyLong_FromUnsignedLong(flags);
3400}
3401
3402static int
3403set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3404{
Christian Heimes598894f2016-09-05 23:19:05 +02003405 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003406 unsigned long new_flags, flags, set, clear;
3407
3408 if (!PyArg_Parse(arg, "k", &new_flags))
3409 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003410 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003411 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003412 clear = flags & ~new_flags;
3413 set = ~flags & new_flags;
3414 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003415 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003416 _setSSLError(NULL, 0, __FILE__, __LINE__);
3417 return -1;
3418 }
3419 }
3420 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003421 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003422 _setSSLError(NULL, 0, __FILE__, __LINE__);
3423 return -1;
3424 }
3425 }
3426 return 0;
3427}
3428
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08003429/* Getter and setter for protocol version */
3430#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3431
3432
3433static int
3434set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3435{
3436 long v;
3437 int result;
3438
3439 if (!PyArg_Parse(arg, "l", &v))
3440 return -1;
3441 if (v > INT_MAX) {
3442 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3443 return -1;
3444 }
3445
3446 switch(self->protocol) {
3447 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3448 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3449 case PY_SSL_VERSION_TLS:
3450 break;
3451 default:
3452 PyErr_SetString(
3453 PyExc_ValueError,
3454 "The context's protocol doesn't support modification of "
3455 "highest and lowest version."
3456 );
3457 return -1;
3458 }
3459
3460 if (what == 0) {
3461 switch(v) {
3462 case PY_PROTO_MINIMUM_SUPPORTED:
3463 v = 0;
3464 break;
3465 case PY_PROTO_MAXIMUM_SUPPORTED:
3466 /* Emulate max for set_min_proto_version */
3467 v = PY_PROTO_MAXIMUM_AVAILABLE;
3468 break;
3469 default:
3470 break;
3471 }
3472 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3473 }
3474 else {
3475 switch(v) {
3476 case PY_PROTO_MAXIMUM_SUPPORTED:
3477 v = 0;
3478 break;
3479 case PY_PROTO_MINIMUM_SUPPORTED:
3480 /* Emulate max for set_min_proto_version */
3481 v = PY_PROTO_MINIMUM_AVAILABLE;
3482 break;
3483 default:
3484 break;
3485 }
3486 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3487 }
3488 if (result == 0) {
3489 PyErr_Format(PyExc_ValueError,
3490 "Unsupported protocol version 0x%x", v);
3491 return -1;
3492 }
3493 return 0;
3494}
3495
3496static PyObject *
3497get_minimum_version(PySSLContext *self, void *c)
3498{
3499 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3500 if (v == 0) {
3501 v = PY_PROTO_MINIMUM_SUPPORTED;
3502 }
3503 return PyLong_FromLong(v);
3504}
3505
3506static int
3507set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3508{
3509 return set_min_max_proto_version(self, arg, 0);
3510}
3511
3512static PyObject *
3513get_maximum_version(PySSLContext *self, void *c)
3514{
3515 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3516 if (v == 0) {
3517 v = PY_PROTO_MAXIMUM_SUPPORTED;
3518 }
3519 return PyLong_FromLong(v);
3520}
3521
3522static int
3523set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3524{
3525 return set_min_max_proto_version(self, arg, 1);
3526}
3527#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3528
Christian Heimes22587792013-11-21 23:56:13 +01003529static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003530get_options(PySSLContext *self, void *c)
3531{
3532 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3533}
3534
3535static int
3536set_options(PySSLContext *self, PyObject *arg, void *c)
3537{
3538 long new_opts, opts, set, clear;
3539 if (!PyArg_Parse(arg, "l", &new_opts))
3540 return -1;
3541 opts = SSL_CTX_get_options(self->ctx);
3542 clear = opts & ~new_opts;
3543 set = ~opts & new_opts;
3544 if (clear) {
3545#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3546 SSL_CTX_clear_options(self->ctx, clear);
3547#else
3548 PyErr_SetString(PyExc_ValueError,
3549 "can't clear options before OpenSSL 0.9.8m");
3550 return -1;
3551#endif
3552 }
3553 if (set)
3554 SSL_CTX_set_options(self->ctx, set);
3555 return 0;
3556}
3557
Christian Heimes1aa9a752013-12-02 02:41:19 +01003558static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003559get_host_flags(PySSLContext *self, void *c)
3560{
3561 return PyLong_FromUnsignedLong(self->hostflags);
3562}
3563
3564static int
3565set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3566{
3567 X509_VERIFY_PARAM *param;
3568 unsigned int new_flags = 0;
3569
3570 if (!PyArg_Parse(arg, "I", &new_flags))
3571 return -1;
3572
3573 param = SSL_CTX_get0_param(self->ctx);
3574 self->hostflags = new_flags;
3575 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3576 return 0;
3577}
3578
3579static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003580get_check_hostname(PySSLContext *self, void *c)
3581{
3582 return PyBool_FromLong(self->check_hostname);
3583}
3584
3585static int
3586set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3587{
3588 int check_hostname;
3589 if (!PyArg_Parse(arg, "p", &check_hostname))
3590 return -1;
3591 if (check_hostname &&
3592 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003593 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes2756ef32018-09-23 09:22:52 +02003594 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003595 return -1;
3596 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003597 }
3598 self->check_hostname = check_hostname;
3599 return 0;
3600}
3601
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003602static PyObject *
Christian Heimes2756ef32018-09-23 09:22:52 +02003603get_post_handshake_auth(PySSLContext *self, void *c) {
3604#if TLS1_3_VERSION
3605 return PyBool_FromLong(self->post_handshake_auth);
3606#else
3607 Py_RETURN_NONE;
3608#endif
3609}
3610
3611#if TLS1_3_VERSION
3612static int
3613set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3614 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3615 int mode = SSL_CTX_get_verify_mode(self->ctx);
3616 int pha = PyObject_IsTrue(arg);
3617
3618 if (pha == -1) {
3619 return -1;
3620 }
3621 self->post_handshake_auth = pha;
3622
3623 /* client-side socket setting, ignored by server-side */
3624 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3625
3626 /* server-side socket setting, ignored by client-side */
3627 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3628 if (pha) {
3629 mode |= SSL_VERIFY_POST_HANDSHAKE;
3630 } else {
3631 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3632 }
3633 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3634
3635 return 0;
3636}
3637#endif
3638
3639static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003640get_protocol(PySSLContext *self, void *c) {
3641 return PyLong_FromLong(self->protocol);
3642}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003643
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003644typedef struct {
3645 PyThreadState *thread_state;
3646 PyObject *callable;
3647 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003648 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003649 int error;
3650} _PySSLPasswordInfo;
3651
3652static int
3653_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3654 const char *bad_type_error)
3655{
3656 /* Set the password and size fields of a _PySSLPasswordInfo struct
3657 from a unicode, bytes, or byte array object.
3658 The password field will be dynamically allocated and must be freed
3659 by the caller */
3660 PyObject *password_bytes = NULL;
3661 const char *data = NULL;
3662 Py_ssize_t size;
3663
3664 if (PyUnicode_Check(password)) {
3665 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3666 if (!password_bytes) {
3667 goto error;
3668 }
3669 data = PyBytes_AS_STRING(password_bytes);
3670 size = PyBytes_GET_SIZE(password_bytes);
3671 } else if (PyBytes_Check(password)) {
3672 data = PyBytes_AS_STRING(password);
3673 size = PyBytes_GET_SIZE(password);
3674 } else if (PyByteArray_Check(password)) {
3675 data = PyByteArray_AS_STRING(password);
3676 size = PyByteArray_GET_SIZE(password);
3677 } else {
3678 PyErr_SetString(PyExc_TypeError, bad_type_error);
3679 goto error;
3680 }
3681
Victor Stinner9ee02032013-06-23 15:08:23 +02003682 if (size > (Py_ssize_t)INT_MAX) {
3683 PyErr_Format(PyExc_ValueError,
3684 "password cannot be longer than %d bytes", INT_MAX);
3685 goto error;
3686 }
3687
Victor Stinner11ebff22013-07-07 17:07:52 +02003688 PyMem_Free(pw_info->password);
3689 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003690 if (!pw_info->password) {
3691 PyErr_SetString(PyExc_MemoryError,
3692 "unable to allocate password buffer");
3693 goto error;
3694 }
3695 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003696 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003697
3698 Py_XDECREF(password_bytes);
3699 return 1;
3700
3701error:
3702 Py_XDECREF(password_bytes);
3703 return 0;
3704}
3705
3706static int
3707_password_callback(char *buf, int size, int rwflag, void *userdata)
3708{
3709 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3710 PyObject *fn_ret = NULL;
3711
3712 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3713
3714 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003715 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003716 if (!fn_ret) {
3717 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3718 core python API, so we could use it to add a frame here */
3719 goto error;
3720 }
3721
3722 if (!_pwinfo_set(pw_info, fn_ret,
3723 "password callback must return a string")) {
3724 goto error;
3725 }
3726 Py_CLEAR(fn_ret);
3727 }
3728
3729 if (pw_info->size > size) {
3730 PyErr_Format(PyExc_ValueError,
3731 "password cannot be longer than %d bytes", size);
3732 goto error;
3733 }
3734
3735 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3736 memcpy(buf, pw_info->password, pw_info->size);
3737 return pw_info->size;
3738
3739error:
3740 Py_XDECREF(fn_ret);
3741 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3742 pw_info->error = 1;
3743 return -1;
3744}
3745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003746/*[clinic input]
3747_ssl._SSLContext.load_cert_chain
3748 certfile: object
3749 keyfile: object = NULL
3750 password: object = NULL
3751
3752[clinic start generated code]*/
3753
Antoine Pitroub5218772010-05-21 09:56:06 +00003754static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003755_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3756 PyObject *keyfile, PyObject *password)
3757/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003758{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003759 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003760 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3761 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003762 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003763 int r;
3764
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003765 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003766 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003767 if (keyfile == Py_None)
3768 keyfile = NULL;
3769 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3770 PyErr_SetString(PyExc_TypeError,
3771 "certfile should be a valid filesystem path");
3772 return NULL;
3773 }
3774 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3775 PyErr_SetString(PyExc_TypeError,
3776 "keyfile should be a valid filesystem path");
3777 goto error;
3778 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003779 if (password && password != Py_None) {
3780 if (PyCallable_Check(password)) {
3781 pw_info.callable = password;
3782 } else if (!_pwinfo_set(&pw_info, password,
3783 "password should be a string or callable")) {
3784 goto error;
3785 }
3786 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3787 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3788 }
3789 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003790 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3791 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003792 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003793 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003794 if (pw_info.error) {
3795 ERR_clear_error();
3796 /* the password callback has already set the error information */
3797 }
3798 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003799 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003800 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003801 }
3802 else {
3803 _setSSLError(NULL, 0, __FILE__, __LINE__);
3804 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003805 goto error;
3806 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003807 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003808 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003809 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3810 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003811 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3812 Py_CLEAR(keyfile_bytes);
3813 Py_CLEAR(certfile_bytes);
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 Pitrou4fd1e6a2011-08-25 14:39:44 +02003826 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003827 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003828 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003829 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003830 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003831 if (r != 1) {
3832 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003833 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003834 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003835 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3836 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003837 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003838 Py_RETURN_NONE;
3839
3840error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003841 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3842 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003843 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003844 Py_XDECREF(keyfile_bytes);
3845 Py_XDECREF(certfile_bytes);
3846 return NULL;
3847}
3848
Christian Heimesefff7062013-11-21 03:35:02 +01003849/* internal helper function, returns -1 on error
3850 */
3851static int
3852_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3853 int filetype)
3854{
3855 BIO *biobuf = NULL;
3856 X509_STORE *store;
3857 int retval = 0, err, loaded = 0;
3858
3859 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3860
3861 if (len <= 0) {
3862 PyErr_SetString(PyExc_ValueError,
3863 "Empty certificate data");
3864 return -1;
3865 } else if (len > INT_MAX) {
3866 PyErr_SetString(PyExc_OverflowError,
3867 "Certificate data is too long.");
3868 return -1;
3869 }
3870
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003871 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003872 if (biobuf == NULL) {
3873 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3874 return -1;
3875 }
3876
3877 store = SSL_CTX_get_cert_store(self->ctx);
3878 assert(store != NULL);
3879
3880 while (1) {
3881 X509 *cert = NULL;
3882 int r;
3883
3884 if (filetype == SSL_FILETYPE_ASN1) {
3885 cert = d2i_X509_bio(biobuf, NULL);
3886 } else {
3887 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003888 SSL_CTX_get_default_passwd_cb(self->ctx),
3889 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3890 );
Christian Heimesefff7062013-11-21 03:35:02 +01003891 }
3892 if (cert == NULL) {
3893 break;
3894 }
3895 r = X509_STORE_add_cert(store, cert);
3896 X509_free(cert);
3897 if (!r) {
3898 err = ERR_peek_last_error();
3899 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3900 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3901 /* cert already in hash table, not an error */
3902 ERR_clear_error();
3903 } else {
3904 break;
3905 }
3906 }
3907 loaded++;
3908 }
3909
3910 err = ERR_peek_last_error();
3911 if ((filetype == SSL_FILETYPE_ASN1) &&
3912 (loaded > 0) &&
3913 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3914 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3915 /* EOF ASN1 file, not an error */
3916 ERR_clear_error();
3917 retval = 0;
3918 } else if ((filetype == SSL_FILETYPE_PEM) &&
3919 (loaded > 0) &&
3920 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3921 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3922 /* EOF PEM file, not an error */
3923 ERR_clear_error();
3924 retval = 0;
3925 } else {
3926 _setSSLError(NULL, 0, __FILE__, __LINE__);
3927 retval = -1;
3928 }
3929
3930 BIO_free(biobuf);
3931 return retval;
3932}
3933
3934
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935/*[clinic input]
3936_ssl._SSLContext.load_verify_locations
3937 cafile: object = NULL
3938 capath: object = NULL
3939 cadata: object = NULL
3940
3941[clinic start generated code]*/
3942
Antoine Pitrou152efa22010-05-16 18:19:27 +00003943static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003944_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3945 PyObject *cafile,
3946 PyObject *capath,
3947 PyObject *cadata)
3948/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003949{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003950 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3951 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003952 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003953
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003954 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003955 if (cafile == Py_None)
3956 cafile = NULL;
3957 if (capath == Py_None)
3958 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003959 if (cadata == Py_None)
3960 cadata = NULL;
3961
3962 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003963 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003964 "cafile, capath and cadata cannot be all omitted");
3965 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966 }
3967 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3968 PyErr_SetString(PyExc_TypeError,
3969 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003970 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003971 }
3972 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003973 PyErr_SetString(PyExc_TypeError,
3974 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003975 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976 }
Christian Heimesefff7062013-11-21 03:35:02 +01003977
3978 /* validata cadata type and load cadata */
3979 if (cadata) {
3980 Py_buffer buf;
3981 PyObject *cadata_ascii = NULL;
3982
3983 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3984 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3985 PyBuffer_Release(&buf);
3986 PyErr_SetString(PyExc_TypeError,
3987 "cadata should be a contiguous buffer with "
3988 "a single dimension");
3989 goto error;
3990 }
3991 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3992 PyBuffer_Release(&buf);
3993 if (r == -1) {
3994 goto error;
3995 }
3996 } else {
3997 PyErr_Clear();
3998 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3999 if (cadata_ascii == NULL) {
4000 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004001 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01004002 "bytes-like object");
4003 goto error;
4004 }
4005 r = _add_ca_certs(self,
4006 PyBytes_AS_STRING(cadata_ascii),
4007 PyBytes_GET_SIZE(cadata_ascii),
4008 SSL_FILETYPE_PEM);
4009 Py_DECREF(cadata_ascii);
4010 if (r == -1) {
4011 goto error;
4012 }
4013 }
4014 }
4015
4016 /* load cafile or capath */
4017 if (cafile || capath) {
4018 if (cafile)
4019 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4020 if (capath)
4021 capath_buf = PyBytes_AS_STRING(capath_bytes);
4022 PySSL_BEGIN_ALLOW_THREADS
4023 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4024 PySSL_END_ALLOW_THREADS
4025 if (r != 1) {
4026 ok = 0;
4027 if (errno != 0) {
4028 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004029 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004030 }
4031 else {
4032 _setSSLError(NULL, 0, __FILE__, __LINE__);
4033 }
4034 goto error;
4035 }
4036 }
4037 goto end;
4038
4039 error:
4040 ok = 0;
4041 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004042 Py_XDECREF(cafile_bytes);
4043 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004044 if (ok) {
4045 Py_RETURN_NONE;
4046 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004047 return NULL;
4048 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004049}
4050
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004051/*[clinic input]
4052_ssl._SSLContext.load_dh_params
4053 path as filepath: object
4054 /
4055
4056[clinic start generated code]*/
4057
Antoine Pitrou152efa22010-05-16 18:19:27 +00004058static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004059_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4060/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004061{
4062 FILE *f;
4063 DH *dh;
4064
Victor Stinnerdaf45552013-08-28 00:53:59 +02004065 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004066 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004067 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004068
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004069 errno = 0;
4070 PySSL_BEGIN_ALLOW_THREADS
4071 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004072 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004073 PySSL_END_ALLOW_THREADS
4074 if (dh == NULL) {
4075 if (errno != 0) {
4076 ERR_clear_error();
4077 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4078 }
4079 else {
4080 _setSSLError(NULL, 0, __FILE__, __LINE__);
4081 }
4082 return NULL;
4083 }
4084 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4085 _setSSLError(NULL, 0, __FILE__, __LINE__);
4086 DH_free(dh);
4087 Py_RETURN_NONE;
4088}
4089
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004090/*[clinic input]
4091_ssl._SSLContext._wrap_socket
4092 sock: object(subclass_of="PySocketModule.Sock_Type")
4093 server_side: int
4094 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004095 *
4096 owner: object = None
4097 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004098
4099[clinic start generated code]*/
4100
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004101static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004102_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004103 int server_side, PyObject *hostname_obj,
4104 PyObject *owner, PyObject *session)
4105/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004106{
Antoine Pitroud5323212010-10-22 18:19:07 +00004107 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004108 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004109
Antoine Pitroud5323212010-10-22 18:19:07 +00004110 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004111 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004112 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004113 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004114 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004115 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004116
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004117 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4118 server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004119 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004120 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004121 if (hostname != NULL)
4122 PyMem_Free(hostname);
4123 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004124}
4125
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004126/*[clinic input]
4127_ssl._SSLContext._wrap_bio
4128 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4129 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4130 server_side: int
4131 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004132 *
4133 owner: object = None
4134 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004135
4136[clinic start generated code]*/
4137
Antoine Pitroub0182c82010-10-12 20:09:02 +00004138static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004139_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4140 PySSLMemoryBIO *outgoing, int server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004141 PyObject *hostname_obj, PyObject *owner,
4142 PyObject *session)
4143/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004144{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004145 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004146 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004147
4148 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004149 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004150 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004151 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004152 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004153 }
4154
4155 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004156 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004157 incoming, outgoing);
4158
4159 PyMem_Free(hostname);
4160 return res;
4161}
4162
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004163/*[clinic input]
4164_ssl._SSLContext.session_stats
4165[clinic start generated code]*/
4166
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004167static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004168_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4169/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004170{
4171 int r;
4172 PyObject *value, *stats = PyDict_New();
4173 if (!stats)
4174 return NULL;
4175
4176#define ADD_STATS(SSL_NAME, KEY_NAME) \
4177 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4178 if (value == NULL) \
4179 goto error; \
4180 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4181 Py_DECREF(value); \
4182 if (r < 0) \
4183 goto error;
4184
4185 ADD_STATS(number, "number");
4186 ADD_STATS(connect, "connect");
4187 ADD_STATS(connect_good, "connect_good");
4188 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4189 ADD_STATS(accept, "accept");
4190 ADD_STATS(accept_good, "accept_good");
4191 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4192 ADD_STATS(accept, "accept");
4193 ADD_STATS(hits, "hits");
4194 ADD_STATS(misses, "misses");
4195 ADD_STATS(timeouts, "timeouts");
4196 ADD_STATS(cache_full, "cache_full");
4197
4198#undef ADD_STATS
4199
4200 return stats;
4201
4202error:
4203 Py_DECREF(stats);
4204 return NULL;
4205}
4206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207/*[clinic input]
4208_ssl._SSLContext.set_default_verify_paths
4209[clinic start generated code]*/
4210
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004211static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004212_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4213/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004214{
4215 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4216 _setSSLError(NULL, 0, __FILE__, __LINE__);
4217 return NULL;
4218 }
4219 Py_RETURN_NONE;
4220}
4221
Antoine Pitrou501da612011-12-21 09:27:41 +01004222#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004223/*[clinic input]
4224_ssl._SSLContext.set_ecdh_curve
4225 name: object
4226 /
4227
4228[clinic start generated code]*/
4229
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004230static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004231_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4232/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004233{
4234 PyObject *name_bytes;
4235 int nid;
4236 EC_KEY *key;
4237
4238 if (!PyUnicode_FSConverter(name, &name_bytes))
4239 return NULL;
4240 assert(PyBytes_Check(name_bytes));
4241 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4242 Py_DECREF(name_bytes);
4243 if (nid == 0) {
4244 PyErr_Format(PyExc_ValueError,
4245 "unknown elliptic curve name %R", name);
4246 return NULL;
4247 }
4248 key = EC_KEY_new_by_curve_name(nid);
4249 if (key == NULL) {
4250 _setSSLError(NULL, 0, __FILE__, __LINE__);
4251 return NULL;
4252 }
4253 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4254 EC_KEY_free(key);
4255 Py_RETURN_NONE;
4256}
Antoine Pitrou501da612011-12-21 09:27:41 +01004257#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004258
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004259#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004260static int
4261_servername_callback(SSL *s, int *al, void *args)
4262{
4263 int ret;
4264 PySSLContext *ssl_ctx = (PySSLContext *) args;
4265 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004266 PyObject *result;
4267 /* The high-level ssl.SSLSocket object */
4268 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004269 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004270 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004271
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004272 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004273 /* remove race condition in this the call back while if removing the
4274 * callback is in progress */
4275 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004276 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004277 }
4278
4279 ssl = SSL_get_app_data(s);
4280 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004281
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004282 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004283 * SSL connection and that has a .context attribute that can be changed to
4284 * identify the requested hostname. Since the official API is the Python
4285 * level API we want to pass the callback a Python level object rather than
4286 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4287 * SSLObject) that will be passed. Otherwise if there's a socket then that
4288 * will be passed. If both do not exist only then the C-level object is
4289 * passed. */
4290 if (ssl->owner)
4291 ssl_socket = PyWeakref_GetObject(ssl->owner);
4292 else if (ssl->Socket)
4293 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4294 else
4295 ssl_socket = (PyObject *) ssl;
4296
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004297 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004298 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004299 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004300
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004301 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004302 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004303 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004304 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004305 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004306 PyObject *servername_bytes;
4307 PyObject *servername_str;
4308
4309 servername_bytes = PyBytes_FromString(servername);
4310 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004311 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4312 goto error;
4313 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004314 /* server_hostname was encoded to an A-label by our caller; put it
4315 * back into a str object, but still as an A-label (bpo-28414)
4316 */
4317 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4318 Py_DECREF(servername_bytes);
4319 if (servername_str == NULL) {
4320 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004321 goto error;
4322 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004323 result = PyObject_CallFunctionObjArgs(
4324 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4325 ssl_ctx, NULL);
4326 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004327 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004328 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004329
4330 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004331 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004332 *al = SSL_AD_HANDSHAKE_FAILURE;
4333 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4334 }
4335 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004336 /* Result may be None, a SSLContext or an integer
4337 * None and SSLContext are OK, integer or other values are an error.
4338 */
4339 if (result == Py_None) {
4340 ret = SSL_TLSEXT_ERR_OK;
4341 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004342 *al = (int) PyLong_AsLong(result);
4343 if (PyErr_Occurred()) {
4344 PyErr_WriteUnraisable(result);
4345 *al = SSL_AD_INTERNAL_ERROR;
4346 }
4347 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4348 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004349 Py_DECREF(result);
4350 }
4351
4352 PyGILState_Release(gstate);
4353 return ret;
4354
4355error:
4356 Py_DECREF(ssl_socket);
4357 *al = SSL_AD_INTERNAL_ERROR;
4358 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4359 PyGILState_Release(gstate);
4360 return ret;
4361}
Antoine Pitroua5963382013-03-30 16:39:00 +01004362#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004363
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004364static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004365get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004366{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004367 PyObject *cb = self->set_sni_cb;
4368 if (cb == NULL) {
4369 Py_RETURN_NONE;
4370 }
4371 Py_INCREF(cb);
4372 return cb;
4373}
4374
4375static int
4376set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4377{
4378 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4379 PyErr_SetString(PyExc_ValueError,
4380 "sni_callback cannot be set on TLS_CLIENT context");
4381 return -1;
4382 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004383#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004384 Py_CLEAR(self->set_sni_cb);
4385 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004386 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4387 }
4388 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004389 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004390 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4391 PyErr_SetString(PyExc_TypeError,
4392 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004393 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004394 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004395 Py_INCREF(arg);
4396 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004397 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4398 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4399 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004400 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004401#else
4402 PyErr_SetString(PyExc_NotImplementedError,
4403 "The TLS extension servername callback, "
4404 "SSL_CTX_set_tlsext_servername_callback, "
4405 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004406 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004407#endif
4408}
4409
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004410PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4411"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4412\n\
4413If the argument is None then the callback is disabled. The method is called\n\
4414with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4415See RFC 6066 for details of the SNI extension.");
4416
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004417/*[clinic input]
4418_ssl._SSLContext.cert_store_stats
4419
4420Returns quantities of loaded X.509 certificates.
4421
4422X.509 certificates with a CA extension and certificate revocation lists
4423inside the context's cert store.
4424
4425NOTE: Certificates in a capath directory aren't loaded unless they have
4426been used at least once.
4427[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004428
4429static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004430_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4431/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004432{
4433 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004434 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004435 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004436 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004437
4438 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004439 objs = X509_STORE_get0_objects(store);
4440 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4441 obj = sk_X509_OBJECT_value(objs, i);
4442 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004443 case X509_LU_X509:
4444 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004445 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004446 ca++;
4447 }
4448 break;
4449 case X509_LU_CRL:
4450 crl++;
4451 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004452 default:
4453 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4454 * As far as I can tell they are internal states and never
4455 * stored in a cert store */
4456 break;
4457 }
4458 }
4459 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4460 "x509_ca", ca);
4461}
4462
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004463/*[clinic input]
4464_ssl._SSLContext.get_ca_certs
4465 binary_form: bool = False
4466
4467Returns a list of dicts with information of loaded CA certs.
4468
4469If the optional argument is True, returns a DER-encoded copy of the CA
4470certificate.
4471
4472NOTE: Certificates in a capath directory aren't loaded unless they have
4473been used at least once.
4474[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004475
4476static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004477_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4478/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004479{
4480 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004481 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004482 PyObject *ci = NULL, *rlist = NULL;
4483 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004484
4485 if ((rlist = PyList_New(0)) == NULL) {
4486 return NULL;
4487 }
4488
4489 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004490 objs = X509_STORE_get0_objects(store);
4491 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004492 X509_OBJECT *obj;
4493 X509 *cert;
4494
Christian Heimes598894f2016-09-05 23:19:05 +02004495 obj = sk_X509_OBJECT_value(objs, i);
4496 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004497 /* not a x509 cert */
4498 continue;
4499 }
4500 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004501 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004502 if (!X509_check_ca(cert)) {
4503 continue;
4504 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004505 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004506 ci = _certificate_to_der(cert);
4507 } else {
4508 ci = _decode_certificate(cert);
4509 }
4510 if (ci == NULL) {
4511 goto error;
4512 }
4513 if (PyList_Append(rlist, ci) == -1) {
4514 goto error;
4515 }
4516 Py_CLEAR(ci);
4517 }
4518 return rlist;
4519
4520 error:
4521 Py_XDECREF(ci);
4522 Py_XDECREF(rlist);
4523 return NULL;
4524}
4525
4526
Antoine Pitrou152efa22010-05-16 18:19:27 +00004527static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004528 {"check_hostname", (getter) get_check_hostname,
4529 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004530 {"_host_flags", (getter) get_host_flags,
4531 (setter) set_host_flags, NULL},
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004532#if SSL_CTRL_GET_MAX_PROTO_VERSION
4533 {"minimum_version", (getter) get_minimum_version,
4534 (setter) set_minimum_version, NULL},
4535 {"maximum_version", (getter) get_maximum_version,
4536 (setter) set_maximum_version, NULL},
4537#endif
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004538 {"sni_callback", (getter) get_sni_callback,
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004539 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004540 {"options", (getter) get_options,
4541 (setter) set_options, NULL},
Christian Heimes2756ef32018-09-23 09:22:52 +02004542 {"post_handshake_auth", (getter) get_post_handshake_auth,
4543#ifdef TLS1_3_VERSION
4544 (setter) set_post_handshake_auth,
4545#else
4546 NULL,
4547#endif
4548 NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004549 {"protocol", (getter) get_protocol,
4550 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004551 {"verify_flags", (getter) get_verify_flags,
4552 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004553 {"verify_mode", (getter) get_verify_mode,
4554 (setter) set_verify_mode, NULL},
4555 {NULL}, /* sentinel */
4556};
4557
4558static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004559 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4560 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4561 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4562 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4563 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4564 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4565 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4566 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4567 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4568 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4569 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004570 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4571 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004572 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004573 {NULL, NULL} /* sentinel */
4574};
4575
4576static PyTypeObject PySSLContext_Type = {
4577 PyVarObject_HEAD_INIT(NULL, 0)
4578 "_ssl._SSLContext", /*tp_name*/
4579 sizeof(PySSLContext), /*tp_basicsize*/
4580 0, /*tp_itemsize*/
4581 (destructor)context_dealloc, /*tp_dealloc*/
4582 0, /*tp_print*/
4583 0, /*tp_getattr*/
4584 0, /*tp_setattr*/
4585 0, /*tp_reserved*/
4586 0, /*tp_repr*/
4587 0, /*tp_as_number*/
4588 0, /*tp_as_sequence*/
4589 0, /*tp_as_mapping*/
4590 0, /*tp_hash*/
4591 0, /*tp_call*/
4592 0, /*tp_str*/
4593 0, /*tp_getattro*/
4594 0, /*tp_setattro*/
4595 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004596 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004597 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004598 (traverseproc) context_traverse, /*tp_traverse*/
4599 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004600 0, /*tp_richcompare*/
4601 0, /*tp_weaklistoffset*/
4602 0, /*tp_iter*/
4603 0, /*tp_iternext*/
4604 context_methods, /*tp_methods*/
4605 0, /*tp_members*/
4606 context_getsetlist, /*tp_getset*/
4607 0, /*tp_base*/
4608 0, /*tp_dict*/
4609 0, /*tp_descr_get*/
4610 0, /*tp_descr_set*/
4611 0, /*tp_dictoffset*/
4612 0, /*tp_init*/
4613 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004614 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004615};
4616
4617
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004618/*
4619 * MemoryBIO objects
4620 */
4621
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004622/*[clinic input]
4623@classmethod
4624_ssl.MemoryBIO.__new__
4625
4626[clinic start generated code]*/
4627
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004628static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004629_ssl_MemoryBIO_impl(PyTypeObject *type)
4630/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004631{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004632 BIO *bio;
4633 PySSLMemoryBIO *self;
4634
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004635 bio = BIO_new(BIO_s_mem());
4636 if (bio == NULL) {
4637 PyErr_SetString(PySSLErrorObject,
4638 "failed to allocate BIO");
4639 return NULL;
4640 }
4641 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4642 * just that no data is currently available. The SSL routines should retry
4643 * the read, which we can achieve by calling BIO_set_retry_read(). */
4644 BIO_set_retry_read(bio);
4645 BIO_set_mem_eof_return(bio, -1);
4646
4647 assert(type != NULL && type->tp_alloc != NULL);
4648 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4649 if (self == NULL) {
4650 BIO_free(bio);
4651 return NULL;
4652 }
4653 self->bio = bio;
4654 self->eof_written = 0;
4655
4656 return (PyObject *) self;
4657}
4658
4659static void
4660memory_bio_dealloc(PySSLMemoryBIO *self)
4661{
4662 BIO_free(self->bio);
4663 Py_TYPE(self)->tp_free(self);
4664}
4665
4666static PyObject *
4667memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4668{
Segev Finer5cff6372017-07-27 01:19:17 +03004669 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004670}
4671
4672PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4673"The number of bytes pending in the memory BIO.");
4674
4675static PyObject *
4676memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4677{
4678 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4679 && self->eof_written);
4680}
4681
4682PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4683"Whether the memory BIO is at EOF.");
4684
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004685/*[clinic input]
4686_ssl.MemoryBIO.read
4687 size as len: int = -1
4688 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004689
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004690Read up to size bytes from the memory BIO.
4691
4692If size is not specified, read the entire buffer.
4693If the return value is an empty bytes instance, this means either
4694EOF or that no data is available. Use the "eof" property to
4695distinguish between the two.
4696[clinic start generated code]*/
4697
4698static PyObject *
4699_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4700/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4701{
4702 int avail, nbytes;
4703 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004704
Segev Finer5cff6372017-07-27 01:19:17 +03004705 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004706 if ((len < 0) || (len > avail))
4707 len = avail;
4708
4709 result = PyBytes_FromStringAndSize(NULL, len);
4710 if ((result == NULL) || (len == 0))
4711 return result;
4712
4713 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004714 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004715 Py_DECREF(result);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004716 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004717 return NULL;
4718 }
4719
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004720 /* There should never be any short reads but check anyway. */
4721 if (nbytes < len) {
4722 _PyBytes_Resize(&result, nbytes);
4723 }
4724
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004725 return result;
4726}
4727
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004728/*[clinic input]
4729_ssl.MemoryBIO.write
4730 b: Py_buffer
4731 /
4732
4733Writes the bytes b into the memory BIO.
4734
4735Returns the number of bytes written.
4736[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004737
4738static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004739_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4740/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004741{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004742 int nbytes;
4743
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004744 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004745 PyErr_Format(PyExc_OverflowError,
4746 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004747 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004748 }
4749
4750 if (self->eof_written) {
4751 PyErr_SetString(PySSLErrorObject,
4752 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004753 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004754 }
4755
Segev Finer5cff6372017-07-27 01:19:17 +03004756 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004757 if (nbytes < 0) {
4758 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004759 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004760 }
4761
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004762 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004763}
4764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004765/*[clinic input]
4766_ssl.MemoryBIO.write_eof
4767
4768Write an EOF marker to the memory BIO.
4769
4770When all data has been read, the "eof" property will be True.
4771[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004772
4773static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004774_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4775/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004776{
4777 self->eof_written = 1;
4778 /* After an EOF is written, a zero return from read() should be a real EOF
4779 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4780 BIO_clear_retry_flags(self->bio);
4781 BIO_set_mem_eof_return(self->bio, 0);
4782
4783 Py_RETURN_NONE;
4784}
4785
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004786static PyGetSetDef memory_bio_getsetlist[] = {
4787 {"pending", (getter) memory_bio_get_pending, NULL,
4788 PySSL_memory_bio_pending_doc},
4789 {"eof", (getter) memory_bio_get_eof, NULL,
4790 PySSL_memory_bio_eof_doc},
4791 {NULL}, /* sentinel */
4792};
4793
4794static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004795 _SSL_MEMORYBIO_READ_METHODDEF
4796 _SSL_MEMORYBIO_WRITE_METHODDEF
4797 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004798 {NULL, NULL} /* sentinel */
4799};
4800
4801static PyTypeObject PySSLMemoryBIO_Type = {
4802 PyVarObject_HEAD_INIT(NULL, 0)
4803 "_ssl.MemoryBIO", /*tp_name*/
4804 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4805 0, /*tp_itemsize*/
4806 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4807 0, /*tp_print*/
4808 0, /*tp_getattr*/
4809 0, /*tp_setattr*/
4810 0, /*tp_reserved*/
4811 0, /*tp_repr*/
4812 0, /*tp_as_number*/
4813 0, /*tp_as_sequence*/
4814 0, /*tp_as_mapping*/
4815 0, /*tp_hash*/
4816 0, /*tp_call*/
4817 0, /*tp_str*/
4818 0, /*tp_getattro*/
4819 0, /*tp_setattro*/
4820 0, /*tp_as_buffer*/
4821 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4822 0, /*tp_doc*/
4823 0, /*tp_traverse*/
4824 0, /*tp_clear*/
4825 0, /*tp_richcompare*/
4826 0, /*tp_weaklistoffset*/
4827 0, /*tp_iter*/
4828 0, /*tp_iternext*/
4829 memory_bio_methods, /*tp_methods*/
4830 0, /*tp_members*/
4831 memory_bio_getsetlist, /*tp_getset*/
4832 0, /*tp_base*/
4833 0, /*tp_dict*/
4834 0, /*tp_descr_get*/
4835 0, /*tp_descr_set*/
4836 0, /*tp_dictoffset*/
4837 0, /*tp_init*/
4838 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004839 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004840};
4841
Antoine Pitrou152efa22010-05-16 18:19:27 +00004842
Christian Heimes99a65702016-09-10 23:44:53 +02004843/*
4844 * SSL Session object
4845 */
4846
4847static void
4848PySSLSession_dealloc(PySSLSession *self)
4849{
INADA Naokia6296d32017-08-24 14:55:17 +09004850 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004851 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004852 Py_XDECREF(self->ctx);
4853 if (self->session != NULL) {
4854 SSL_SESSION_free(self->session);
4855 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004856 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004857}
4858
4859static PyObject *
4860PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4861{
4862 int result;
4863
4864 if (left == NULL || right == NULL) {
4865 PyErr_BadInternalCall();
4866 return NULL;
4867 }
4868
4869 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4870 Py_RETURN_NOTIMPLEMENTED;
4871 }
4872
4873 if (left == right) {
4874 result = 0;
4875 } else {
4876 const unsigned char *left_id, *right_id;
4877 unsigned int left_len, right_len;
4878 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4879 &left_len);
4880 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4881 &right_len);
4882 if (left_len == right_len) {
4883 result = memcmp(left_id, right_id, left_len);
4884 } else {
4885 result = 1;
4886 }
4887 }
4888
4889 switch (op) {
4890 case Py_EQ:
4891 if (result == 0) {
4892 Py_RETURN_TRUE;
4893 } else {
4894 Py_RETURN_FALSE;
4895 }
4896 break;
4897 case Py_NE:
4898 if (result != 0) {
4899 Py_RETURN_TRUE;
4900 } else {
4901 Py_RETURN_FALSE;
4902 }
4903 break;
4904 case Py_LT:
4905 case Py_LE:
4906 case Py_GT:
4907 case Py_GE:
4908 Py_RETURN_NOTIMPLEMENTED;
4909 break;
4910 default:
4911 PyErr_BadArgument();
4912 return NULL;
4913 }
4914}
4915
4916static int
4917PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4918{
4919 Py_VISIT(self->ctx);
4920 return 0;
4921}
4922
4923static int
4924PySSLSession_clear(PySSLSession *self)
4925{
4926 Py_CLEAR(self->ctx);
4927 return 0;
4928}
4929
4930
4931static PyObject *
4932PySSLSession_get_time(PySSLSession *self, void *closure) {
4933 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4934}
4935
4936PyDoc_STRVAR(PySSLSession_get_time_doc,
4937"Session creation time (seconds since epoch).");
4938
4939
4940static PyObject *
4941PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4942 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4943}
4944
4945PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4946"Session timeout (delta in seconds).");
4947
4948
4949static PyObject *
4950PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4951 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4952 return PyLong_FromUnsignedLong(hint);
4953}
4954
4955PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4956"Ticket life time hint.");
4957
4958
4959static PyObject *
4960PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4961 const unsigned char *id;
4962 unsigned int len;
4963 id = SSL_SESSION_get_id(self->session, &len);
4964 return PyBytes_FromStringAndSize((const char *)id, len);
4965}
4966
4967PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4968"Session id");
4969
4970
4971static PyObject *
4972PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4973 if (SSL_SESSION_has_ticket(self->session)) {
4974 Py_RETURN_TRUE;
4975 } else {
4976 Py_RETURN_FALSE;
4977 }
4978}
4979
4980PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4981"Does the session contain a ticket?");
4982
4983
4984static PyGetSetDef PySSLSession_getsetlist[] = {
4985 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4986 PySSLSession_get_has_ticket_doc},
4987 {"id", (getter) PySSLSession_get_session_id, NULL,
4988 PySSLSession_get_session_id_doc},
4989 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4990 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4991 {"time", (getter) PySSLSession_get_time, NULL,
4992 PySSLSession_get_time_doc},
4993 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4994 PySSLSession_get_timeout_doc},
4995 {NULL}, /* sentinel */
4996};
4997
4998static PyTypeObject PySSLSession_Type = {
4999 PyVarObject_HEAD_INIT(NULL, 0)
5000 "_ssl.Session", /*tp_name*/
5001 sizeof(PySSLSession), /*tp_basicsize*/
5002 0, /*tp_itemsize*/
5003 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
5004 0, /*tp_print*/
5005 0, /*tp_getattr*/
5006 0, /*tp_setattr*/
5007 0, /*tp_reserved*/
5008 0, /*tp_repr*/
5009 0, /*tp_as_number*/
5010 0, /*tp_as_sequence*/
5011 0, /*tp_as_mapping*/
5012 0, /*tp_hash*/
5013 0, /*tp_call*/
5014 0, /*tp_str*/
5015 0, /*tp_getattro*/
5016 0, /*tp_setattro*/
5017 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005018 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005019 0, /*tp_doc*/
5020 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5021 (inquiry)PySSLSession_clear, /*tp_clear*/
5022 PySSLSession_richcompare, /*tp_richcompare*/
5023 0, /*tp_weaklistoffset*/
5024 0, /*tp_iter*/
5025 0, /*tp_iternext*/
5026 0, /*tp_methods*/
5027 0, /*tp_members*/
5028 PySSLSession_getsetlist, /*tp_getset*/
5029};
5030
5031
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005032/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005033/*[clinic input]
5034_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005035 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005036 entropy: double
5037 /
5038
5039Mix string into the OpenSSL PRNG state.
5040
5041entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305042string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005043[clinic start generated code]*/
5044
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005046_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005047/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005048{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005049 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005050 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005051
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005052 buf = (const char *)view->buf;
5053 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005054 do {
5055 written = Py_MIN(len, INT_MAX);
5056 RAND_add(buf, (int)written, entropy);
5057 buf += written;
5058 len -= written;
5059 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005060 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005061}
5062
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005063static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005064PySSL_RAND(int len, int pseudo)
5065{
5066 int ok;
5067 PyObject *bytes;
5068 unsigned long err;
5069 const char *errstr;
5070 PyObject *v;
5071
Victor Stinner1e81a392013-12-19 16:47:04 +01005072 if (len < 0) {
5073 PyErr_SetString(PyExc_ValueError, "num must be positive");
5074 return NULL;
5075 }
5076
Victor Stinner99c8b162011-05-24 12:05:19 +02005077 bytes = PyBytes_FromStringAndSize(NULL, len);
5078 if (bytes == NULL)
5079 return NULL;
5080 if (pseudo) {
5081 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5082 if (ok == 0 || ok == 1)
5083 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5084 }
5085 else {
5086 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5087 if (ok == 1)
5088 return bytes;
5089 }
5090 Py_DECREF(bytes);
5091
5092 err = ERR_get_error();
5093 errstr = ERR_reason_error_string(err);
5094 v = Py_BuildValue("(ks)", err, errstr);
5095 if (v != NULL) {
5096 PyErr_SetObject(PySSLErrorObject, v);
5097 Py_DECREF(v);
5098 }
5099 return NULL;
5100}
5101
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005102/*[clinic input]
5103_ssl.RAND_bytes
5104 n: int
5105 /
5106
5107Generate n cryptographically strong pseudo-random bytes.
5108[clinic start generated code]*/
5109
Victor Stinner99c8b162011-05-24 12:05:19 +02005110static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005111_ssl_RAND_bytes_impl(PyObject *module, int n)
5112/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005113{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005114 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005115}
5116
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005117/*[clinic input]
5118_ssl.RAND_pseudo_bytes
5119 n: int
5120 /
5121
5122Generate n pseudo-random bytes.
5123
5124Return a pair (bytes, is_cryptographic). is_cryptographic is True
5125if the bytes generated are cryptographically strong.
5126[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005127
5128static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005129_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5130/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005131{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005132 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005133}
5134
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005135/*[clinic input]
5136_ssl.RAND_status
5137
5138Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5139
5140It is necessary to seed the PRNG with RAND_add() on some platforms before
5141using the ssl() function.
5142[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005143
5144static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005145_ssl_RAND_status_impl(PyObject *module)
5146/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005147{
Christian Heimes217cfd12007-12-02 14:31:20 +00005148 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005149}
5150
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005151#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005152/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005153/*[clinic input]
5154_ssl.RAND_egd
5155 path: object(converter="PyUnicode_FSConverter")
5156 /
5157
5158Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5159
5160Returns number of bytes read. Raises SSLError if connection to EGD
5161fails or if it does not provide enough data to seed PRNG.
5162[clinic start generated code]*/
5163
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005164static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005165_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5166/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005167{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005168 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005169 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005170 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005171 PyErr_SetString(PySSLErrorObject,
5172 "EGD connection failed or EGD did not return "
5173 "enough data to seed the PRNG");
5174 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005175 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005176 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005177}
Christian Heimesa5d07652016-09-24 10:48:05 +02005178/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005179#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005180
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005181
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005182
5183/*[clinic input]
5184_ssl.get_default_verify_paths
5185
5186Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5187
5188The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5189[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005190
5191static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005192_ssl_get_default_verify_paths_impl(PyObject *module)
5193/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005194{
5195 PyObject *ofile_env = NULL;
5196 PyObject *ofile = NULL;
5197 PyObject *odir_env = NULL;
5198 PyObject *odir = NULL;
5199
Benjamin Petersond113c962015-07-18 10:59:13 -07005200#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005201 const char *tmp = (info); \
5202 target = NULL; \
5203 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5204 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5205 target = PyBytes_FromString(tmp); } \
5206 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005207 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005208
Benjamin Petersond113c962015-07-18 10:59:13 -07005209 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5210 CONVERT(X509_get_default_cert_file(), ofile);
5211 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5212 CONVERT(X509_get_default_cert_dir(), odir);
5213#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005214
Christian Heimes200bb1b2013-06-14 15:14:29 +02005215 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005216
5217 error:
5218 Py_XDECREF(ofile_env);
5219 Py_XDECREF(ofile);
5220 Py_XDECREF(odir_env);
5221 Py_XDECREF(odir);
5222 return NULL;
5223}
5224
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005225static PyObject*
5226asn1obj2py(ASN1_OBJECT *obj)
5227{
5228 int nid;
5229 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005230
5231 nid = OBJ_obj2nid(obj);
5232 if (nid == NID_undef) {
5233 PyErr_Format(PyExc_ValueError, "Unknown object");
5234 return NULL;
5235 }
5236 sn = OBJ_nid2sn(nid);
5237 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005238 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005239}
5240
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005241/*[clinic input]
5242_ssl.txt2obj
5243 txt: str
5244 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005245
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005246Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5247
5248By default objects are looked up by OID. With name=True short and
5249long name are also matched.
5250[clinic start generated code]*/
5251
5252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005253_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5254/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005255{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005256 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005257 ASN1_OBJECT *obj;
5258
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005259 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5260 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005261 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005262 return NULL;
5263 }
5264 result = asn1obj2py(obj);
5265 ASN1_OBJECT_free(obj);
5266 return result;
5267}
5268
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005269/*[clinic input]
5270_ssl.nid2obj
5271 nid: int
5272 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005274Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5275[clinic start generated code]*/
5276
5277static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005278_ssl_nid2obj_impl(PyObject *module, int nid)
5279/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005280{
5281 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005282 ASN1_OBJECT *obj;
5283
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005284 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005285 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005286 return NULL;
5287 }
5288 obj = OBJ_nid2obj(nid);
5289 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005290 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005291 return NULL;
5292 }
5293 result = asn1obj2py(obj);
5294 ASN1_OBJECT_free(obj);
5295 return result;
5296}
5297
Christian Heimes46bebee2013-06-09 19:03:31 +02005298#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005299
5300static PyObject*
5301certEncodingType(DWORD encodingType)
5302{
5303 static PyObject *x509_asn = NULL;
5304 static PyObject *pkcs_7_asn = NULL;
5305
5306 if (x509_asn == NULL) {
5307 x509_asn = PyUnicode_InternFromString("x509_asn");
5308 if (x509_asn == NULL)
5309 return NULL;
5310 }
5311 if (pkcs_7_asn == NULL) {
5312 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5313 if (pkcs_7_asn == NULL)
5314 return NULL;
5315 }
5316 switch(encodingType) {
5317 case X509_ASN_ENCODING:
5318 Py_INCREF(x509_asn);
5319 return x509_asn;
5320 case PKCS_7_ASN_ENCODING:
5321 Py_INCREF(pkcs_7_asn);
5322 return pkcs_7_asn;
5323 default:
5324 return PyLong_FromLong(encodingType);
5325 }
5326}
5327
5328static PyObject*
5329parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5330{
5331 CERT_ENHKEY_USAGE *usage;
5332 DWORD size, error, i;
5333 PyObject *retval;
5334
5335 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5336 error = GetLastError();
5337 if (error == CRYPT_E_NOT_FOUND) {
5338 Py_RETURN_TRUE;
5339 }
5340 return PyErr_SetFromWindowsErr(error);
5341 }
5342
5343 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5344 if (usage == NULL) {
5345 return PyErr_NoMemory();
5346 }
5347
5348 /* Now get the actual enhanced usage property */
5349 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5350 PyMem_Free(usage);
5351 error = GetLastError();
5352 if (error == CRYPT_E_NOT_FOUND) {
5353 Py_RETURN_TRUE;
5354 }
5355 return PyErr_SetFromWindowsErr(error);
5356 }
5357 retval = PySet_New(NULL);
5358 if (retval == NULL) {
5359 goto error;
5360 }
5361 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5362 if (usage->rgpszUsageIdentifier[i]) {
5363 PyObject *oid;
5364 int err;
5365 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5366 if (oid == NULL) {
5367 Py_CLEAR(retval);
5368 goto error;
5369 }
5370 err = PySet_Add(retval, oid);
5371 Py_DECREF(oid);
5372 if (err == -1) {
5373 Py_CLEAR(retval);
5374 goto error;
5375 }
5376 }
5377 }
5378 error:
5379 PyMem_Free(usage);
5380 return retval;
5381}
5382
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005383/*[clinic input]
5384_ssl.enum_certificates
5385 store_name: str
5386
5387Retrieve certificates from Windows' cert store.
5388
5389store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5390more cert storages, too. The function returns a list of (bytes,
5391encoding_type, trust) tuples. The encoding_type flag can be interpreted
5392with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5393a set of OIDs or the boolean True.
5394[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005395
Christian Heimes46bebee2013-06-09 19:03:31 +02005396static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005397_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5398/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005399{
Christian Heimes46bebee2013-06-09 19:03:31 +02005400 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005401 PCCERT_CONTEXT pCertCtx = NULL;
5402 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005403 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005404
Christian Heimes44109d72013-11-22 01:51:30 +01005405 result = PyList_New(0);
5406 if (result == NULL) {
5407 return NULL;
5408 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005409 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5410 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5411 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005412 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005413 Py_DECREF(result);
5414 return PyErr_SetFromWindowsErr(GetLastError());
5415 }
5416
Christian Heimes44109d72013-11-22 01:51:30 +01005417 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5418 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5419 pCertCtx->cbCertEncoded);
5420 if (!cert) {
5421 Py_CLEAR(result);
5422 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005423 }
Christian Heimes44109d72013-11-22 01:51:30 +01005424 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5425 Py_CLEAR(result);
5426 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005427 }
Christian Heimes44109d72013-11-22 01:51:30 +01005428 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5429 if (keyusage == Py_True) {
5430 Py_DECREF(keyusage);
5431 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005432 }
Christian Heimes44109d72013-11-22 01:51:30 +01005433 if (keyusage == NULL) {
5434 Py_CLEAR(result);
5435 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005436 }
Christian Heimes44109d72013-11-22 01:51:30 +01005437 if ((tup = PyTuple_New(3)) == NULL) {
5438 Py_CLEAR(result);
5439 break;
5440 }
5441 PyTuple_SET_ITEM(tup, 0, cert);
5442 cert = NULL;
5443 PyTuple_SET_ITEM(tup, 1, enc);
5444 enc = NULL;
5445 PyTuple_SET_ITEM(tup, 2, keyusage);
5446 keyusage = NULL;
5447 if (PyList_Append(result, tup) < 0) {
5448 Py_CLEAR(result);
5449 break;
5450 }
5451 Py_CLEAR(tup);
5452 }
5453 if (pCertCtx) {
5454 /* loop ended with an error, need to clean up context manually */
5455 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005456 }
5457
5458 /* In error cases cert, enc and tup may not be NULL */
5459 Py_XDECREF(cert);
5460 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005461 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005462 Py_XDECREF(tup);
5463
5464 if (!CertCloseStore(hStore, 0)) {
5465 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005466 Py_XDECREF(result);
5467 return PyErr_SetFromWindowsErr(GetLastError());
5468 }
5469 return result;
5470}
5471
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005472/*[clinic input]
5473_ssl.enum_crls
5474 store_name: str
5475
5476Retrieve CRLs from Windows' cert store.
5477
5478store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5479more cert storages, too. The function returns a list of (bytes,
5480encoding_type) tuples. The encoding_type flag can be interpreted with
5481X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5482[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005483
5484static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005485_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5486/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005487{
Christian Heimes44109d72013-11-22 01:51:30 +01005488 HCERTSTORE hStore = NULL;
5489 PCCRL_CONTEXT pCrlCtx = NULL;
5490 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5491 PyObject *result = NULL;
5492
Christian Heimes44109d72013-11-22 01:51:30 +01005493 result = PyList_New(0);
5494 if (result == NULL) {
5495 return NULL;
5496 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005497 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5498 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5499 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005500 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005501 Py_DECREF(result);
5502 return PyErr_SetFromWindowsErr(GetLastError());
5503 }
Christian Heimes44109d72013-11-22 01:51:30 +01005504
5505 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5506 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5507 pCrlCtx->cbCrlEncoded);
5508 if (!crl) {
5509 Py_CLEAR(result);
5510 break;
5511 }
5512 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5513 Py_CLEAR(result);
5514 break;
5515 }
5516 if ((tup = PyTuple_New(2)) == NULL) {
5517 Py_CLEAR(result);
5518 break;
5519 }
5520 PyTuple_SET_ITEM(tup, 0, crl);
5521 crl = NULL;
5522 PyTuple_SET_ITEM(tup, 1, enc);
5523 enc = NULL;
5524
5525 if (PyList_Append(result, tup) < 0) {
5526 Py_CLEAR(result);
5527 break;
5528 }
5529 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005530 }
Christian Heimes44109d72013-11-22 01:51:30 +01005531 if (pCrlCtx) {
5532 /* loop ended with an error, need to clean up context manually */
5533 CertFreeCRLContext(pCrlCtx);
5534 }
5535
5536 /* In error cases cert, enc and tup may not be NULL */
5537 Py_XDECREF(crl);
5538 Py_XDECREF(enc);
5539 Py_XDECREF(tup);
5540
5541 if (!CertCloseStore(hStore, 0)) {
5542 /* This error case might shadow another exception.*/
5543 Py_XDECREF(result);
5544 return PyErr_SetFromWindowsErr(GetLastError());
5545 }
5546 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005547}
Christian Heimes44109d72013-11-22 01:51:30 +01005548
5549#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005550
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005551/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005552static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005553 _SSL__TEST_DECODE_CERT_METHODDEF
5554 _SSL_RAND_ADD_METHODDEF
5555 _SSL_RAND_BYTES_METHODDEF
5556 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5557 _SSL_RAND_EGD_METHODDEF
5558 _SSL_RAND_STATUS_METHODDEF
5559 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5560 _SSL_ENUM_CERTIFICATES_METHODDEF
5561 _SSL_ENUM_CRLS_METHODDEF
5562 _SSL_TXT2OBJ_METHODDEF
5563 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005564 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005565};
5566
5567
Christian Heimes598894f2016-09-05 23:19:05 +02005568#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005569
5570/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005571 * of the Python C thread library
5572 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5573 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005574
5575static PyThread_type_lock *_ssl_locks = NULL;
5576
Christian Heimes4d98ca92013-08-19 17:36:29 +02005577#if OPENSSL_VERSION_NUMBER >= 0x10000000
5578/* use new CRYPTO_THREADID API. */
5579static void
5580_ssl_threadid_callback(CRYPTO_THREADID *id)
5581{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005582 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005583}
5584#else
5585/* deprecated CRYPTO_set_id_callback() API. */
5586static unsigned long
5587_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005588 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005589}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005590#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005591
Bill Janssen6e027db2007-11-15 22:23:56 +00005592static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005593 (int mode, int n, const char *file, int line) {
5594 /* this function is needed to perform locking on shared data
5595 structures. (Note that OpenSSL uses a number of global data
5596 structures that will be implicitly shared whenever multiple
5597 threads use OpenSSL.) Multi-threaded applications will
5598 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005600 locking_function() must be able to handle up to
5601 CRYPTO_num_locks() different mutex locks. It sets the n-th
5602 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005604 file and line are the file number of the function setting the
5605 lock. They can be useful for debugging.
5606 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005608 if ((_ssl_locks == NULL) ||
5609 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5610 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005612 if (mode & CRYPTO_LOCK) {
5613 PyThread_acquire_lock(_ssl_locks[n], 1);
5614 } else {
5615 PyThread_release_lock(_ssl_locks[n]);
5616 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005617}
5618
5619static int _setup_ssl_threads(void) {
5620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005621 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005622
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005623 if (_ssl_locks == NULL) {
5624 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005625 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5626 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005627 if (_ssl_locks == NULL) {
5628 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005629 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005630 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005631 for (i = 0; i < _ssl_locks_count; i++) {
5632 _ssl_locks[i] = PyThread_allocate_lock();
5633 if (_ssl_locks[i] == NULL) {
5634 unsigned int j;
5635 for (j = 0; j < i; j++) {
5636 PyThread_free_lock(_ssl_locks[j]);
5637 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005638 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005639 return 0;
5640 }
5641 }
5642 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005643#if OPENSSL_VERSION_NUMBER >= 0x10000000
5644 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5645#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005646 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005647#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005648 }
5649 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005650}
5651
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005652#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005653
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005654PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005655"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005656for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005657
Martin v. Löwis1a214512008-06-11 05:26:20 +00005658
5659static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005660 PyModuleDef_HEAD_INIT,
5661 "_ssl",
5662 module_doc,
5663 -1,
5664 PySSL_methods,
5665 NULL,
5666 NULL,
5667 NULL,
5668 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005669};
5670
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005671
5672static void
5673parse_openssl_version(unsigned long libver,
5674 unsigned int *major, unsigned int *minor,
5675 unsigned int *fix, unsigned int *patch,
5676 unsigned int *status)
5677{
5678 *status = libver & 0xF;
5679 libver >>= 4;
5680 *patch = libver & 0xFF;
5681 libver >>= 8;
5682 *fix = libver & 0xFF;
5683 libver >>= 8;
5684 *minor = libver & 0xFF;
5685 libver >>= 8;
5686 *major = libver & 0xFF;
5687}
5688
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005689PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005690PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005691{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005692 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005693 unsigned long libver;
5694 unsigned int major, minor, fix, patch, status;
5695 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005696 struct py_ssl_error_code *errcode;
5697 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005698
Antoine Pitrou152efa22010-05-16 18:19:27 +00005699 if (PyType_Ready(&PySSLContext_Type) < 0)
5700 return NULL;
5701 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005702 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005703 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5704 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005705 if (PyType_Ready(&PySSLSession_Type) < 0)
5706 return NULL;
5707
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005709 m = PyModule_Create(&_sslmodule);
5710 if (m == NULL)
5711 return NULL;
5712 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005714 /* Load _socket module and its C API */
5715 socket_api = PySocketModule_ImportModuleAndAPI();
5716 if (!socket_api)
5717 return NULL;
5718 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005719
Christian Heimesc941e622017-09-05 15:47:11 +02005720#ifndef OPENSSL_VERSION_1_1
5721 /* Load all algorithms and initialize cpuid */
5722 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005723 /* Init OpenSSL */
5724 SSL_load_error_strings();
5725 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005726#endif
5727
Christian Heimes598894f2016-09-05 23:19:05 +02005728#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005729 /* note that this will start threading if not already started */
5730 if (!_setup_ssl_threads()) {
5731 return NULL;
5732 }
Christian Heimes598894f2016-09-05 23:19:05 +02005733#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5734 /* OpenSSL 1.1.0 builtin thread support is enabled */
5735 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005736#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005738 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005739 sslerror_type_slots[0].pfunc = PyExc_OSError;
5740 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005741 if (PySSLErrorObject == NULL)
5742 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005743
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005744 /* ssl.CertificateError used to be a subclass of ValueError */
5745 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5746 if (bases == NULL)
5747 return NULL;
5748 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5749 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5750 bases, NULL);
5751 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005752 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5753 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5754 PySSLErrorObject, NULL);
5755 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5756 "ssl.SSLWantReadError", SSLWantReadError_doc,
5757 PySSLErrorObject, NULL);
5758 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5759 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5760 PySSLErrorObject, NULL);
5761 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5762 "ssl.SSLSyscallError", SSLSyscallError_doc,
5763 PySSLErrorObject, NULL);
5764 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5765 "ssl.SSLEOFError", SSLEOFError_doc,
5766 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005767 if (PySSLCertVerificationErrorObject == NULL
5768 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005769 || PySSLWantReadErrorObject == NULL
5770 || PySSLWantWriteErrorObject == NULL
5771 || PySSLSyscallErrorObject == NULL
5772 || PySSLEOFErrorObject == NULL)
5773 return NULL;
5774 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005775 || PyDict_SetItemString(d, "SSLCertVerificationError",
5776 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005777 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5778 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5779 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5780 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5781 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005782 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005783 if (PyDict_SetItemString(d, "_SSLContext",
5784 (PyObject *)&PySSLContext_Type) != 0)
5785 return NULL;
5786 if (PyDict_SetItemString(d, "_SSLSocket",
5787 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005788 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005789 if (PyDict_SetItemString(d, "MemoryBIO",
5790 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5791 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005792 if (PyDict_SetItemString(d, "SSLSession",
5793 (PyObject *)&PySSLSession_Type) != 0)
5794 return NULL;
5795
Christian Heimes892d66e2018-01-29 14:10:18 +01005796 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5797 PY_SSL_DEFAULT_CIPHER_STRING);
5798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005799 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5800 PY_SSL_ERROR_ZERO_RETURN);
5801 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5802 PY_SSL_ERROR_WANT_READ);
5803 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5804 PY_SSL_ERROR_WANT_WRITE);
5805 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5806 PY_SSL_ERROR_WANT_X509_LOOKUP);
5807 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5808 PY_SSL_ERROR_SYSCALL);
5809 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5810 PY_SSL_ERROR_SSL);
5811 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5812 PY_SSL_ERROR_WANT_CONNECT);
5813 /* non ssl.h errorcodes */
5814 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5815 PY_SSL_ERROR_EOF);
5816 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5817 PY_SSL_ERROR_INVALID_ERROR_CODE);
5818 /* cert requirements */
5819 PyModule_AddIntConstant(m, "CERT_NONE",
5820 PY_SSL_CERT_NONE);
5821 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5822 PY_SSL_CERT_OPTIONAL);
5823 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5824 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005825 /* CRL verification for verification_flags */
5826 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5827 0);
5828 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5829 X509_V_FLAG_CRL_CHECK);
5830 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5831 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5832 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5833 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005834#ifdef X509_V_FLAG_TRUSTED_FIRST
5835 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5836 X509_V_FLAG_TRUSTED_FIRST);
5837#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005838
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005839 /* Alert Descriptions from ssl.h */
5840 /* note RESERVED constants no longer intended for use have been removed */
5841 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5842
5843#define ADD_AD_CONSTANT(s) \
5844 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5845 SSL_AD_##s)
5846
5847 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5848 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5849 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5850 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5851 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5852 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5853 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5854 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5855 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5856 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5857 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5858 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5859 ADD_AD_CONSTANT(UNKNOWN_CA);
5860 ADD_AD_CONSTANT(ACCESS_DENIED);
5861 ADD_AD_CONSTANT(DECODE_ERROR);
5862 ADD_AD_CONSTANT(DECRYPT_ERROR);
5863 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5864 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5865 ADD_AD_CONSTANT(INTERNAL_ERROR);
5866 ADD_AD_CONSTANT(USER_CANCELLED);
5867 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005868 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005869#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5870 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5871#endif
5872#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5873 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5874#endif
5875#ifdef SSL_AD_UNRECOGNIZED_NAME
5876 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5877#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005878#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5879 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5880#endif
5881#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5882 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5883#endif
5884#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5885 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5886#endif
5887
5888#undef ADD_AD_CONSTANT
5889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005890 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005891#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005892 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5893 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005894#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005895#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005896 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5897 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005898#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005899 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005900 PY_SSL_VERSION_TLS);
5901 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5902 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005903 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5904 PY_SSL_VERSION_TLS_CLIENT);
5905 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5906 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005907 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5908 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005909#if HAVE_TLSv1_2
5910 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5911 PY_SSL_VERSION_TLS1_1);
5912 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5913 PY_SSL_VERSION_TLS1_2);
5914#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005915
Antoine Pitroub5218772010-05-21 09:56:06 +00005916 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005917 PyModule_AddIntConstant(m, "OP_ALL",
5918 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005919 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5920 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5921 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005922#if HAVE_TLSv1_2
5923 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5924 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5925#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005926#ifdef SSL_OP_NO_TLSv1_3
5927 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5928#else
5929 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5930#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005931 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5932 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005933 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005934 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005935#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005936 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005937#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005938#ifdef SSL_OP_NO_COMPRESSION
5939 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5940 SSL_OP_NO_COMPRESSION);
5941#endif
Miss Islington (bot)2614ed42018-02-27 00:17:49 -08005942#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5943 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5944 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5945#endif
Miss Islington (bot)e2db6ad2018-05-16 07:26:19 -07005946#ifdef SSL_OP_NO_RENEGOTIATION
5947 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5948 SSL_OP_NO_RENEGOTIATION);
5949#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005950
Christian Heimes61d478c2018-01-27 15:51:38 +01005951#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5952 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5953 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5954#endif
5955#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5956 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5957 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5958#endif
5959#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5960 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5961 X509_CHECK_FLAG_NO_WILDCARDS);
5962#endif
5963#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5964 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5965 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5966#endif
5967#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5968 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5969 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5970#endif
5971#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5972 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5973 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5974#endif
5975
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005976 /* protocol versions */
5977 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5978 PY_PROTO_MINIMUM_SUPPORTED);
5979 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5980 PY_PROTO_MAXIMUM_SUPPORTED);
5981 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5982 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5983 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5984 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5985 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005986
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005987#define addbool(m, v, b) \
5988 Py_INCREF((b) ? Py_True : Py_False); \
5989 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5990
5991#if HAVE_SNI
5992 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005993#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005994 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005995#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005996
5997 addbool(m, "HAS_TLS_UNIQUE", 1);
5998
5999#ifndef OPENSSL_NO_ECDH
6000 addbool(m, "HAS_ECDH", 1);
6001#else
6002 addbool(m, "HAS_ECDH", 0);
6003#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006004
Miss Islington (bot)96177412018-02-25 04:18:43 -08006005#if HAVE_NPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006006 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006007#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006008 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006009#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006010
Miss Islington (bot)96177412018-02-25 04:18:43 -08006011#if HAVE_ALPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006012 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006013#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006014 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006015#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006016
6017#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6018 addbool(m, "HAS_SSLv2", 1);
6019#else
6020 addbool(m, "HAS_SSLv2", 0);
6021#endif
6022
6023#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6024 addbool(m, "HAS_SSLv3", 1);
6025#else
6026 addbool(m, "HAS_SSLv3", 0);
6027#endif
6028
6029#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6030 addbool(m, "HAS_TLSv1", 1);
6031#else
6032 addbool(m, "HAS_TLSv1", 0);
6033#endif
6034
6035#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6036 addbool(m, "HAS_TLSv1_1", 1);
6037#else
6038 addbool(m, "HAS_TLSv1_1", 0);
6039#endif
6040
6041#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6042 addbool(m, "HAS_TLSv1_2", 1);
6043#else
6044 addbool(m, "HAS_TLSv1_2", 0);
6045#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006046
Christian Heimescb5b68a2017-09-07 18:07:00 -07006047#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006048 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006049#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006050 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006051#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006052
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006053 /* Mappings for error codes */
6054 err_codes_to_names = PyDict_New();
6055 err_names_to_codes = PyDict_New();
6056 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6057 return NULL;
6058 errcode = error_codes;
6059 while (errcode->mnemonic != NULL) {
6060 PyObject *mnemo, *key;
6061 mnemo = PyUnicode_FromString(errcode->mnemonic);
6062 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6063 if (mnemo == NULL || key == NULL)
6064 return NULL;
6065 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6066 return NULL;
6067 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6068 return NULL;
6069 Py_DECREF(key);
6070 Py_DECREF(mnemo);
6071 errcode++;
6072 }
6073 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6074 return NULL;
6075 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6076 return NULL;
6077
6078 lib_codes_to_names = PyDict_New();
6079 if (lib_codes_to_names == NULL)
6080 return NULL;
6081 libcode = library_codes;
6082 while (libcode->library != NULL) {
6083 PyObject *mnemo, *key;
6084 key = PyLong_FromLong(libcode->code);
6085 mnemo = PyUnicode_FromString(libcode->library);
6086 if (key == NULL || mnemo == NULL)
6087 return NULL;
6088 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6089 return NULL;
6090 Py_DECREF(key);
6091 Py_DECREF(mnemo);
6092 libcode++;
6093 }
6094 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6095 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006096
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006097 /* OpenSSL version */
6098 /* SSLeay() gives us the version of the library linked against,
6099 which could be different from the headers version.
6100 */
6101 libver = SSLeay();
6102 r = PyLong_FromUnsignedLong(libver);
6103 if (r == NULL)
6104 return NULL;
6105 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6106 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006107 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006108 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6109 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6110 return NULL;
6111 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6112 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6113 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006114
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006115 libver = OPENSSL_VERSION_NUMBER;
6116 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6117 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6118 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6119 return NULL;
6120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006121 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006122}