blob: 310b38bf11f4578e23cfdf3d5c27cca6c39c5650 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Miss Islington (bot)e2c0aea2018-09-17 05:18:23 -070066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010078/* SSL error object */
79static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070080static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010081static PyObject *PySSLZeroReturnErrorObject;
82static PyObject *PySSLWantReadErrorObject;
83static PyObject *PySSLWantWriteErrorObject;
84static PyObject *PySSLSyscallErrorObject;
85static PyObject *PySSLEOFErrorObject;
86
87/* Error mappings */
88static PyObject *err_codes_to_names;
89static PyObject *err_names_to_codes;
90static PyObject *lib_codes_to_names;
91
92struct py_ssl_error_code {
93 const char *mnemonic;
94 int library, reason;
95};
96struct py_ssl_library_code {
97 const char *library;
98 int code;
99};
100
Steve Dower68d663c2017-07-17 11:15:48 +0200101#if defined(MS_WINDOWS) && defined(Py_DEBUG)
102/* Debug builds on Windows rely on getting errno directly from OpenSSL.
103 * However, because it uses a different CRT, we need to transfer the
104 * value of errno from OpenSSL into our debug CRT.
105 *
106 * Don't be fooled - this is horribly ugly code. The only reasonable
107 * alternative is to do both debug and release builds of OpenSSL, which
108 * requires much uglier code to transform their automatically generated
109 * makefile. This is the lesser of all the evils.
110 */
111
112static void _PySSLFixErrno(void) {
113 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
114 if (!ucrtbase) {
115 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
116 * have a catastrophic failure, but this function is not the
117 * place to raise it. */
118 return;
119 }
120
121 typedef int *(__stdcall *errno_func)(void);
122 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
123 if (ssl_errno) {
124 errno = *ssl_errno();
125 *ssl_errno() = 0;
126 } else {
127 errno = ENOTRECOVERABLE;
128 }
129}
130
131#undef _PySSL_FIX_ERRNO
132#define _PySSL_FIX_ERRNO _PySSLFixErrno()
133#endif
134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135/* Include generated data (error codes) */
136#include "_ssl_data.h"
137
Christian Heimes598894f2016-09-05 23:19:05 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
139# define OPENSSL_VERSION_1_1 1
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700140# define PY_OPENSSL_1_1_API 1
141#endif
142
143/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
144#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
145# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200146#endif
147
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
149 http://www.openssl.org/news/changelog.html
150 */
151#if OPENSSL_VERSION_NUMBER >= 0x10001000L
152# define HAVE_TLSv1_2 1
153#else
154# define HAVE_TLSv1_2 0
155#endif
156
Christian Heimes470fba12013-11-28 15:12:15 +0100157/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100158 * This includes the SSL_set_SSL_CTX() function.
159 */
160#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
161# define HAVE_SNI 1
162#else
163# define HAVE_SNI 0
164#endif
165
Benjamin Petersond3308222015-09-27 00:09:02 -0700166#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Miss Islington (bot)96177412018-02-25 04:18:43 -0800167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800172/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
173 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
174 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
175 * OpenSSL 1.0.1+ and LibreSSL.
Miss Islington (bot)96177412018-02-25 04:18:43 -0800176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Miss Islington (bot)96177412018-02-25 04:18:43 -0800179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800182#elif defined(TLSEXT_TYPE_next_proto_neg)
Miss Islington (bot)96177412018-02-25 04:18:43 -0800183# define HAVE_NPN 1
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800184#else
Miss Islington (bot)96177412018-02-25 04:18:43 -0800185# define HAVE_NPN 0
186#endif
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800187
Victor Stinner524714e2016-07-22 17:43:59 +0200188#ifndef INVALID_SOCKET /* MS defines this */
189#define INVALID_SOCKET (-1)
190#endif
191
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700192/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
193#ifndef OPENSSL_VERSION_1_1
194#define HAVE_OPENSSL_CRYPTO_LOCK
195#endif
196
197#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200198#define OPENSSL_NO_SSL2
199#endif
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700200
201#ifndef PY_OPENSSL_1_1_API
202/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200203
204#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200205#define TLS_client_method SSLv23_client_method
206#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
209{
210 return ne->set;
211}
212
213#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200214/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200215static int COMP_get_type(const COMP_METHOD *meth)
216{
217 return meth->type;
218}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200219/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200220#endif
221
222static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
223{
224 return ctx->default_passwd_callback;
225}
226
227static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
228{
229 return ctx->default_passwd_callback_userdata;
230}
231
232static int X509_OBJECT_get_type(X509_OBJECT *x)
233{
234 return x->type;
235}
236
237static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
238{
239 return x->data.x509;
240}
241
242static int BIO_up_ref(BIO *b)
243{
244 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
245 return 1;
246}
247
248static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
249 return store->objs;
250}
251
Christian Heimes99a65702016-09-10 23:44:53 +0200252static int
253SSL_SESSION_has_ticket(const SSL_SESSION *s)
254{
255 return (s->tlsext_ticklen > 0) ? 1 : 0;
256}
257
258static unsigned long
259SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
260{
261 return s->tlsext_tick_lifetime_hint;
262}
263
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700264#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200265
Christian Heimes892d66e2018-01-29 14:10:18 +0100266/* Default cipher suites */
267#ifndef PY_SSL_DEFAULT_CIPHERS
268#define PY_SSL_DEFAULT_CIPHERS 1
269#endif
270
271#if PY_SSL_DEFAULT_CIPHERS == 0
272 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
273 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
274 #endif
275#elif PY_SSL_DEFAULT_CIPHERS == 1
Miss Islington (bot)b3c4a052018-10-05 07:35:18 -0700276/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100277 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
278 * !aNULL:!eNULL: really no NULL ciphers
279 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
280 * !aDSS: no authentication with discrete logarithm DSA algorithm
281 * !SRP:!PSK: no secure remote password or pre-shared key authentication
282 */
283 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
284#elif PY_SSL_DEFAULT_CIPHERS == 2
285/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
286 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
287#else
288 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
289#endif
290
Christian Heimes598894f2016-09-05 23:19:05 +0200291
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000292enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 /* these mirror ssl.h */
294 PY_SSL_ERROR_NONE,
295 PY_SSL_ERROR_SSL,
296 PY_SSL_ERROR_WANT_READ,
297 PY_SSL_ERROR_WANT_WRITE,
298 PY_SSL_ERROR_WANT_X509_LOOKUP,
299 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
300 PY_SSL_ERROR_ZERO_RETURN,
301 PY_SSL_ERROR_WANT_CONNECT,
302 /* start of non ssl.h errorcodes */
303 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
304 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
305 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000306};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000307
Thomas Woutersed03b412007-08-28 21:37:11 +0000308enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 PY_SSL_CLIENT,
310 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000311};
312
313enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 PY_SSL_CERT_NONE,
315 PY_SSL_CERT_OPTIONAL,
316 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000317};
318
319enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200321 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200322 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100323#if HAVE_TLSv1_2
324 PY_SSL_VERSION_TLS1,
325 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200328 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000329#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS_CLIENT=0x10,
331 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100332};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200333
Miss Islington (bot)4c842b02018-02-27 03:41:04 -0800334enum py_proto_version {
335 PY_PROTO_MINIMUM_SUPPORTED = -2,
336 PY_PROTO_SSLv3 = SSL3_VERSION,
337 PY_PROTO_TLSv1 = TLS1_VERSION,
338 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
339 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
340#ifdef TLS1_3_VERSION
341 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
342#else
343 PY_PROTO_TLSv1_3 = 0x304,
344#endif
345 PY_PROTO_MAXIMUM_SUPPORTED = -1,
346
347/* OpenSSL has no dedicated API to set the minimum version to the maximum
348 * available version, and the other way around. We have to figure out the
349 * minimum and maximum available version on our own and hope for the best.
350 */
351#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
352 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
353#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
354 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
355#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
357#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
359#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
361#else
362 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
363#endif
364
365#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
366 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
367#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
368 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
369#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
371#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
373#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
375#else
376 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
377#endif
378};
379
380
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000381/* serves as a flag to see whether we've initialized the SSL thread support. */
382/* 0 means no, greater than 0 means yes */
383
384static unsigned int _ssl_locks_count = 0;
385
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386/* SSL socket object */
387
388#define X509_NAME_MAXLEN 256
389
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000390/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
391 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
392 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
393#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000394# define HAVE_SSL_CTX_CLEAR_OPTIONS
395#else
396# undef HAVE_SSL_CTX_CLEAR_OPTIONS
397#endif
398
Antoine Pitroud6494802011-07-21 01:11:30 +0200399/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
400 * older SSL, but let's be safe */
401#define PySSL_CB_MAXLEN 128
402
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100403
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000406 SSL_CTX *ctx;
Miss Islington (bot)96177412018-02-25 04:18:43 -0800407#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500408 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100409 int npn_protocols_len;
410#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -0800411#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300413 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500414#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100415#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800416 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100417#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100418 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100419 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
420 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
421 */
422 unsigned int hostflags;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800423 int protocol;
Christian Heimes2756ef32018-09-23 09:22:52 +0200424#ifdef TLS1_3_VERSION
425 int post_handshake_auth;
426#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000427} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000428
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429typedef struct {
Miss Islington (bot)12296642018-09-17 12:12:13 -0700430 int ssl; /* last seen error from SSL */
431 int c; /* last seen error from libc */
432#ifdef MS_WINDOWS
433 int ws; /* last seen error from winsock */
434#endif
435} _PySSLError;
436
437typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438 PyObject_HEAD
439 PyObject *Socket; /* weakref to socket on which we're layered */
440 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100441 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200442 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200443 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200444 PyObject *owner; /* Python level "owner" passed to servername callback */
445 PyObject *server_hostname;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700446 _PySSLError err; /* last seen error from various sources */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200449typedef struct {
450 PyObject_HEAD
451 BIO *bio;
452 int eof_written;
453} PySSLMemoryBIO;
454
Christian Heimes99a65702016-09-10 23:44:53 +0200455typedef struct {
456 PyObject_HEAD
457 SSL_SESSION *session;
458 PySSLContext *ctx;
459} PySSLSession;
460
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461static PyTypeObject PySSLContext_Type;
462static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200463static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200464static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000465
Miss Islington (bot)12296642018-09-17 12:12:13 -0700466static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
467{
468 _PySSLError err = { 0 };
469 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700470#ifdef MS_WINDOWS
Miss Islington (bot)12296642018-09-17 12:12:13 -0700471 err.ws = WSAGetLastError();
472 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700473#endif
Miss Islington (bot)12296642018-09-17 12:12:13 -0700474 err.c = errno;
475 err.ssl = SSL_get_error(ssl, retcode);
476 }
477 return err;
478}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300480/*[clinic input]
481module _ssl
482class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
483class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
484class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200485class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300486[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200487/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300488
489#include "clinic/_ssl.c.h"
490
Victor Stinner14690702015-04-06 22:46:13 +0200491static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800493static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
494static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200496#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200497#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000498
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000499typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 SOCKET_IS_NONBLOCKING,
501 SOCKET_IS_BLOCKING,
502 SOCKET_HAS_TIMED_OUT,
503 SOCKET_HAS_BEEN_CLOSED,
504 SOCKET_TOO_LARGE_FOR_SELECT,
505 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000506} timeout_state;
507
Thomas Woutersed03b412007-08-28 21:37:11 +0000508/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000509#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200510#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000511
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512/* Get the socket from a PySSLSocket, if it has one */
513#define GET_SOCKET(obj) ((obj)->Socket ? \
514 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200515
Victor Stinner14690702015-04-06 22:46:13 +0200516/* If sock is NULL, use a timeout of 0 second */
517#define GET_SOCKET_TIMEOUT(sock) \
518 ((sock != NULL) ? (sock)->sock_timeout : 0)
519
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520/*
521 * SSL errors.
522 */
523
524PyDoc_STRVAR(SSLError_doc,
525"An error occurred in the SSL implementation.");
526
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700527PyDoc_STRVAR(SSLCertVerificationError_doc,
528"A certificate could not be verified.");
529
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200530PyDoc_STRVAR(SSLZeroReturnError_doc,
531"SSL/TLS session closed cleanly.");
532
533PyDoc_STRVAR(SSLWantReadError_doc,
534"Non-blocking SSL socket needs to read more data\n"
535"before the requested operation can be completed.");
536
537PyDoc_STRVAR(SSLWantWriteError_doc,
538"Non-blocking SSL socket needs to write more data\n"
539"before the requested operation can be completed.");
540
541PyDoc_STRVAR(SSLSyscallError_doc,
542"System error when attempting SSL operation.");
543
544PyDoc_STRVAR(SSLEOFError_doc,
545"SSL/TLS connection terminated abruptly.");
546
547static PyObject *
548SSLError_str(PyOSErrorObject *self)
549{
550 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
551 Py_INCREF(self->strerror);
552 return self->strerror;
553 }
554 else
555 return PyObject_Str(self->args);
556}
557
558static PyType_Slot sslerror_type_slots[] = {
559 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
560 {Py_tp_doc, SSLError_doc},
561 {Py_tp_str, SSLError_str},
562 {0, 0},
563};
564
565static PyType_Spec sslerror_type_spec = {
566 "ssl.SSLError",
567 sizeof(PyOSErrorObject),
568 0,
569 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
570 sslerror_type_slots
571};
572
573static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700574fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
575 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200576{
577 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700578 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 PyObject *init_value, *msg, *key;
580 _Py_IDENTIFIER(reason);
581 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700582 _Py_IDENTIFIER(verify_message);
583 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200584
585 if (errcode != 0) {
586 int lib, reason;
587
588 lib = ERR_GET_LIB(errcode);
589 reason = ERR_GET_REASON(errcode);
590 key = Py_BuildValue("ii", lib, reason);
591 if (key == NULL)
592 goto fail;
593 reason_obj = PyDict_GetItem(err_codes_to_names, key);
594 Py_DECREF(key);
595 if (reason_obj == NULL) {
596 /* XXX if reason < 100, it might reflect a library number (!!) */
597 PyErr_Clear();
598 }
599 key = PyLong_FromLong(lib);
600 if (key == NULL)
601 goto fail;
602 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
603 Py_DECREF(key);
604 if (lib_obj == NULL) {
605 PyErr_Clear();
606 }
607 if (errstr == NULL)
608 errstr = ERR_reason_error_string(errcode);
609 }
610 if (errstr == NULL)
611 errstr = "unknown error";
612
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700613 /* verify code for cert validation error */
614 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
615 const char *verify_str = NULL;
616 long verify_code;
617
618 verify_code = SSL_get_verify_result(sslsock->ssl);
619 verify_code_obj = PyLong_FromLong(verify_code);
620 if (verify_code_obj == NULL) {
621 goto fail;
622 }
623
624 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700625#ifdef X509_V_ERR_HOSTNAME_MISMATCH
626 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700627 case X509_V_ERR_HOSTNAME_MISMATCH:
628 verify_obj = PyUnicode_FromFormat(
629 "Hostname mismatch, certificate is not valid for '%S'.",
630 sslsock->server_hostname
631 );
632 break;
Christian Heimes09153602017-09-08 14:47:58 -0700633#endif
634#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 case X509_V_ERR_IP_ADDRESS_MISMATCH:
636 verify_obj = PyUnicode_FromFormat(
637 "IP address mismatch, certificate is not valid for '%S'.",
638 sslsock->server_hostname
639 );
640 break;
Christian Heimes09153602017-09-08 14:47:58 -0700641#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700642 default:
643 verify_str = X509_verify_cert_error_string(verify_code);
644 if (verify_str != NULL) {
645 verify_obj = PyUnicode_FromString(verify_str);
646 } else {
647 verify_obj = Py_None;
648 Py_INCREF(verify_obj);
649 }
650 break;
651 }
652 if (verify_obj == NULL) {
653 goto fail;
654 }
655 }
656
657 if (verify_obj && reason_obj && lib_obj)
658 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
659 lib_obj, reason_obj, errstr, verify_obj,
660 lineno);
661 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200662 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
663 lib_obj, reason_obj, errstr, lineno);
664 else if (lib_obj)
665 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
666 lib_obj, errstr, lineno);
667 else
668 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200669 if (msg == NULL)
670 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100671
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200672 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100673 if (init_value == NULL)
674 goto fail;
675
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200676 err_value = PyObject_CallObject(type, init_value);
677 Py_DECREF(init_value);
678 if (err_value == NULL)
679 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100680
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200681 if (reason_obj == NULL)
682 reason_obj = Py_None;
683 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
684 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700685
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 if (lib_obj == NULL)
687 lib_obj = Py_None;
688 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
689 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700690
691 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
692 /* Only set verify code / message for SSLCertVerificationError */
693 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
694 verify_code_obj))
695 goto fail;
696 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
697 goto fail;
698 }
699
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200700 PyErr_SetObject(type, err_value);
701fail:
702 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700703 Py_XDECREF(verify_code_obj);
704 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200705}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000706
707static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700708PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000709{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200710 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711 char *errstr = NULL;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700712 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200714 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000715
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200717 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000718
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700719 if (sslsock->ssl != NULL) {
Miss Islington (bot)12296642018-09-17 12:12:13 -0700720 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000721
Miss Islington (bot)12296642018-09-17 12:12:13 -0700722 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200724 errstr = "TLS/SSL connection has been closed (EOF)";
725 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 p = PY_SSL_ERROR_ZERO_RETURN;
727 break;
728 case SSL_ERROR_WANT_READ:
729 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200730 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 p = PY_SSL_ERROR_WANT_READ;
732 break;
733 case SSL_ERROR_WANT_WRITE:
734 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200735 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 errstr = "The operation did not complete (write)";
737 break;
738 case SSL_ERROR_WANT_X509_LOOKUP:
739 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000740 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 break;
742 case SSL_ERROR_WANT_CONNECT:
743 p = PY_SSL_ERROR_WANT_CONNECT;
744 errstr = "The operation did not complete (connect)";
745 break;
746 case SSL_ERROR_SYSCALL:
747 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700749 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000751 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200752 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000753 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200754 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000755 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000756 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700757#ifdef MS_WINDOWS
Miss Islington (bot)12296642018-09-17 12:12:13 -0700758 if (err.ws) {
759 return PyErr_SetFromWindowsErr(err.ws);
760 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700761#endif
Miss Islington (bot)12296642018-09-17 12:12:13 -0700762 if (err.c) {
763 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700764 return PyErr_SetFromErrno(PyExc_OSError);
765 }
766 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200767 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000768 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200769 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000771 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200772 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000773 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 }
775 } else {
776 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 }
778 break;
779 }
780 case SSL_ERROR_SSL:
781 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700783 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200784 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000785 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700786 }
787 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
788 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
789 type = PySSLCertVerificationErrorObject;
790 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 break;
792 }
793 default:
794 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
795 errstr = "Invalid error code";
796 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700798 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000799 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000801}
802
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000803static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200804_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200806 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200808 else
809 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700810 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000811 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000813}
814
Christian Heimes61d478c2018-01-27 15:51:38 +0100815/*
816 * SSL objects
817 */
818
819static int
820_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
821{
822 int retval = -1;
823 ASN1_OCTET_STRING *ip;
824 PyObject *hostname;
825 size_t len;
826
827 assert(server_hostname);
828
829 /* Disable OpenSSL's special mode with leading dot in hostname:
830 * When name starts with a dot (e.g ".example.com"), it will be
831 * matched by a certificate valid for any sub-domain of name.
832 */
833 len = strlen(server_hostname);
834 if (len == 0 || *server_hostname == '.') {
835 PyErr_SetString(
836 PyExc_ValueError,
837 "server_hostname cannot be an empty string or start with a "
838 "leading dot.");
839 return retval;
840 }
841
842 /* inet_pton is not available on all platforms. */
843 ip = a2i_IPADDRESS(server_hostname);
844 if (ip == NULL) {
845 ERR_clear_error();
846 }
847
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800848 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100849 if (hostname == NULL) {
850 goto error;
851 }
852 self->server_hostname = hostname;
853
854 /* Only send SNI extension for non-IP hostnames */
855 if (ip == NULL) {
856 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
857 _setSSLError(NULL, 0, __FILE__, __LINE__);
858 }
859 }
860 if (self->ctx->check_hostname) {
861 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
862 if (ip == NULL) {
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -0700863 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
864 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100865 _setSSLError(NULL, 0, __FILE__, __LINE__);
866 goto error;
867 }
868 } else {
869 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
870 ASN1_STRING_length(ip))) {
871 _setSSLError(NULL, 0, __FILE__, __LINE__);
872 goto error;
873 }
874 }
875 }
876 retval = 0;
877 error:
878 if (ip != NULL) {
879 ASN1_OCTET_STRING_free(ip);
880 }
881 return retval;
882}
883
Antoine Pitrou152efa22010-05-16 18:19:27 +0000884static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100885newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000886 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200887 char *server_hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800888 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200889 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000890{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000891 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100892 SSL_CTX *ctx = sslctx->ctx;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700893 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000894
Antoine Pitrou152efa22010-05-16 18:19:27 +0000895 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 if (self == NULL)
897 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100901 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700902 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200903 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700905 self->server_hostname = NULL;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700906 self->err = err;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 /* Make sure the SSL error state is initialized */
909 (void) ERR_get_state();
910 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000911
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000912 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000913 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 PySSL_END_ALLOW_THREADS
Zackery Spytz602d3072018-12-07 05:17:43 -0700915 if (self->ssl == NULL) {
916 Py_DECREF(self);
917 _setSSLError(NULL, 0, __FILE__, __LINE__);
918 return NULL;
919 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200920 SSL_set_app_data(self->ssl, self);
921 if (sock) {
922 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
923 } else {
924 /* BIOs are reference counted and SSL_set_bio borrows our reference.
925 * To prevent a double free in memory_bio_dealloc() we need to take an
926 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200927 BIO_up_ref(inbio->bio);
928 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200929 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
930 }
Miss Islington (bot)67d19682018-05-14 10:45:45 -0700931 SSL_set_mode(self->ssl,
932 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000933
Christian Heimes61d478c2018-01-27 15:51:38 +0100934 if (server_hostname != NULL) {
935 if (_ssl_configure_hostname(self, server_hostname) < 0) {
936 Py_DECREF(self);
937 return NULL;
938 }
939 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 /* If the socket is in non-blocking mode or timeout mode, set the BIO
941 * to non-blocking mode (blocking is the default)
942 */
Victor Stinnere2452312015-03-28 03:00:46 +0100943 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
945 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
946 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 PySSL_BEGIN_ALLOW_THREADS
949 if (socket_type == PY_SSL_CLIENT)
950 SSL_set_connect_state(self->ssl);
951 else
952 SSL_set_accept_state(self->ssl);
953 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000954
Antoine Pitroud6494802011-07-21 01:11:30 +0200955 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200956 if (sock != NULL) {
957 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
958 if (self->Socket == NULL) {
959 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200960 return NULL;
961 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100962 }
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800963 if (owner && owner != Py_None) {
964 if (PySSL_set_owner(self, owner, NULL) == -1) {
965 Py_DECREF(self);
966 return NULL;
967 }
968 }
969 if (session && session != Py_None) {
970 if (PySSL_set_session(self, session, NULL) == -1) {
971 Py_DECREF(self);
972 return NULL;
973 }
974 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000975 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000976}
977
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000978/* SSL object methods */
979
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300980/*[clinic input]
981_ssl._SSLSocket.do_handshake
982[clinic start generated code]*/
983
984static PyObject *
985_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
986/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000987{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 int ret;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700989 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200991 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200992 _PyTime_t timeout, deadline = 0;
993 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000994
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200995 if (sock) {
996 if (((PyObject*)sock) == Py_None) {
997 _setSSLError("Underlying socket connection gone",
998 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
999 return NULL;
1000 }
1001 Py_INCREF(sock);
1002
1003 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001004 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001005 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1006 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001008
Victor Stinner14690702015-04-06 22:46:13 +02001009 timeout = GET_SOCKET_TIMEOUT(sock);
1010 has_timeout = (timeout > 0);
1011 if (has_timeout)
1012 deadline = _PyTime_GetMonotonicClock() + timeout;
1013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 /* Actually negotiate SSL connection */
1015 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001017 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 ret = SSL_do_handshake(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001019 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07001021 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001022
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001023 if (PyErr_CheckSignals())
1024 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001025
Victor Stinner14690702015-04-06 22:46:13 +02001026 if (has_timeout)
1027 timeout = deadline - _PyTime_GetMonotonicClock();
1028
Miss Islington (bot)12296642018-09-17 12:12:13 -07001029 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001030 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001031 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001032 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 } else {
1034 sockstate = SOCKET_OPERATION_OK;
1035 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001036
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001038 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001039 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001040 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1042 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001043 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001044 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1046 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001047 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001048 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001049 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1050 break;
1051 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07001052 } while (err.ssl == SSL_ERROR_WANT_READ ||
1053 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001054 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 if (ret < 1)
1056 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001057
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001058 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001059
1060error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001061 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001062 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001063}
1064
Thomas Woutersed03b412007-08-28 21:37:11 +00001065static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001066_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1067{
1068 char buf[X509_NAME_MAXLEN];
1069 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001071 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001072
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001073 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 if (buflen < 0) {
1075 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001076 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001078 /* initial buffer is too small for oid + terminating null byte */
1079 if (buflen > X509_NAME_MAXLEN - 1) {
1080 /* make OBJ_obj2txt() calculate the required buflen */
1081 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1082 /* allocate len + 1 for terminating NULL byte */
1083 namebuf = PyMem_Malloc(buflen + 1);
1084 if (namebuf == NULL) {
1085 PyErr_NoMemory();
1086 return NULL;
1087 }
1088 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1089 if (buflen < 0) {
1090 _setSSLError(NULL, 0, __FILE__, __LINE__);
1091 goto done;
1092 }
1093 }
1094 if (!buflen && no_name) {
1095 Py_INCREF(Py_None);
1096 name_obj = Py_None;
1097 }
1098 else {
1099 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1100 }
1101
1102 done:
1103 if (buf != namebuf) {
1104 PyMem_Free(namebuf);
1105 }
1106 return name_obj;
1107}
1108
1109static PyObject *
1110_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1111{
1112 Py_ssize_t buflen;
1113 unsigned char *valuebuf = NULL;
1114 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001115
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1117 if (buflen < 0) {
1118 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001119 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001121 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001124}
1125
1126static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001127_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001128{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1130 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1131 PyObject *rdnt;
1132 PyObject *attr = NULL; /* tuple to hold an attribute */
1133 int entry_count = X509_NAME_entry_count(xname);
1134 X509_NAME_ENTRY *entry;
1135 ASN1_OBJECT *name;
1136 ASN1_STRING *value;
1137 int index_counter;
1138 int rdn_level = -1;
1139 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 dn = PyList_New(0);
1142 if (dn == NULL)
1143 return NULL;
1144 /* now create another tuple to hold the top-level RDN */
1145 rdn = PyList_New(0);
1146 if (rdn == NULL)
1147 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 for (index_counter = 0;
1150 index_counter < entry_count;
1151 index_counter++)
1152 {
1153 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 /* check to see if we've gotten to a new RDN */
1156 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001157 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 /* yes, new RDN */
1159 /* add old RDN to DN */
1160 rdnt = PyList_AsTuple(rdn);
1161 Py_DECREF(rdn);
1162 if (rdnt == NULL)
1163 goto fail0;
1164 retcode = PyList_Append(dn, rdnt);
1165 Py_DECREF(rdnt);
1166 if (retcode < 0)
1167 goto fail0;
1168 /* create new RDN */
1169 rdn = PyList_New(0);
1170 if (rdn == NULL)
1171 goto fail0;
1172 }
1173 }
Christian Heimes598894f2016-09-05 23:19:05 +02001174 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 /* now add this attribute to the current RDN */
1177 name = X509_NAME_ENTRY_get_object(entry);
1178 value = X509_NAME_ENTRY_get_data(entry);
1179 attr = _create_tuple_for_attribute(name, value);
1180 /*
1181 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1182 entry->set,
1183 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1184 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1185 */
1186 if (attr == NULL)
1187 goto fail1;
1188 retcode = PyList_Append(rdn, attr);
1189 Py_DECREF(attr);
1190 if (retcode < 0)
1191 goto fail1;
1192 }
1193 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001194 if (rdn != NULL) {
1195 if (PyList_GET_SIZE(rdn) > 0) {
1196 rdnt = PyList_AsTuple(rdn);
1197 Py_DECREF(rdn);
1198 if (rdnt == NULL)
1199 goto fail0;
1200 retcode = PyList_Append(dn, rdnt);
1201 Py_DECREF(rdnt);
1202 if (retcode < 0)
1203 goto fail0;
1204 }
1205 else {
1206 Py_DECREF(rdn);
1207 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 /* convert list to tuple */
1211 rdnt = PyList_AsTuple(dn);
1212 Py_DECREF(dn);
1213 if (rdnt == NULL)
1214 return NULL;
1215 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216
1217 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001219
1220 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 Py_XDECREF(dn);
1222 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001223}
1224
1225static PyObject *
1226_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 /* this code follows the procedure outlined in
1229 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1230 function to extract the STACK_OF(GENERAL_NAME),
1231 then iterates through the stack to add the
1232 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001233
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001234 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001236 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 GENERAL_NAMES *names = NULL;
1238 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 BIO *biobuf = NULL;
1240 char buf[2048];
1241 char *vptr;
1242 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 if (certificate == NULL)
1245 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 /* get a memory buffer */
1248 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz602d3072018-12-07 05:17:43 -07001249 if (biobuf == NULL) {
1250 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1251 return NULL;
1252 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001254 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1255 certificate, NID_subject_alt_name, NULL, NULL);
1256 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 if (peer_alt_names == Py_None) {
1258 peer_alt_names = PyList_New(0);
1259 if (peer_alt_names == NULL)
1260 goto fail;
1261 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001265 int gntype;
1266 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001269 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001270 switch (gntype) {
1271 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 /* we special-case DirName as a tuple of
1273 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 t = PyTuple_New(2);
1276 if (t == NULL) {
1277 goto fail;
1278 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 v = PyUnicode_FromString("DirName");
1281 if (v == NULL) {
1282 Py_DECREF(t);
1283 goto fail;
1284 }
1285 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 v = _create_tuple_for_X509_NAME (name->d.dirn);
1288 if (v == NULL) {
1289 Py_DECREF(t);
1290 goto fail;
1291 }
1292 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001293 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001294
Christian Heimes824f7f32013-08-17 00:54:47 +02001295 case GEN_EMAIL:
1296 case GEN_DNS:
1297 case GEN_URI:
1298 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1299 correctly, CVE-2013-4238 */
1300 t = PyTuple_New(2);
1301 if (t == NULL)
1302 goto fail;
1303 switch (gntype) {
1304 case GEN_EMAIL:
1305 v = PyUnicode_FromString("email");
1306 as = name->d.rfc822Name;
1307 break;
1308 case GEN_DNS:
1309 v = PyUnicode_FromString("DNS");
1310 as = name->d.dNSName;
1311 break;
1312 case GEN_URI:
1313 v = PyUnicode_FromString("URI");
1314 as = name->d.uniformResourceIdentifier;
1315 break;
1316 }
1317 if (v == NULL) {
1318 Py_DECREF(t);
1319 goto fail;
1320 }
1321 PyTuple_SET_ITEM(t, 0, v);
1322 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1323 ASN1_STRING_length(as));
1324 if (v == NULL) {
1325 Py_DECREF(t);
1326 goto fail;
1327 }
1328 PyTuple_SET_ITEM(t, 1, v);
1329 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Christian Heimes1c03abd2016-09-06 23:25:35 +02001331 case GEN_RID:
1332 t = PyTuple_New(2);
1333 if (t == NULL)
1334 goto fail;
1335
1336 v = PyUnicode_FromString("Registered ID");
1337 if (v == NULL) {
1338 Py_DECREF(t);
1339 goto fail;
1340 }
1341 PyTuple_SET_ITEM(t, 0, v);
1342
1343 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1344 if (len < 0) {
1345 Py_DECREF(t);
1346 _setSSLError(NULL, 0, __FILE__, __LINE__);
1347 goto fail;
1348 } else if (len >= (int)sizeof(buf)) {
1349 v = PyUnicode_FromString("<INVALID>");
1350 } else {
1351 v = PyUnicode_FromStringAndSize(buf, len);
1352 }
1353 if (v == NULL) {
1354 Py_DECREF(t);
1355 goto fail;
1356 }
1357 PyTuple_SET_ITEM(t, 1, v);
1358 break;
1359
Christian Heimes824f7f32013-08-17 00:54:47 +02001360 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001362 switch (gntype) {
1363 /* check for new general name type */
1364 case GEN_OTHERNAME:
1365 case GEN_X400:
1366 case GEN_EDIPARTY:
1367 case GEN_IPADD:
1368 case GEN_RID:
1369 break;
1370 default:
1371 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1372 "Unknown general name type %d",
1373 gntype) == -1) {
1374 goto fail;
1375 }
1376 break;
1377 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 (void) BIO_reset(biobuf);
1379 GENERAL_NAME_print(biobuf, name);
1380 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1381 if (len < 0) {
1382 _setSSLError(NULL, 0, __FILE__, __LINE__);
1383 goto fail;
1384 }
1385 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001386 if (vptr == NULL) {
1387 PyErr_Format(PyExc_ValueError,
1388 "Invalid value %.200s",
1389 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001390 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001391 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001392 t = PyTuple_New(2);
1393 if (t == NULL)
1394 goto fail;
1395 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1396 if (v == NULL) {
1397 Py_DECREF(t);
1398 goto fail;
1399 }
1400 PyTuple_SET_ITEM(t, 0, v);
1401 v = PyUnicode_FromStringAndSize((vptr + 1),
1402 (len - (vptr - buf + 1)));
1403 if (v == NULL) {
1404 Py_DECREF(t);
1405 goto fail;
1406 }
1407 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001408 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 if (PyList_Append(peer_alt_names, t) < 0) {
1414 Py_DECREF(t);
1415 goto fail;
1416 }
1417 Py_DECREF(t);
1418 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001419 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 }
1421 BIO_free(biobuf);
1422 if (peer_alt_names != Py_None) {
1423 v = PyList_AsTuple(peer_alt_names);
1424 Py_DECREF(peer_alt_names);
1425 return v;
1426 } else {
1427 return peer_alt_names;
1428 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001429
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001430
1431 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001432 if (biobuf != NULL)
1433 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001434
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001435 if (peer_alt_names != Py_None) {
1436 Py_XDECREF(peer_alt_names);
1437 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001439 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001440}
1441
1442static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001443_get_aia_uri(X509 *certificate, int nid) {
1444 PyObject *lst = NULL, *ostr = NULL;
1445 int i, result;
1446 AUTHORITY_INFO_ACCESS *info;
1447
1448 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001449 if (info == NULL)
1450 return Py_None;
1451 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1452 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001453 return Py_None;
1454 }
1455
1456 if ((lst = PyList_New(0)) == NULL) {
1457 goto fail;
1458 }
1459
1460 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1461 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1462 ASN1_IA5STRING *uri;
1463
1464 if ((OBJ_obj2nid(ad->method) != nid) ||
1465 (ad->location->type != GEN_URI)) {
1466 continue;
1467 }
1468 uri = ad->location->d.uniformResourceIdentifier;
1469 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1470 uri->length);
1471 if (ostr == NULL) {
1472 goto fail;
1473 }
1474 result = PyList_Append(lst, ostr);
1475 Py_DECREF(ostr);
1476 if (result < 0) {
1477 goto fail;
1478 }
1479 }
1480 AUTHORITY_INFO_ACCESS_free(info);
1481
1482 /* convert to tuple or None */
1483 if (PyList_Size(lst) == 0) {
1484 Py_DECREF(lst);
1485 return Py_None;
1486 } else {
1487 PyObject *tup;
1488 tup = PyList_AsTuple(lst);
1489 Py_DECREF(lst);
1490 return tup;
1491 }
1492
1493 fail:
1494 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001495 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001496 return NULL;
1497}
1498
1499static PyObject *
1500_get_crl_dp(X509 *certificate) {
1501 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001502 int i, j;
1503 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504
Christian Heimes598894f2016-09-05 23:19:05 +02001505 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001506
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001507 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001508 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001509
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001510 lst = PyList_New(0);
1511 if (lst == NULL)
1512 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001513
1514 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1515 DIST_POINT *dp;
1516 STACK_OF(GENERAL_NAME) *gns;
1517
1518 dp = sk_DIST_POINT_value(dps, i);
1519 gns = dp->distpoint->name.fullname;
1520
1521 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1522 GENERAL_NAME *gn;
1523 ASN1_IA5STRING *uri;
1524 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001525 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001526
1527 gn = sk_GENERAL_NAME_value(gns, j);
1528 if (gn->type != GEN_URI) {
1529 continue;
1530 }
1531 uri = gn->d.uniformResourceIdentifier;
1532 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1533 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001534 if (ouri == NULL)
1535 goto done;
1536
1537 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001538 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001539 if (err < 0)
1540 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001541 }
1542 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001543
1544 /* Convert to tuple. */
1545 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1546
1547 done:
1548 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001549 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001550 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001551}
1552
1553static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001554_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 PyObject *retval = NULL;
1557 BIO *biobuf = NULL;
1558 PyObject *peer;
1559 PyObject *peer_alt_names = NULL;
1560 PyObject *issuer;
1561 PyObject *version;
1562 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001563 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 ASN1_INTEGER *serialNumber;
1565 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001566 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 ASN1_TIME *notBefore, *notAfter;
1568 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001569
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 retval = PyDict_New();
1571 if (retval == NULL)
1572 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 peer = _create_tuple_for_X509_NAME(
1575 X509_get_subject_name(certificate));
1576 if (peer == NULL)
1577 goto fail0;
1578 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1579 Py_DECREF(peer);
1580 goto fail0;
1581 }
1582 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001583
Antoine Pitroufb046912010-11-09 20:21:19 +00001584 issuer = _create_tuple_for_X509_NAME(
1585 X509_get_issuer_name(certificate));
1586 if (issuer == NULL)
1587 goto fail0;
1588 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001590 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001591 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001592 Py_DECREF(issuer);
1593
1594 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001595 if (version == NULL)
1596 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001597 if (PyDict_SetItemString(retval, "version", version) < 0) {
1598 Py_DECREF(version);
1599 goto fail0;
1600 }
1601 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001602
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001603 /* get a memory buffer */
1604 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz602d3072018-12-07 05:17:43 -07001605 if (biobuf == NULL) {
1606 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1607 goto fail0;
1608 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001609
Antoine Pitroufb046912010-11-09 20:21:19 +00001610 (void) BIO_reset(biobuf);
1611 serialNumber = X509_get_serialNumber(certificate);
1612 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1613 i2a_ASN1_INTEGER(biobuf, serialNumber);
1614 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1615 if (len < 0) {
1616 _setSSLError(NULL, 0, __FILE__, __LINE__);
1617 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001619 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1620 if (sn_obj == NULL)
1621 goto fail1;
1622 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1623 Py_DECREF(sn_obj);
1624 goto fail1;
1625 }
1626 Py_DECREF(sn_obj);
1627
1628 (void) BIO_reset(biobuf);
1629 notBefore = X509_get_notBefore(certificate);
1630 ASN1_TIME_print(biobuf, notBefore);
1631 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1632 if (len < 0) {
1633 _setSSLError(NULL, 0, __FILE__, __LINE__);
1634 goto fail1;
1635 }
1636 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1637 if (pnotBefore == NULL)
1638 goto fail1;
1639 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1640 Py_DECREF(pnotBefore);
1641 goto fail1;
1642 }
1643 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 (void) BIO_reset(biobuf);
1646 notAfter = X509_get_notAfter(certificate);
1647 ASN1_TIME_print(biobuf, notAfter);
1648 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1649 if (len < 0) {
1650 _setSSLError(NULL, 0, __FILE__, __LINE__);
1651 goto fail1;
1652 }
1653 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1654 if (pnotAfter == NULL)
1655 goto fail1;
1656 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1657 Py_DECREF(pnotAfter);
1658 goto fail1;
1659 }
1660 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001662 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 peer_alt_names = _get_peer_alt_names(certificate);
1665 if (peer_alt_names == NULL)
1666 goto fail1;
1667 else if (peer_alt_names != Py_None) {
1668 if (PyDict_SetItemString(retval, "subjectAltName",
1669 peer_alt_names) < 0) {
1670 Py_DECREF(peer_alt_names);
1671 goto fail1;
1672 }
1673 Py_DECREF(peer_alt_names);
1674 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001675
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001676 /* Authority Information Access: OCSP URIs */
1677 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1678 if (obj == NULL) {
1679 goto fail1;
1680 } else if (obj != Py_None) {
1681 result = PyDict_SetItemString(retval, "OCSP", obj);
1682 Py_DECREF(obj);
1683 if (result < 0) {
1684 goto fail1;
1685 }
1686 }
1687
1688 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1689 if (obj == NULL) {
1690 goto fail1;
1691 } else if (obj != Py_None) {
1692 result = PyDict_SetItemString(retval, "caIssuers", obj);
1693 Py_DECREF(obj);
1694 if (result < 0) {
1695 goto fail1;
1696 }
1697 }
1698
1699 /* CDP (CRL distribution points) */
1700 obj = _get_crl_dp(certificate);
1701 if (obj == NULL) {
1702 goto fail1;
1703 } else if (obj != Py_None) {
1704 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1705 Py_DECREF(obj);
1706 if (result < 0) {
1707 goto fail1;
1708 }
1709 }
1710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 BIO_free(biobuf);
1712 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001713
1714 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 if (biobuf != NULL)
1716 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001717 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001718 Py_XDECREF(retval);
1719 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001720}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001721
Christian Heimes9a5395a2013-06-17 15:44:12 +02001722static PyObject *
1723_certificate_to_der(X509 *certificate)
1724{
1725 unsigned char *bytes_buf = NULL;
1726 int len;
1727 PyObject *retval;
1728
1729 bytes_buf = NULL;
1730 len = i2d_X509(certificate, &bytes_buf);
1731 if (len < 0) {
1732 _setSSLError(NULL, 0, __FILE__, __LINE__);
1733 return NULL;
1734 }
1735 /* this is actually an immutable bytes sequence */
1736 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1737 OPENSSL_free(bytes_buf);
1738 return retval;
1739}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001741/*[clinic input]
1742_ssl._test_decode_cert
1743 path: object(converter="PyUnicode_FSConverter")
1744 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001746[clinic start generated code]*/
1747
1748static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001749_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1750/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001751{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 X509 *x=NULL;
1754 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001755
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001756 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1757 PyErr_SetString(PySSLErrorObject,
1758 "Can't malloc memory to read file");
1759 goto fail0;
1760 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001762 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 PyErr_SetString(PySSLErrorObject,
1764 "Can't open file");
1765 goto fail0;
1766 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1769 if (x == NULL) {
1770 PyErr_SetString(PySSLErrorObject,
1771 "Error decoding PEM-encoded file");
1772 goto fail0;
1773 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001774
Antoine Pitroufb046912010-11-09 20:21:19 +00001775 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001776 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
1778 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001779 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001780 if (cert != NULL) BIO_free(cert);
1781 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782}
1783
1784
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001785/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001786_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001787 der as binary_mode: bool = False
1788 /
1789
1790Returns the certificate for the peer.
1791
1792If no certificate was provided, returns None. If a certificate was
1793provided, but not validated, returns an empty dictionary. Otherwise
1794returns a dict containing information about the peer certificate.
1795
1796If the optional argument is True, returns a DER-encoded copy of the
1797peer certificate, or None if no certificate was provided. This will
1798return the certificate even if it wasn't validated.
1799[clinic start generated code]*/
1800
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001802_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1803/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001806 X509 *peer_cert;
1807 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001808
Christian Heimes66dc33b2017-05-23 16:02:02 -07001809 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001810 PyErr_SetString(PyExc_ValueError,
1811 "handshake not done yet");
1812 return NULL;
1813 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001814 peer_cert = SSL_get_peer_certificate(self->ssl);
1815 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001816 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001817
Antoine Pitrou721738f2012-08-15 23:20:39 +02001818 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001820 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001822 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001824 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001826 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001828 X509_free(peer_cert);
1829 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001830}
1831
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001832static PyObject *
1833cipher_to_tuple(const SSL_CIPHER *cipher)
1834{
1835 const char *cipher_name, *cipher_protocol;
1836 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 if (retval == NULL)
1838 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001839
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001840 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001842 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 PyTuple_SET_ITEM(retval, 0, Py_None);
1844 } else {
1845 v = PyUnicode_FromString(cipher_name);
1846 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001847 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 PyTuple_SET_ITEM(retval, 0, v);
1849 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001850
1851 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001853 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 PyTuple_SET_ITEM(retval, 1, Py_None);
1855 } else {
1856 v = PyUnicode_FromString(cipher_protocol);
1857 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001858 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 PyTuple_SET_ITEM(retval, 1, v);
1860 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001861
1862 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001863 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001864 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001866
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001868
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001869 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001870 Py_DECREF(retval);
1871 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001872}
1873
Christian Heimes25bfcd52016-09-06 00:04:45 +02001874#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1875static PyObject *
1876cipher_to_dict(const SSL_CIPHER *cipher)
1877{
1878 const char *cipher_name, *cipher_protocol;
1879
1880 unsigned long cipher_id;
1881 int alg_bits, strength_bits, len;
1882 char buf[512] = {0};
1883#if OPENSSL_VERSION_1_1
1884 int aead, nid;
1885 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1886#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001887
1888 /* can be NULL */
1889 cipher_name = SSL_CIPHER_get_name(cipher);
1890 cipher_protocol = SSL_CIPHER_get_version(cipher);
1891 cipher_id = SSL_CIPHER_get_id(cipher);
1892 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001893 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1894 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001895 if (len > 1 && buf[len-1] == '\n')
1896 buf[len-1] = '\0';
1897 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1898
1899#if OPENSSL_VERSION_1_1
1900 aead = SSL_CIPHER_is_aead(cipher);
1901 nid = SSL_CIPHER_get_cipher_nid(cipher);
1902 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1903 nid = SSL_CIPHER_get_digest_nid(cipher);
1904 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1905 nid = SSL_CIPHER_get_kx_nid(cipher);
1906 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1907 nid = SSL_CIPHER_get_auth_nid(cipher);
1908 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1909#endif
1910
Victor Stinner410b9882016-09-12 12:00:23 +02001911 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001912 "{sksssssssisi"
1913#if OPENSSL_VERSION_1_1
1914 "sOssssssss"
1915#endif
1916 "}",
1917 "id", cipher_id,
1918 "name", cipher_name,
1919 "protocol", cipher_protocol,
1920 "description", buf,
1921 "strength_bits", strength_bits,
1922 "alg_bits", alg_bits
1923#if OPENSSL_VERSION_1_1
1924 ,"aead", aead ? Py_True : Py_False,
1925 "symmetric", skcipher,
1926 "digest", digest,
1927 "kea", kx,
1928 "auth", auth
1929#endif
1930 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001931}
1932#endif
1933
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001934/*[clinic input]
1935_ssl._SSLSocket.shared_ciphers
1936[clinic start generated code]*/
1937
1938static PyObject *
1939_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1940/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001941{
1942 STACK_OF(SSL_CIPHER) *ciphers;
1943 int i;
1944 PyObject *res;
1945
Christian Heimes598894f2016-09-05 23:19:05 +02001946 ciphers = SSL_get_ciphers(self->ssl);
1947 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001948 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001949 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1950 if (!res)
1951 return NULL;
1952 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1953 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1954 if (!tup) {
1955 Py_DECREF(res);
1956 return NULL;
1957 }
1958 PyList_SET_ITEM(res, i, tup);
1959 }
1960 return res;
1961}
1962
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001963/*[clinic input]
1964_ssl._SSLSocket.cipher
1965[clinic start generated code]*/
1966
1967static PyObject *
1968_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1969/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001970{
1971 const SSL_CIPHER *current;
1972
1973 if (self->ssl == NULL)
1974 Py_RETURN_NONE;
1975 current = SSL_get_current_cipher(self->ssl);
1976 if (current == NULL)
1977 Py_RETURN_NONE;
1978 return cipher_to_tuple(current);
1979}
1980
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001981/*[clinic input]
1982_ssl._SSLSocket.version
1983[clinic start generated code]*/
1984
1985static PyObject *
1986_ssl__SSLSocket_version_impl(PySSLSocket *self)
1987/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001988{
1989 const char *version;
1990
1991 if (self->ssl == NULL)
1992 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001993 if (!SSL_is_init_finished(self->ssl)) {
1994 /* handshake not finished */
1995 Py_RETURN_NONE;
1996 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001997 version = SSL_get_version(self->ssl);
1998 if (!strcmp(version, "unknown"))
1999 Py_RETURN_NONE;
2000 return PyUnicode_FromString(version);
2001}
2002
Miss Islington (bot)96177412018-02-25 04:18:43 -08002003#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002004/*[clinic input]
2005_ssl._SSLSocket.selected_npn_protocol
2006[clinic start generated code]*/
2007
2008static PyObject *
2009_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2010/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2011{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002012 const unsigned char *out;
2013 unsigned int outlen;
2014
Victor Stinner4569cd52013-06-23 14:58:43 +02002015 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002016 &out, &outlen);
2017
2018 if (out == NULL)
2019 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002020 return PyUnicode_FromStringAndSize((char *)out, outlen);
2021}
2022#endif
2023
Miss Islington (bot)96177412018-02-25 04:18:43 -08002024#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002025/*[clinic input]
2026_ssl._SSLSocket.selected_alpn_protocol
2027[clinic start generated code]*/
2028
2029static PyObject *
2030_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2031/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2032{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002033 const unsigned char *out;
2034 unsigned int outlen;
2035
2036 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2037
2038 if (out == NULL)
2039 Py_RETURN_NONE;
2040 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002041}
2042#endif
2043
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002044/*[clinic input]
2045_ssl._SSLSocket.compression
2046[clinic start generated code]*/
2047
2048static PyObject *
2049_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2050/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2051{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002052#ifdef OPENSSL_NO_COMP
2053 Py_RETURN_NONE;
2054#else
2055 const COMP_METHOD *comp_method;
2056 const char *short_name;
2057
2058 if (self->ssl == NULL)
2059 Py_RETURN_NONE;
2060 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002061 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002062 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002063 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002064 if (short_name == NULL)
2065 Py_RETURN_NONE;
2066 return PyUnicode_DecodeFSDefault(short_name);
2067#endif
2068}
2069
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002070static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2071 Py_INCREF(self->ctx);
2072 return self->ctx;
2073}
2074
2075static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2076 void *closure) {
2077
2078 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002079#if !HAVE_SNI
2080 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2081 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002082 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002083#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002084 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002085 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002086 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002087#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002088 } else {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002089 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002090 return -1;
2091 }
2092
2093 return 0;
2094}
2095
2096PyDoc_STRVAR(PySSL_set_context_doc,
2097"_setter_context(ctx)\n\
2098\
2099This changes the context associated with the SSLSocket. This is typically\n\
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002100used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002101on the SSLContext to change the certificate information associated with the\n\
2102SSLSocket before the cryptographic exchange handshake messages\n");
2103
2104
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002105static PyObject *
2106PySSL_get_server_side(PySSLSocket *self, void *c)
2107{
2108 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2109}
2110
2111PyDoc_STRVAR(PySSL_get_server_side_doc,
2112"Whether this is a server-side socket.");
2113
2114static PyObject *
2115PySSL_get_server_hostname(PySSLSocket *self, void *c)
2116{
2117 if (self->server_hostname == NULL)
2118 Py_RETURN_NONE;
2119 Py_INCREF(self->server_hostname);
2120 return self->server_hostname;
2121}
2122
2123PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2124"The currently set server hostname (for SNI).");
2125
2126static PyObject *
2127PySSL_get_owner(PySSLSocket *self, void *c)
2128{
2129 PyObject *owner;
2130
2131 if (self->owner == NULL)
2132 Py_RETURN_NONE;
2133
2134 owner = PyWeakref_GetObject(self->owner);
2135 Py_INCREF(owner);
2136 return owner;
2137}
2138
2139static int
2140PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2141{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002142 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002143 if (self->owner == NULL)
2144 return -1;
2145 return 0;
2146}
2147
2148PyDoc_STRVAR(PySSL_get_owner_doc,
2149"The Python-level owner of this object.\
2150Passed as \"self\" in servername callback.");
2151
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002152
Antoine Pitrou152efa22010-05-16 18:19:27 +00002153static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002154{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 if (self->ssl)
2156 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002158 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002159 Py_XDECREF(self->server_hostname);
2160 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002162}
2163
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002164/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002165 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002166 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002167 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002168
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002169static int
Victor Stinner14690702015-04-06 22:46:13 +02002170PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002171{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002172 int rc;
2173#ifdef HAVE_POLL
2174 struct pollfd pollfd;
2175 _PyTime_t ms;
2176#else
2177 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 fd_set fds;
2179 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002180#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002182 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002183 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002185 else if (timeout < 0) {
2186 if (s->sock_timeout > 0)
2187 return SOCKET_HAS_TIMED_OUT;
2188 else
2189 return SOCKET_IS_BLOCKING;
2190 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002193 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 /* Prefer poll, if available, since you can poll() any fd
2197 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002198#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002199 pollfd.fd = s->sock_fd;
2200 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002201
Victor Stinner14690702015-04-06 22:46:13 +02002202 /* timeout is in seconds, poll() uses milliseconds */
2203 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002204 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002205
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 PySSL_BEGIN_ALLOW_THREADS
2207 rc = poll(&pollfd, 1, (int)ms);
2208 PySSL_END_ALLOW_THREADS
2209#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002211 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002213
Victor Stinner14690702015-04-06 22:46:13 +02002214 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 FD_ZERO(&fds);
2217 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002218
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002219 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002221 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002223 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002225 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002227#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2230 (when we are able to write or when there's something to read) */
2231 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002232}
2233
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002234/*[clinic input]
2235_ssl._SSLSocket.write
2236 b: Py_buffer
2237 /
2238
2239Writes the bytes-like object b into the SSL object.
2240
2241Returns the number of bytes written.
2242[clinic start generated code]*/
2243
2244static PyObject *
2245_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2246/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002247{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 int len;
2249 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002250 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002252 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002253 _PyTime_t timeout, deadline = 0;
2254 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002255
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002256 if (sock != NULL) {
2257 if (((PyObject*)sock) == Py_None) {
2258 _setSSLError("Underlying socket connection gone",
2259 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2260 return NULL;
2261 }
2262 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 }
2264
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002265 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002266 PyErr_Format(PyExc_OverflowError,
2267 "string longer than %d bytes", INT_MAX);
2268 goto error;
2269 }
2270
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002271 if (sock != NULL) {
2272 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002273 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002274 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2275 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2276 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277
Victor Stinner14690702015-04-06 22:46:13 +02002278 timeout = GET_SOCKET_TIMEOUT(sock);
2279 has_timeout = (timeout > 0);
2280 if (has_timeout)
2281 deadline = _PyTime_GetMonotonicClock() + timeout;
2282
2283 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002285 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 "The write operation timed out");
2287 goto error;
2288 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2289 PyErr_SetString(PySSLErrorObject,
2290 "Underlying socket has been closed.");
2291 goto error;
2292 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2293 PyErr_SetString(PySSLErrorObject,
2294 "Underlying socket too large for select().");
2295 goto error;
2296 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002300 len = SSL_write(self->ssl, b->buf, (int)b->len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002301 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002303 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002304
2305 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002307
Victor Stinner14690702015-04-06 22:46:13 +02002308 if (has_timeout)
2309 timeout = deadline - _PyTime_GetMonotonicClock();
2310
Miss Islington (bot)12296642018-09-17 12:12:13 -07002311 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002312 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002313 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002314 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 } else {
2316 sockstate = SOCKET_OPERATION_OK;
2317 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002318
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002319 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002320 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 "The write operation timed out");
2322 goto error;
2323 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2324 PyErr_SetString(PySSLErrorObject,
2325 "Underlying socket has been closed.");
2326 goto error;
2327 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2328 break;
2329 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002330 } while (err.ssl == SSL_ERROR_WANT_READ ||
2331 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002332
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002333 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 if (len > 0)
2335 return PyLong_FromLong(len);
2336 else
2337 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002338
2339error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002340 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002342}
2343
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002344/*[clinic input]
2345_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002346
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002347Returns the number of already decrypted bytes available for read, pending on the connection.
2348[clinic start generated code]*/
2349
2350static PyObject *
2351_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2352/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002353{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 int count = 0;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002355 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002356
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 PySSL_BEGIN_ALLOW_THREADS
2358 count = SSL_pending(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002359 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002361 self->err = err;
2362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 if (count < 0)
2364 return PySSL_SetError(self, count, __FILE__, __LINE__);
2365 else
2366 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002367}
2368
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002369/*[clinic input]
2370_ssl._SSLSocket.read
2371 size as len: int
2372 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002373 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002374 ]
2375 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002376
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002377Read up to size bytes from the SSL socket.
2378[clinic start generated code]*/
2379
2380static PyObject *
2381_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2382 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002383/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002384{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002386 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002387 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002389 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002391 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002392 _PyTime_t timeout, deadline = 0;
2393 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002394
Martin Panter5503d472016-03-27 05:35:19 +00002395 if (!group_right_1 && len < 0) {
2396 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2397 return NULL;
2398 }
2399
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002400 if (sock != NULL) {
2401 if (((PyObject*)sock) == Py_None) {
2402 _setSSLError("Underlying socket connection gone",
2403 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2404 return NULL;
2405 }
2406 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002407 }
2408
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002409 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002410 dest = PyBytes_FromStringAndSize(NULL, len);
2411 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002412 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002413 if (len == 0) {
2414 Py_XDECREF(sock);
2415 return dest;
2416 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002417 mem = PyBytes_AS_STRING(dest);
2418 }
2419 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002420 mem = buffer->buf;
2421 if (len <= 0 || len > buffer->len) {
2422 len = (int) buffer->len;
2423 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002424 PyErr_SetString(PyExc_OverflowError,
2425 "maximum length can't fit in a C 'int'");
2426 goto error;
2427 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002428 if (len == 0) {
2429 count = 0;
2430 goto done;
2431 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002432 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 }
2434
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002435 if (sock != NULL) {
2436 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002437 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002438 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2439 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2440 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441
Victor Stinner14690702015-04-06 22:46:13 +02002442 timeout = GET_SOCKET_TIMEOUT(sock);
2443 has_timeout = (timeout > 0);
2444 if (has_timeout)
2445 deadline = _PyTime_GetMonotonicClock() + timeout;
2446
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002448 PySSL_BEGIN_ALLOW_THREADS
2449 count = SSL_read(self->ssl, mem, len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002450 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002452 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002454 if (PyErr_CheckSignals())
2455 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002456
Victor Stinner14690702015-04-06 22:46:13 +02002457 if (has_timeout)
2458 timeout = deadline - _PyTime_GetMonotonicClock();
2459
Miss Islington (bot)12296642018-09-17 12:12:13 -07002460 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002461 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002462 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002463 sockstate = PySSL_select(sock, 1, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002464 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002465 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 {
2467 count = 0;
2468 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002469 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002470 else
2471 sockstate = SOCKET_OPERATION_OK;
2472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002473 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002474 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 "The read operation timed out");
2476 goto error;
2477 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2478 break;
2479 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002480 } while (err.ssl == SSL_ERROR_WANT_READ ||
2481 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002482
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002483 if (count <= 0) {
2484 PySSL_SetError(self, count, __FILE__, __LINE__);
2485 goto error;
2486 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002487
2488done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002489 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002490 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002491 _PyBytes_Resize(&dest, count);
2492 return dest;
2493 }
2494 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002495 return PyLong_FromLong(count);
2496 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002497
2498error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002499 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002500 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002501 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002502 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002503}
2504
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002505/*[clinic input]
2506_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002507
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002508Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002509[clinic start generated code]*/
2510
2511static PyObject *
2512_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002513/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002514{
Miss Islington (bot)12296642018-09-17 12:12:13 -07002515 _PySSLError err;
2516 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002518 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002519 _PyTime_t timeout, deadline = 0;
2520 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002521
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002522 if (sock != NULL) {
2523 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002524 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002525 _setSSLError("Underlying socket connection gone",
2526 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2527 return NULL;
2528 }
2529 Py_INCREF(sock);
2530
2531 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002532 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002533 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2534 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536
Victor Stinner14690702015-04-06 22:46:13 +02002537 timeout = GET_SOCKET_TIMEOUT(sock);
2538 has_timeout = (timeout > 0);
2539 if (has_timeout)
2540 deadline = _PyTime_GetMonotonicClock() + timeout;
2541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 while (1) {
2543 PySSL_BEGIN_ALLOW_THREADS
2544 /* Disable read-ahead so that unwrap can work correctly.
2545 * Otherwise OpenSSL might read in too much data,
2546 * eating clear text data that happens to be
2547 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002548 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002549 * function is used and the shutdown_seen_zero != 0
2550 * condition is met.
2551 */
2552 if (self->shutdown_seen_zero)
2553 SSL_set_read_ahead(self->ssl, 0);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002554 ret = SSL_shutdown(self->ssl);
2555 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002556 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002557 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002560 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 break;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002562 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 /* Don't loop endlessly; instead preserve legacy
2564 behaviour of trying SSL_shutdown() only twice.
2565 This looks necessary for OpenSSL < 0.9.8m */
2566 if (++zeros > 1)
2567 break;
2568 /* Shutdown was sent, now try receiving */
2569 self->shutdown_seen_zero = 1;
2570 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002571 }
2572
Victor Stinner14690702015-04-06 22:46:13 +02002573 if (has_timeout)
2574 timeout = deadline - _PyTime_GetMonotonicClock();
2575
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 /* Possibly retry shutdown until timeout or failure */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002577 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002578 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002579 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002580 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 else
2582 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002583
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Miss Islington (bot)12296642018-09-17 12:12:13 -07002585 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002586 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002587 "The read operation timed out");
2588 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002589 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002590 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002591 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 }
2593 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2594 PyErr_SetString(PySSLErrorObject,
2595 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002596 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002597 }
2598 else if (sockstate != SOCKET_OPERATION_OK)
2599 /* Retain the SSL error code */
2600 break;
2601 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002602
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002603 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002604 Py_XDECREF(sock);
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002605 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002607 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002608 /* It's already INCREF'ed */
2609 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002610 else
2611 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002612
2613error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002614 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002615 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002616}
2617
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002618/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002619_ssl._SSLSocket.get_channel_binding
2620 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002621
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002622Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002623
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002624Raise ValueError if the requested `cb_type` is not supported. Return bytes
2625of the data or None if the data is not available (e.g. before the handshake).
2626Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002627[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002628
Antoine Pitroud6494802011-07-21 01:11:30 +02002629static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002630_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2631 const char *cb_type)
2632/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002633{
Antoine Pitroud6494802011-07-21 01:11:30 +02002634 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002635 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002636
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002637 if (strcmp(cb_type, "tls-unique") == 0) {
2638 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2639 /* if session is resumed XOR we are the client */
2640 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2641 }
2642 else {
2643 /* if a new session XOR we are the server */
2644 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2645 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002646 }
2647 else {
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002648 PyErr_Format(
2649 PyExc_ValueError,
2650 "'%s' channel binding type not implemented",
2651 cb_type
2652 );
2653 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002654 }
2655
2656 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002657 if (len == 0)
2658 Py_RETURN_NONE;
2659
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002660 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002661}
2662
Christian Heimes2756ef32018-09-23 09:22:52 +02002663/*[clinic input]
2664_ssl._SSLSocket.verify_client_post_handshake
2665
2666Initiate TLS 1.3 post-handshake authentication
2667[clinic start generated code]*/
2668
2669static PyObject *
2670_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2671/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2672{
2673#ifdef TLS1_3_VERSION
2674 int err = SSL_verify_client_post_handshake(self->ssl);
2675 if (err == 0)
2676 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2677 else
2678 Py_RETURN_NONE;
2679#else
2680 PyErr_SetString(PyExc_NotImplementedError,
2681 "Post-handshake auth is not supported by your "
2682 "OpenSSL version.");
2683 return NULL;
2684#endif
2685}
2686
Christian Heimes99a65702016-09-10 23:44:53 +02002687#ifdef OPENSSL_VERSION_1_1
2688
2689static SSL_SESSION*
2690_ssl_session_dup(SSL_SESSION *session) {
2691 SSL_SESSION *newsession = NULL;
2692 int slen;
2693 unsigned char *senc = NULL, *p;
2694 const unsigned char *const_p;
2695
2696 if (session == NULL) {
2697 PyErr_SetString(PyExc_ValueError, "Invalid session");
2698 goto error;
2699 }
2700
2701 /* get length */
2702 slen = i2d_SSL_SESSION(session, NULL);
2703 if (slen == 0 || slen > 0xFF00) {
2704 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2705 goto error;
2706 }
2707 if ((senc = PyMem_Malloc(slen)) == NULL) {
2708 PyErr_NoMemory();
2709 goto error;
2710 }
2711 p = senc;
2712 if (!i2d_SSL_SESSION(session, &p)) {
2713 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2714 goto error;
2715 }
2716 const_p = senc;
2717 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2718 if (session == NULL) {
2719 goto error;
2720 }
2721 PyMem_Free(senc);
2722 return newsession;
2723 error:
2724 if (senc != NULL) {
2725 PyMem_Free(senc);
2726 }
2727 return NULL;
2728}
2729#endif
2730
2731static PyObject *
2732PySSL_get_session(PySSLSocket *self, void *closure) {
2733 /* get_session can return sessions from a server-side connection,
2734 * it does not check for handshake done or client socket. */
2735 PySSLSession *pysess;
2736 SSL_SESSION *session;
2737
2738#ifdef OPENSSL_VERSION_1_1
2739 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2740 * https://github.com/openssl/openssl/issues/1550 */
2741 session = SSL_get0_session(self->ssl); /* borrowed reference */
2742 if (session == NULL) {
2743 Py_RETURN_NONE;
2744 }
2745 if ((session = _ssl_session_dup(session)) == NULL) {
2746 return NULL;
2747 }
2748#else
2749 session = SSL_get1_session(self->ssl);
2750 if (session == NULL) {
2751 Py_RETURN_NONE;
2752 }
2753#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002754 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002755 if (pysess == NULL) {
2756 SSL_SESSION_free(session);
2757 return NULL;
2758 }
2759
2760 assert(self->ctx);
2761 pysess->ctx = self->ctx;
2762 Py_INCREF(pysess->ctx);
2763 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002764 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002765 return (PyObject *)pysess;
2766}
2767
2768static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2769 void *closure)
2770 {
2771 PySSLSession *pysess;
2772#ifdef OPENSSL_VERSION_1_1
2773 SSL_SESSION *session;
2774#endif
2775 int result;
2776
2777 if (!PySSLSession_Check(value)) {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002778 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002779 return -1;
2780 }
2781 pysess = (PySSLSession *)value;
2782
2783 if (self->ctx->ctx != pysess->ctx->ctx) {
2784 PyErr_SetString(PyExc_ValueError,
2785 "Session refers to a different SSLContext.");
2786 return -1;
2787 }
2788 if (self->socket_type != PY_SSL_CLIENT) {
2789 PyErr_SetString(PyExc_ValueError,
2790 "Cannot set session for server-side SSLSocket.");
2791 return -1;
2792 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002793 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002794 PyErr_SetString(PyExc_ValueError,
2795 "Cannot set session after handshake.");
2796 return -1;
2797 }
2798#ifdef OPENSSL_VERSION_1_1
2799 /* duplicate session */
2800 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2801 return -1;
2802 }
2803 result = SSL_set_session(self->ssl, session);
2804 /* free duplicate, SSL_set_session() bumps ref count */
2805 SSL_SESSION_free(session);
2806#else
2807 result = SSL_set_session(self->ssl, pysess->session);
2808#endif
2809 if (result == 0) {
2810 _setSSLError(NULL, 0, __FILE__, __LINE__);
2811 return -1;
2812 }
2813 return 0;
2814}
2815
2816PyDoc_STRVAR(PySSL_set_session_doc,
2817"_setter_session(session)\n\
2818\
2819Get / set SSLSession.");
2820
2821static PyObject *
2822PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2823 if (SSL_session_reused(self->ssl)) {
2824 Py_RETURN_TRUE;
2825 } else {
2826 Py_RETURN_FALSE;
2827 }
2828}
2829
2830PyDoc_STRVAR(PySSL_get_session_reused_doc,
2831"Was the client session reused during handshake?");
2832
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002833static PyGetSetDef ssl_getsetlist[] = {
2834 {"context", (getter) PySSL_get_context,
2835 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002836 {"server_side", (getter) PySSL_get_server_side, NULL,
2837 PySSL_get_server_side_doc},
2838 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2839 PySSL_get_server_hostname_doc},
2840 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2841 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002842 {"session", (getter) PySSL_get_session,
2843 (setter) PySSL_set_session, PySSL_set_session_doc},
2844 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2845 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002846 {NULL}, /* sentinel */
2847};
2848
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002849static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002850 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2851 _SSL__SSLSOCKET_WRITE_METHODDEF
2852 _SSL__SSLSOCKET_READ_METHODDEF
2853 _SSL__SSLSOCKET_PENDING_METHODDEF
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002854 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2855 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002856 _SSL__SSLSOCKET_CIPHER_METHODDEF
2857 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2858 _SSL__SSLSOCKET_VERSION_METHODDEF
2859 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2860 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2861 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2862 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes2756ef32018-09-23 09:22:52 +02002863 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002864 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002865};
2866
Antoine Pitrou152efa22010-05-16 18:19:27 +00002867static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002868 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002869 "_ssl._SSLSocket", /*tp_name*/
2870 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002871 0, /*tp_itemsize*/
2872 /* methods */
2873 (destructor)PySSL_dealloc, /*tp_dealloc*/
2874 0, /*tp_print*/
2875 0, /*tp_getattr*/
2876 0, /*tp_setattr*/
2877 0, /*tp_reserved*/
2878 0, /*tp_repr*/
2879 0, /*tp_as_number*/
2880 0, /*tp_as_sequence*/
2881 0, /*tp_as_mapping*/
2882 0, /*tp_hash*/
2883 0, /*tp_call*/
2884 0, /*tp_str*/
2885 0, /*tp_getattro*/
2886 0, /*tp_setattro*/
2887 0, /*tp_as_buffer*/
2888 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2889 0, /*tp_doc*/
2890 0, /*tp_traverse*/
2891 0, /*tp_clear*/
2892 0, /*tp_richcompare*/
2893 0, /*tp_weaklistoffset*/
2894 0, /*tp_iter*/
2895 0, /*tp_iternext*/
2896 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002897 0, /*tp_members*/
2898 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002899};
2900
Antoine Pitrou152efa22010-05-16 18:19:27 +00002901
2902/*
2903 * _SSLContext objects
2904 */
2905
Christian Heimes5fe668c2016-09-12 00:01:11 +02002906static int
Christian Heimes2756ef32018-09-23 09:22:52 +02002907_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002908{
2909 int mode;
2910 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2911
2912 switch(n) {
2913 case PY_SSL_CERT_NONE:
2914 mode = SSL_VERIFY_NONE;
2915 break;
2916 case PY_SSL_CERT_OPTIONAL:
2917 mode = SSL_VERIFY_PEER;
2918 break;
2919 case PY_SSL_CERT_REQUIRED:
2920 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2921 break;
2922 default:
2923 PyErr_SetString(PyExc_ValueError,
2924 "invalid value for verify_mode");
2925 return -1;
2926 }
Christian Heimes2756ef32018-09-23 09:22:52 +02002927#ifdef TLS1_3_VERSION
2928 if (self->post_handshake_auth)
2929 mode |= SSL_VERIFY_POST_HANDSHAKE;
2930#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002931 /* keep current verify cb */
Christian Heimes2756ef32018-09-23 09:22:52 +02002932 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2933 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002934 return 0;
2935}
2936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002937/*[clinic input]
2938@classmethod
2939_ssl._SSLContext.__new__
2940 protocol as proto_version: int
2941 /
2942[clinic start generated code]*/
2943
Antoine Pitrou152efa22010-05-16 18:19:27 +00002944static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002945_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2946/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002947{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002948 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002949 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002950 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002951 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002952 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002953#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002954 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002955#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002956
Antoine Pitrou152efa22010-05-16 18:19:27 +00002957 PySSL_BEGIN_ALLOW_THREADS
2958 if (proto_version == PY_SSL_VERSION_TLS1)
2959 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002960#if HAVE_TLSv1_2
2961 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2962 ctx = SSL_CTX_new(TLSv1_1_method());
2963 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2964 ctx = SSL_CTX_new(TLSv1_2_method());
2965#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002966#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002967 else if (proto_version == PY_SSL_VERSION_SSL3)
2968 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002969#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002970#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002971 else if (proto_version == PY_SSL_VERSION_SSL2)
2972 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002973#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002974 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002975 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002976 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2977 ctx = SSL_CTX_new(TLS_client_method());
2978 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2979 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002980 else
2981 proto_version = -1;
2982 PySSL_END_ALLOW_THREADS
2983
2984 if (proto_version == -1) {
2985 PyErr_SetString(PyExc_ValueError,
2986 "invalid protocol version");
2987 return NULL;
2988 }
2989 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002990 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002991 return NULL;
2992 }
2993
2994 assert(type != NULL && type->tp_alloc != NULL);
2995 self = (PySSLContext *) type->tp_alloc(type, 0);
2996 if (self == NULL) {
2997 SSL_CTX_free(ctx);
2998 return NULL;
2999 }
3000 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003001 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003002 self->protocol = proto_version;
Miss Islington (bot)96177412018-02-25 04:18:43 -08003003#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003004 self->npn_protocols = NULL;
3005#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08003006#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003007 self->alpn_protocols = NULL;
3008#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003009#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003010 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003011#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003012 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003013 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3014 self->check_hostname = 1;
Christian Heimes2756ef32018-09-23 09:22:52 +02003015 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003016 Py_DECREF(self);
3017 return NULL;
3018 }
3019 } else {
3020 self->check_hostname = 0;
Christian Heimes2756ef32018-09-23 09:22:52 +02003021 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003022 Py_DECREF(self);
3023 return NULL;
3024 }
3025 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003026 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003027 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3028 if (proto_version != PY_SSL_VERSION_SSL2)
3029 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003030 if (proto_version != PY_SSL_VERSION_SSL3)
3031 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003032 /* Minimal security flags for server and client side context.
3033 * Client sockets ignore server-side parameters. */
3034#ifdef SSL_OP_NO_COMPRESSION
3035 options |= SSL_OP_NO_COMPRESSION;
3036#endif
3037#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3038 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3039#endif
3040#ifdef SSL_OP_SINGLE_DH_USE
3041 options |= SSL_OP_SINGLE_DH_USE;
3042#endif
3043#ifdef SSL_OP_SINGLE_ECDH_USE
3044 options |= SSL_OP_SINGLE_ECDH_USE;
3045#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003046 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003047
Semen Zhydenko1295e112017-10-15 21:28:31 +02003048 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003049 * It's far from perfect but gives users a better head start. */
3050 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003051#if PY_SSL_DEFAULT_CIPHERS == 2
3052 /* stick to OpenSSL's default settings */
3053 result = 1;
3054#else
3055 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3056#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003057 } else {
3058 /* SSLv2 needs MD5 */
3059 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3060 }
3061 if (result == 0) {
3062 Py_DECREF(self);
3063 ERR_clear_error();
3064 PyErr_SetString(PySSLErrorObject,
3065 "No cipher can be selected.");
3066 return NULL;
3067 }
3068
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003069#if defined(SSL_MODE_RELEASE_BUFFERS)
3070 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3071 usage for no cost at all. However, don't do this for OpenSSL versions
3072 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3073 2014-0198. I can't find exactly which beta fixed this CVE, so be
3074 conservative and assume it wasn't fixed until release. We do this check
3075 at runtime to avoid problems from the dynamic linker.
3076 See #25672 for more on this. */
3077 libver = SSLeay();
3078 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3079 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3080 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3081 }
3082#endif
3083
3084
Donald Stufft8ae264c2017-03-02 11:45:29 -05003085#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003086 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3087 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003088 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3089 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003090#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003091 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3092#else
3093 {
3094 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3095 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3096 EC_KEY_free(key);
3097 }
3098#endif
3099#endif
3100
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003101#define SID_CTX "Python"
3102 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3103 sizeof(SID_CTX));
3104#undef SID_CTX
3105
Christian Heimes61d478c2018-01-27 15:51:38 +01003106 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003107#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003108 /* Improve trust chain building when cross-signed intermediate
3109 certificates are present. See https://bugs.python.org/issue23476. */
3110 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003111#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003112 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003113
Christian Heimes2756ef32018-09-23 09:22:52 +02003114#ifdef TLS1_3_VERSION
3115 self->post_handshake_auth = 0;
3116 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3117#endif
3118
Antoine Pitrou152efa22010-05-16 18:19:27 +00003119 return (PyObject *)self;
3120}
3121
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003122static int
3123context_traverse(PySSLContext *self, visitproc visit, void *arg)
3124{
3125#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003126 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003127#endif
3128 return 0;
3129}
3130
3131static int
3132context_clear(PySSLContext *self)
3133{
3134#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003135 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003136#endif
3137 return 0;
3138}
3139
Antoine Pitrou152efa22010-05-16 18:19:27 +00003140static void
3141context_dealloc(PySSLContext *self)
3142{
INADA Naokia6296d32017-08-24 14:55:17 +09003143 /* bpo-31095: UnTrack is needed before calling any callbacks */
3144 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003145 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003146 SSL_CTX_free(self->ctx);
Miss Islington (bot)96177412018-02-25 04:18:43 -08003147#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003148 PyMem_FREE(self->npn_protocols);
3149#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08003150#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003151 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003152#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003153 Py_TYPE(self)->tp_free(self);
3154}
3155
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003156/*[clinic input]
3157_ssl._SSLContext.set_ciphers
3158 cipherlist: str
3159 /
3160[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003161
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003162static PyObject *
3163_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3164/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3165{
3166 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003167 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003168 /* Clearing the error queue is necessary on some OpenSSL versions,
3169 otherwise the error will be reported again when another SSL call
3170 is done. */
3171 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003172 PyErr_SetString(PySSLErrorObject,
3173 "No cipher can be selected.");
3174 return NULL;
3175 }
3176 Py_RETURN_NONE;
3177}
3178
Christian Heimes25bfcd52016-09-06 00:04:45 +02003179#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3180/*[clinic input]
3181_ssl._SSLContext.get_ciphers
3182[clinic start generated code]*/
3183
3184static PyObject *
3185_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3186/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3187{
3188 SSL *ssl = NULL;
3189 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003190 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003191 int i=0;
3192 PyObject *result = NULL, *dct;
3193
3194 ssl = SSL_new(self->ctx);
3195 if (ssl == NULL) {
3196 _setSSLError(NULL, 0, __FILE__, __LINE__);
3197 goto exit;
3198 }
3199 sk = SSL_get_ciphers(ssl);
3200
3201 result = PyList_New(sk_SSL_CIPHER_num(sk));
3202 if (result == NULL) {
3203 goto exit;
3204 }
3205
3206 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3207 cipher = sk_SSL_CIPHER_value(sk, i);
3208 dct = cipher_to_dict(cipher);
3209 if (dct == NULL) {
3210 Py_CLEAR(result);
3211 goto exit;
3212 }
3213 PyList_SET_ITEM(result, i, dct);
3214 }
3215
3216 exit:
3217 if (ssl != NULL)
3218 SSL_free(ssl);
3219 return result;
3220
3221}
3222#endif
3223
3224
Miss Islington (bot)96177412018-02-25 04:18:43 -08003225#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003227do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3228 const unsigned char *server_protocols, unsigned int server_protocols_len,
3229 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003230{
Benjamin Peterson88615022015-01-23 17:30:26 -05003231 int ret;
3232 if (client_protocols == NULL) {
3233 client_protocols = (unsigned char *)"";
3234 client_protocols_len = 0;
3235 }
3236 if (server_protocols == NULL) {
3237 server_protocols = (unsigned char *)"";
3238 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003239 }
3240
Benjamin Peterson88615022015-01-23 17:30:26 -05003241 ret = SSL_select_next_proto(out, outlen,
3242 server_protocols, server_protocols_len,
3243 client_protocols, client_protocols_len);
3244 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3245 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003246
3247 return SSL_TLSEXT_ERR_OK;
3248}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003249#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003250
Miss Islington (bot)96177412018-02-25 04:18:43 -08003251#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003252/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3253static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003254_advertiseNPN_cb(SSL *s,
3255 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003256 void *args)
3257{
3258 PySSLContext *ssl_ctx = (PySSLContext *) args;
3259
3260 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003261 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003262 *len = 0;
3263 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003264 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003265 *len = ssl_ctx->npn_protocols_len;
3266 }
3267
3268 return SSL_TLSEXT_ERR_OK;
3269}
3270/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3271static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003272_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003273 unsigned char **out, unsigned char *outlen,
3274 const unsigned char *server, unsigned int server_len,
3275 void *args)
3276{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003277 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003278 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003279 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003280}
3281#endif
3282
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003283/*[clinic input]
3284_ssl._SSLContext._set_npn_protocols
3285 protos: Py_buffer
3286 /
3287[clinic start generated code]*/
3288
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003289static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003290_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3291 Py_buffer *protos)
3292/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003293{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003294#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003295 PyMem_Free(self->npn_protocols);
3296 self->npn_protocols = PyMem_Malloc(protos->len);
3297 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003298 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003299 memcpy(self->npn_protocols, protos->buf, protos->len);
3300 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003301
3302 /* set both server and client callbacks, because the context can
3303 * be used to create both types of sockets */
3304 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3305 _advertiseNPN_cb,
3306 self);
3307 SSL_CTX_set_next_proto_select_cb(self->ctx,
3308 _selectNPN_cb,
3309 self);
3310
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003311 Py_RETURN_NONE;
3312#else
3313 PyErr_SetString(PyExc_NotImplementedError,
3314 "The NPN extension requires OpenSSL 1.0.1 or later.");
3315 return NULL;
3316#endif
3317}
3318
Miss Islington (bot)96177412018-02-25 04:18:43 -08003319#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003320static int
3321_selectALPN_cb(SSL *s,
3322 const unsigned char **out, unsigned char *outlen,
3323 const unsigned char *client_protocols, unsigned int client_protocols_len,
3324 void *args)
3325{
3326 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003327 return do_protocol_selection(1, (unsigned char **)out, outlen,
3328 ctx->alpn_protocols, ctx->alpn_protocols_len,
3329 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003330}
3331#endif
3332
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003333/*[clinic input]
3334_ssl._SSLContext._set_alpn_protocols
3335 protos: Py_buffer
3336 /
3337[clinic start generated code]*/
3338
Benjamin Petersoncca27322015-01-23 16:35:37 -05003339static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003340_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3341 Py_buffer *protos)
3342/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003343{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003344#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003345 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003346 PyErr_Format(PyExc_OverflowError,
3347 "protocols longer than %d bytes", UINT_MAX);
3348 return NULL;
3349 }
3350
Benjamin Petersoncca27322015-01-23 16:35:37 -05003351 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003352 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003353 if (!self->alpn_protocols)
3354 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003355 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003356 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003357
3358 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3359 return PyErr_NoMemory();
3360 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3361
Benjamin Petersoncca27322015-01-23 16:35:37 -05003362 Py_RETURN_NONE;
3363#else
3364 PyErr_SetString(PyExc_NotImplementedError,
3365 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3366 return NULL;
3367#endif
3368}
3369
Antoine Pitrou152efa22010-05-16 18:19:27 +00003370static PyObject *
3371get_verify_mode(PySSLContext *self, void *c)
3372{
Christian Heimes2756ef32018-09-23 09:22:52 +02003373 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3374 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3375 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3376 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003377 case SSL_VERIFY_NONE:
3378 return PyLong_FromLong(PY_SSL_CERT_NONE);
3379 case SSL_VERIFY_PEER:
3380 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3381 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3382 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3383 }
3384 PyErr_SetString(PySSLErrorObject,
3385 "invalid return value from SSL_CTX_get_verify_mode");
3386 return NULL;
3387}
3388
3389static int
3390set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3391{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003392 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003393 if (!PyArg_Parse(arg, "i", &n))
3394 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003395 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003396 PyErr_SetString(PyExc_ValueError,
3397 "Cannot set verify_mode to CERT_NONE when "
3398 "check_hostname is enabled.");
3399 return -1;
3400 }
Christian Heimes2756ef32018-09-23 09:22:52 +02003401 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003402}
3403
3404static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003405get_verify_flags(PySSLContext *self, void *c)
3406{
Christian Heimes598894f2016-09-05 23:19:05 +02003407 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003408 unsigned long flags;
3409
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 return PyLong_FromUnsignedLong(flags);
3413}
3414
3415static int
3416set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3417{
Christian Heimes598894f2016-09-05 23:19:05 +02003418 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003419 unsigned long new_flags, flags, set, clear;
3420
3421 if (!PyArg_Parse(arg, "k", &new_flags))
3422 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003423 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003424 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003425 clear = flags & ~new_flags;
3426 set = ~flags & new_flags;
3427 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003428 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003429 _setSSLError(NULL, 0, __FILE__, __LINE__);
3430 return -1;
3431 }
3432 }
3433 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003434 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003435 _setSSLError(NULL, 0, __FILE__, __LINE__);
3436 return -1;
3437 }
3438 }
3439 return 0;
3440}
3441
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08003442/* Getter and setter for protocol version */
3443#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3444
3445
3446static int
3447set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3448{
3449 long v;
3450 int result;
3451
3452 if (!PyArg_Parse(arg, "l", &v))
3453 return -1;
3454 if (v > INT_MAX) {
3455 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3456 return -1;
3457 }
3458
3459 switch(self->protocol) {
3460 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3461 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3462 case PY_SSL_VERSION_TLS:
3463 break;
3464 default:
3465 PyErr_SetString(
3466 PyExc_ValueError,
3467 "The context's protocol doesn't support modification of "
3468 "highest and lowest version."
3469 );
3470 return -1;
3471 }
3472
3473 if (what == 0) {
3474 switch(v) {
3475 case PY_PROTO_MINIMUM_SUPPORTED:
3476 v = 0;
3477 break;
3478 case PY_PROTO_MAXIMUM_SUPPORTED:
3479 /* Emulate max for set_min_proto_version */
3480 v = PY_PROTO_MAXIMUM_AVAILABLE;
3481 break;
3482 default:
3483 break;
3484 }
3485 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3486 }
3487 else {
3488 switch(v) {
3489 case PY_PROTO_MAXIMUM_SUPPORTED:
3490 v = 0;
3491 break;
3492 case PY_PROTO_MINIMUM_SUPPORTED:
3493 /* Emulate max for set_min_proto_version */
3494 v = PY_PROTO_MINIMUM_AVAILABLE;
3495 break;
3496 default:
3497 break;
3498 }
3499 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3500 }
3501 if (result == 0) {
3502 PyErr_Format(PyExc_ValueError,
3503 "Unsupported protocol version 0x%x", v);
3504 return -1;
3505 }
3506 return 0;
3507}
3508
3509static PyObject *
3510get_minimum_version(PySSLContext *self, void *c)
3511{
3512 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3513 if (v == 0) {
3514 v = PY_PROTO_MINIMUM_SUPPORTED;
3515 }
3516 return PyLong_FromLong(v);
3517}
3518
3519static int
3520set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3521{
3522 return set_min_max_proto_version(self, arg, 0);
3523}
3524
3525static PyObject *
3526get_maximum_version(PySSLContext *self, void *c)
3527{
3528 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3529 if (v == 0) {
3530 v = PY_PROTO_MAXIMUM_SUPPORTED;
3531 }
3532 return PyLong_FromLong(v);
3533}
3534
3535static int
3536set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3537{
3538 return set_min_max_proto_version(self, arg, 1);
3539}
3540#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3541
Christian Heimes22587792013-11-21 23:56:13 +01003542static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003543get_options(PySSLContext *self, void *c)
3544{
3545 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3546}
3547
3548static int
3549set_options(PySSLContext *self, PyObject *arg, void *c)
3550{
3551 long new_opts, opts, set, clear;
3552 if (!PyArg_Parse(arg, "l", &new_opts))
3553 return -1;
3554 opts = SSL_CTX_get_options(self->ctx);
3555 clear = opts & ~new_opts;
3556 set = ~opts & new_opts;
3557 if (clear) {
3558#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3559 SSL_CTX_clear_options(self->ctx, clear);
3560#else
3561 PyErr_SetString(PyExc_ValueError,
3562 "can't clear options before OpenSSL 0.9.8m");
3563 return -1;
3564#endif
3565 }
3566 if (set)
3567 SSL_CTX_set_options(self->ctx, set);
3568 return 0;
3569}
3570
Christian Heimes1aa9a752013-12-02 02:41:19 +01003571static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003572get_host_flags(PySSLContext *self, void *c)
3573{
3574 return PyLong_FromUnsignedLong(self->hostflags);
3575}
3576
3577static int
3578set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3579{
3580 X509_VERIFY_PARAM *param;
3581 unsigned int new_flags = 0;
3582
3583 if (!PyArg_Parse(arg, "I", &new_flags))
3584 return -1;
3585
3586 param = SSL_CTX_get0_param(self->ctx);
3587 self->hostflags = new_flags;
3588 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3589 return 0;
3590}
3591
3592static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003593get_check_hostname(PySSLContext *self, void *c)
3594{
3595 return PyBool_FromLong(self->check_hostname);
3596}
3597
3598static int
3599set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3600{
3601 int check_hostname;
3602 if (!PyArg_Parse(arg, "p", &check_hostname))
3603 return -1;
3604 if (check_hostname &&
3605 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003606 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes2756ef32018-09-23 09:22:52 +02003607 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003608 return -1;
3609 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003610 }
3611 self->check_hostname = check_hostname;
3612 return 0;
3613}
3614
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003615static PyObject *
Christian Heimes2756ef32018-09-23 09:22:52 +02003616get_post_handshake_auth(PySSLContext *self, void *c) {
3617#if TLS1_3_VERSION
3618 return PyBool_FromLong(self->post_handshake_auth);
3619#else
3620 Py_RETURN_NONE;
3621#endif
3622}
3623
3624#if TLS1_3_VERSION
3625static int
3626set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3627 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3628 int mode = SSL_CTX_get_verify_mode(self->ctx);
3629 int pha = PyObject_IsTrue(arg);
3630
3631 if (pha == -1) {
3632 return -1;
3633 }
3634 self->post_handshake_auth = pha;
3635
3636 /* client-side socket setting, ignored by server-side */
3637 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3638
3639 /* server-side socket setting, ignored by client-side */
3640 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3641 if (pha) {
3642 mode |= SSL_VERIFY_POST_HANDSHAKE;
3643 } else {
3644 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3645 }
3646 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3647
3648 return 0;
3649}
3650#endif
3651
3652static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003653get_protocol(PySSLContext *self, void *c) {
3654 return PyLong_FromLong(self->protocol);
3655}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003656
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003657typedef struct {
3658 PyThreadState *thread_state;
3659 PyObject *callable;
3660 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003661 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003662 int error;
3663} _PySSLPasswordInfo;
3664
3665static int
3666_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3667 const char *bad_type_error)
3668{
3669 /* Set the password and size fields of a _PySSLPasswordInfo struct
3670 from a unicode, bytes, or byte array object.
3671 The password field will be dynamically allocated and must be freed
3672 by the caller */
3673 PyObject *password_bytes = NULL;
3674 const char *data = NULL;
3675 Py_ssize_t size;
3676
3677 if (PyUnicode_Check(password)) {
3678 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3679 if (!password_bytes) {
3680 goto error;
3681 }
3682 data = PyBytes_AS_STRING(password_bytes);
3683 size = PyBytes_GET_SIZE(password_bytes);
3684 } else if (PyBytes_Check(password)) {
3685 data = PyBytes_AS_STRING(password);
3686 size = PyBytes_GET_SIZE(password);
3687 } else if (PyByteArray_Check(password)) {
3688 data = PyByteArray_AS_STRING(password);
3689 size = PyByteArray_GET_SIZE(password);
3690 } else {
3691 PyErr_SetString(PyExc_TypeError, bad_type_error);
3692 goto error;
3693 }
3694
Victor Stinner9ee02032013-06-23 15:08:23 +02003695 if (size > (Py_ssize_t)INT_MAX) {
3696 PyErr_Format(PyExc_ValueError,
3697 "password cannot be longer than %d bytes", INT_MAX);
3698 goto error;
3699 }
3700
Victor Stinner11ebff22013-07-07 17:07:52 +02003701 PyMem_Free(pw_info->password);
3702 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003703 if (!pw_info->password) {
3704 PyErr_SetString(PyExc_MemoryError,
3705 "unable to allocate password buffer");
3706 goto error;
3707 }
3708 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003709 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003710
3711 Py_XDECREF(password_bytes);
3712 return 1;
3713
3714error:
3715 Py_XDECREF(password_bytes);
3716 return 0;
3717}
3718
3719static int
3720_password_callback(char *buf, int size, int rwflag, void *userdata)
3721{
3722 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3723 PyObject *fn_ret = NULL;
3724
3725 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3726
3727 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003728 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003729 if (!fn_ret) {
3730 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3731 core python API, so we could use it to add a frame here */
3732 goto error;
3733 }
3734
3735 if (!_pwinfo_set(pw_info, fn_ret,
3736 "password callback must return a string")) {
3737 goto error;
3738 }
3739 Py_CLEAR(fn_ret);
3740 }
3741
3742 if (pw_info->size > size) {
3743 PyErr_Format(PyExc_ValueError,
3744 "password cannot be longer than %d bytes", size);
3745 goto error;
3746 }
3747
3748 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3749 memcpy(buf, pw_info->password, pw_info->size);
3750 return pw_info->size;
3751
3752error:
3753 Py_XDECREF(fn_ret);
3754 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3755 pw_info->error = 1;
3756 return -1;
3757}
3758
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003759/*[clinic input]
3760_ssl._SSLContext.load_cert_chain
3761 certfile: object
3762 keyfile: object = NULL
3763 password: object = NULL
3764
3765[clinic start generated code]*/
3766
Antoine Pitroub5218772010-05-21 09:56:06 +00003767static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003768_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3769 PyObject *keyfile, PyObject *password)
3770/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003771{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003772 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003773 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3774 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003775 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003776 int r;
3777
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003778 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003779 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003780 if (keyfile == Py_None)
3781 keyfile = NULL;
3782 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3783 PyErr_SetString(PyExc_TypeError,
3784 "certfile should be a valid filesystem path");
3785 return NULL;
3786 }
3787 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3788 PyErr_SetString(PyExc_TypeError,
3789 "keyfile should be a valid filesystem path");
3790 goto error;
3791 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003792 if (password && password != Py_None) {
3793 if (PyCallable_Check(password)) {
3794 pw_info.callable = password;
3795 } else if (!_pwinfo_set(&pw_info, password,
3796 "password should be a string or callable")) {
3797 goto error;
3798 }
3799 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3800 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3801 }
3802 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003803 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3804 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003805 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003806 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003807 if (pw_info.error) {
3808 ERR_clear_error();
3809 /* the password callback has already set the error information */
3810 }
3811 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003812 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003813 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003814 }
3815 else {
3816 _setSSLError(NULL, 0, __FILE__, __LINE__);
3817 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003818 goto error;
3819 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003820 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003821 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003822 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3823 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003824 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3825 Py_CLEAR(keyfile_bytes);
3826 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003827 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003828 if (pw_info.error) {
3829 ERR_clear_error();
3830 /* the password callback has already set the error information */
3831 }
3832 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003833 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003834 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003835 }
3836 else {
3837 _setSSLError(NULL, 0, __FILE__, __LINE__);
3838 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003839 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003840 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003841 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003842 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003843 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003844 if (r != 1) {
3845 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003846 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003847 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003848 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3849 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003850 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003851 Py_RETURN_NONE;
3852
3853error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003854 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3855 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003856 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003857 Py_XDECREF(keyfile_bytes);
3858 Py_XDECREF(certfile_bytes);
3859 return NULL;
3860}
3861
Christian Heimesefff7062013-11-21 03:35:02 +01003862/* internal helper function, returns -1 on error
3863 */
3864static int
3865_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3866 int filetype)
3867{
3868 BIO *biobuf = NULL;
3869 X509_STORE *store;
3870 int retval = 0, err, loaded = 0;
3871
3872 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3873
3874 if (len <= 0) {
3875 PyErr_SetString(PyExc_ValueError,
3876 "Empty certificate data");
3877 return -1;
3878 } else if (len > INT_MAX) {
3879 PyErr_SetString(PyExc_OverflowError,
3880 "Certificate data is too long.");
3881 return -1;
3882 }
3883
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003884 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003885 if (biobuf == NULL) {
3886 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3887 return -1;
3888 }
3889
3890 store = SSL_CTX_get_cert_store(self->ctx);
3891 assert(store != NULL);
3892
3893 while (1) {
3894 X509 *cert = NULL;
3895 int r;
3896
3897 if (filetype == SSL_FILETYPE_ASN1) {
3898 cert = d2i_X509_bio(biobuf, NULL);
3899 } else {
3900 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003901 SSL_CTX_get_default_passwd_cb(self->ctx),
3902 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3903 );
Christian Heimesefff7062013-11-21 03:35:02 +01003904 }
3905 if (cert == NULL) {
3906 break;
3907 }
3908 r = X509_STORE_add_cert(store, cert);
3909 X509_free(cert);
3910 if (!r) {
3911 err = ERR_peek_last_error();
3912 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3913 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3914 /* cert already in hash table, not an error */
3915 ERR_clear_error();
3916 } else {
3917 break;
3918 }
3919 }
3920 loaded++;
3921 }
3922
3923 err = ERR_peek_last_error();
3924 if ((filetype == SSL_FILETYPE_ASN1) &&
3925 (loaded > 0) &&
3926 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3927 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3928 /* EOF ASN1 file, not an error */
3929 ERR_clear_error();
3930 retval = 0;
3931 } else if ((filetype == SSL_FILETYPE_PEM) &&
3932 (loaded > 0) &&
3933 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3934 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3935 /* EOF PEM file, not an error */
3936 ERR_clear_error();
3937 retval = 0;
3938 } else {
3939 _setSSLError(NULL, 0, __FILE__, __LINE__);
3940 retval = -1;
3941 }
3942
3943 BIO_free(biobuf);
3944 return retval;
3945}
3946
3947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003948/*[clinic input]
3949_ssl._SSLContext.load_verify_locations
3950 cafile: object = NULL
3951 capath: object = NULL
3952 cadata: object = NULL
3953
3954[clinic start generated code]*/
3955
Antoine Pitrou152efa22010-05-16 18:19:27 +00003956static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003957_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3958 PyObject *cafile,
3959 PyObject *capath,
3960 PyObject *cadata)
3961/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003962{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003963 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3964 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003965 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003967 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003968 if (cafile == Py_None)
3969 cafile = NULL;
3970 if (capath == Py_None)
3971 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003972 if (cadata == Py_None)
3973 cadata = NULL;
3974
3975 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003977 "cafile, capath and cadata cannot be all omitted");
3978 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003979 }
3980 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3981 PyErr_SetString(PyExc_TypeError,
3982 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003983 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003984 }
3985 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003986 PyErr_SetString(PyExc_TypeError,
3987 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003988 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003989 }
Christian Heimesefff7062013-11-21 03:35:02 +01003990
3991 /* validata cadata type and load cadata */
3992 if (cadata) {
3993 Py_buffer buf;
3994 PyObject *cadata_ascii = NULL;
3995
3996 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3997 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3998 PyBuffer_Release(&buf);
3999 PyErr_SetString(PyExc_TypeError,
4000 "cadata should be a contiguous buffer with "
4001 "a single dimension");
4002 goto error;
4003 }
4004 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4005 PyBuffer_Release(&buf);
4006 if (r == -1) {
4007 goto error;
4008 }
4009 } else {
4010 PyErr_Clear();
4011 cadata_ascii = PyUnicode_AsASCIIString(cadata);
4012 if (cadata_ascii == NULL) {
4013 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004014 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01004015 "bytes-like object");
4016 goto error;
4017 }
4018 r = _add_ca_certs(self,
4019 PyBytes_AS_STRING(cadata_ascii),
4020 PyBytes_GET_SIZE(cadata_ascii),
4021 SSL_FILETYPE_PEM);
4022 Py_DECREF(cadata_ascii);
4023 if (r == -1) {
4024 goto error;
4025 }
4026 }
4027 }
4028
4029 /* load cafile or capath */
4030 if (cafile || capath) {
4031 if (cafile)
4032 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4033 if (capath)
4034 capath_buf = PyBytes_AS_STRING(capath_bytes);
4035 PySSL_BEGIN_ALLOW_THREADS
4036 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4037 PySSL_END_ALLOW_THREADS
4038 if (r != 1) {
4039 ok = 0;
4040 if (errno != 0) {
4041 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004042 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004043 }
4044 else {
4045 _setSSLError(NULL, 0, __FILE__, __LINE__);
4046 }
4047 goto error;
4048 }
4049 }
4050 goto end;
4051
4052 error:
4053 ok = 0;
4054 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004055 Py_XDECREF(cafile_bytes);
4056 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004057 if (ok) {
4058 Py_RETURN_NONE;
4059 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004060 return NULL;
4061 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004062}
4063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004064/*[clinic input]
4065_ssl._SSLContext.load_dh_params
4066 path as filepath: object
4067 /
4068
4069[clinic start generated code]*/
4070
Antoine Pitrou152efa22010-05-16 18:19:27 +00004071static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004072_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4073/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004074{
4075 FILE *f;
4076 DH *dh;
4077
Victor Stinnerdaf45552013-08-28 00:53:59 +02004078 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004079 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004080 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004081
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004082 errno = 0;
4083 PySSL_BEGIN_ALLOW_THREADS
4084 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004085 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004086 PySSL_END_ALLOW_THREADS
4087 if (dh == NULL) {
4088 if (errno != 0) {
4089 ERR_clear_error();
4090 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4091 }
4092 else {
4093 _setSSLError(NULL, 0, __FILE__, __LINE__);
4094 }
4095 return NULL;
4096 }
4097 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4098 _setSSLError(NULL, 0, __FILE__, __LINE__);
4099 DH_free(dh);
4100 Py_RETURN_NONE;
4101}
4102
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004103/*[clinic input]
4104_ssl._SSLContext._wrap_socket
4105 sock: object(subclass_of="PySocketModule.Sock_Type")
4106 server_side: int
4107 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004108 *
4109 owner: object = None
4110 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004111
4112[clinic start generated code]*/
4113
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004114static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004115_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004116 int server_side, PyObject *hostname_obj,
4117 PyObject *owner, PyObject *session)
4118/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004119{
Antoine Pitroud5323212010-10-22 18:19:07 +00004120 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004121 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004122
Antoine Pitroud5323212010-10-22 18:19:07 +00004123 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004124 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004126 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004127 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004128 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004129
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4131 server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004132 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004133 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004134 if (hostname != NULL)
4135 PyMem_Free(hostname);
4136 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004137}
4138
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004139/*[clinic input]
4140_ssl._SSLContext._wrap_bio
4141 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4142 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4143 server_side: int
4144 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004145 *
4146 owner: object = None
4147 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004148
4149[clinic start generated code]*/
4150
Antoine Pitroub0182c82010-10-12 20:09:02 +00004151static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004152_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4153 PySSLMemoryBIO *outgoing, int server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004154 PyObject *hostname_obj, PyObject *owner,
4155 PyObject *session)
4156/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004157{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004158 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004160
4161 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004162 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004163 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004164 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004165 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004166 }
4167
4168 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004169 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004170 incoming, outgoing);
4171
4172 PyMem_Free(hostname);
4173 return res;
4174}
4175
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004176/*[clinic input]
4177_ssl._SSLContext.session_stats
4178[clinic start generated code]*/
4179
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004180static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4182/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004183{
4184 int r;
4185 PyObject *value, *stats = PyDict_New();
4186 if (!stats)
4187 return NULL;
4188
4189#define ADD_STATS(SSL_NAME, KEY_NAME) \
4190 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4191 if (value == NULL) \
4192 goto error; \
4193 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4194 Py_DECREF(value); \
4195 if (r < 0) \
4196 goto error;
4197
4198 ADD_STATS(number, "number");
4199 ADD_STATS(connect, "connect");
4200 ADD_STATS(connect_good, "connect_good");
4201 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4202 ADD_STATS(accept, "accept");
4203 ADD_STATS(accept_good, "accept_good");
4204 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4205 ADD_STATS(accept, "accept");
4206 ADD_STATS(hits, "hits");
4207 ADD_STATS(misses, "misses");
4208 ADD_STATS(timeouts, "timeouts");
4209 ADD_STATS(cache_full, "cache_full");
4210
4211#undef ADD_STATS
4212
4213 return stats;
4214
4215error:
4216 Py_DECREF(stats);
4217 return NULL;
4218}
4219
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004220/*[clinic input]
4221_ssl._SSLContext.set_default_verify_paths
4222[clinic start generated code]*/
4223
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004224static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004225_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4226/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004227{
4228 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4229 _setSSLError(NULL, 0, __FILE__, __LINE__);
4230 return NULL;
4231 }
4232 Py_RETURN_NONE;
4233}
4234
Antoine Pitrou501da612011-12-21 09:27:41 +01004235#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004236/*[clinic input]
4237_ssl._SSLContext.set_ecdh_curve
4238 name: object
4239 /
4240
4241[clinic start generated code]*/
4242
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004243static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004244_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4245/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004246{
4247 PyObject *name_bytes;
4248 int nid;
4249 EC_KEY *key;
4250
4251 if (!PyUnicode_FSConverter(name, &name_bytes))
4252 return NULL;
4253 assert(PyBytes_Check(name_bytes));
4254 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4255 Py_DECREF(name_bytes);
4256 if (nid == 0) {
4257 PyErr_Format(PyExc_ValueError,
4258 "unknown elliptic curve name %R", name);
4259 return NULL;
4260 }
4261 key = EC_KEY_new_by_curve_name(nid);
4262 if (key == NULL) {
4263 _setSSLError(NULL, 0, __FILE__, __LINE__);
4264 return NULL;
4265 }
4266 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4267 EC_KEY_free(key);
4268 Py_RETURN_NONE;
4269}
Antoine Pitrou501da612011-12-21 09:27:41 +01004270#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004271
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004272#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004273static int
4274_servername_callback(SSL *s, int *al, void *args)
4275{
4276 int ret;
4277 PySSLContext *ssl_ctx = (PySSLContext *) args;
4278 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004279 PyObject *result;
4280 /* The high-level ssl.SSLSocket object */
4281 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004282 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004283 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004284
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004285 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004286 /* remove race condition in this the call back while if removing the
4287 * callback is in progress */
4288 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004289 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004290 }
4291
4292 ssl = SSL_get_app_data(s);
4293 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004294
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004295 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004296 * SSL connection and that has a .context attribute that can be changed to
4297 * identify the requested hostname. Since the official API is the Python
4298 * level API we want to pass the callback a Python level object rather than
4299 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4300 * SSLObject) that will be passed. Otherwise if there's a socket then that
4301 * will be passed. If both do not exist only then the C-level object is
4302 * passed. */
4303 if (ssl->owner)
4304 ssl_socket = PyWeakref_GetObject(ssl->owner);
4305 else if (ssl->Socket)
4306 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4307 else
4308 ssl_socket = (PyObject *) ssl;
4309
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004310 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004311 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004312 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004313
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004314 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004315 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004316 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004317 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004318 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004319 PyObject *servername_bytes;
4320 PyObject *servername_str;
4321
4322 servername_bytes = PyBytes_FromString(servername);
4323 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004324 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4325 goto error;
4326 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004327 /* server_hostname was encoded to an A-label by our caller; put it
4328 * back into a str object, but still as an A-label (bpo-28414)
4329 */
4330 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4331 Py_DECREF(servername_bytes);
4332 if (servername_str == NULL) {
4333 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004334 goto error;
4335 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004336 result = PyObject_CallFunctionObjArgs(
4337 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4338 ssl_ctx, NULL);
4339 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004340 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004341 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004342
4343 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004344 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004345 *al = SSL_AD_HANDSHAKE_FAILURE;
4346 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4347 }
4348 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004349 /* Result may be None, a SSLContext or an integer
4350 * None and SSLContext are OK, integer or other values are an error.
4351 */
4352 if (result == Py_None) {
4353 ret = SSL_TLSEXT_ERR_OK;
4354 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004355 *al = (int) PyLong_AsLong(result);
4356 if (PyErr_Occurred()) {
4357 PyErr_WriteUnraisable(result);
4358 *al = SSL_AD_INTERNAL_ERROR;
4359 }
4360 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4361 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004362 Py_DECREF(result);
4363 }
4364
4365 PyGILState_Release(gstate);
4366 return ret;
4367
4368error:
4369 Py_DECREF(ssl_socket);
4370 *al = SSL_AD_INTERNAL_ERROR;
4371 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4372 PyGILState_Release(gstate);
4373 return ret;
4374}
Antoine Pitroua5963382013-03-30 16:39:00 +01004375#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004376
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004377static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004378get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004379{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004380 PyObject *cb = self->set_sni_cb;
4381 if (cb == NULL) {
4382 Py_RETURN_NONE;
4383 }
4384 Py_INCREF(cb);
4385 return cb;
4386}
4387
4388static int
4389set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4390{
4391 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4392 PyErr_SetString(PyExc_ValueError,
4393 "sni_callback cannot be set on TLS_CLIENT context");
4394 return -1;
4395 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004396#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004397 Py_CLEAR(self->set_sni_cb);
4398 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004399 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4400 }
4401 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004402 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004403 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4404 PyErr_SetString(PyExc_TypeError,
4405 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004406 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004407 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004408 Py_INCREF(arg);
4409 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004410 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4411 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4412 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004413 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004414#else
4415 PyErr_SetString(PyExc_NotImplementedError,
4416 "The TLS extension servername callback, "
4417 "SSL_CTX_set_tlsext_servername_callback, "
4418 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004419 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004420#endif
4421}
4422
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004423PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4424"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4425\n\
4426If the argument is None then the callback is disabled. The method is called\n\
4427with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4428See RFC 6066 for details of the SNI extension.");
4429
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004430/*[clinic input]
4431_ssl._SSLContext.cert_store_stats
4432
4433Returns quantities of loaded X.509 certificates.
4434
4435X.509 certificates with a CA extension and certificate revocation lists
4436inside the context's cert store.
4437
4438NOTE: Certificates in a capath directory aren't loaded unless they have
4439been used at least once.
4440[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004441
4442static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004443_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4444/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004445{
4446 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004447 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004448 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004449 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004450
4451 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004452 objs = X509_STORE_get0_objects(store);
4453 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4454 obj = sk_X509_OBJECT_value(objs, i);
4455 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004456 case X509_LU_X509:
4457 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004458 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004459 ca++;
4460 }
4461 break;
4462 case X509_LU_CRL:
4463 crl++;
4464 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004465 default:
4466 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4467 * As far as I can tell they are internal states and never
4468 * stored in a cert store */
4469 break;
4470 }
4471 }
4472 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4473 "x509_ca", ca);
4474}
4475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004476/*[clinic input]
4477_ssl._SSLContext.get_ca_certs
4478 binary_form: bool = False
4479
4480Returns a list of dicts with information of loaded CA certs.
4481
4482If the optional argument is True, returns a DER-encoded copy of the CA
4483certificate.
4484
4485NOTE: Certificates in a capath directory aren't loaded unless they have
4486been used at least once.
4487[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004488
4489static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004490_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4491/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004492{
4493 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004494 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004495 PyObject *ci = NULL, *rlist = NULL;
4496 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004497
4498 if ((rlist = PyList_New(0)) == NULL) {
4499 return NULL;
4500 }
4501
4502 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004503 objs = X509_STORE_get0_objects(store);
4504 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004505 X509_OBJECT *obj;
4506 X509 *cert;
4507
Christian Heimes598894f2016-09-05 23:19:05 +02004508 obj = sk_X509_OBJECT_value(objs, i);
4509 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004510 /* not a x509 cert */
4511 continue;
4512 }
4513 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004514 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004515 if (!X509_check_ca(cert)) {
4516 continue;
4517 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004518 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004519 ci = _certificate_to_der(cert);
4520 } else {
4521 ci = _decode_certificate(cert);
4522 }
4523 if (ci == NULL) {
4524 goto error;
4525 }
4526 if (PyList_Append(rlist, ci) == -1) {
4527 goto error;
4528 }
4529 Py_CLEAR(ci);
4530 }
4531 return rlist;
4532
4533 error:
4534 Py_XDECREF(ci);
4535 Py_XDECREF(rlist);
4536 return NULL;
4537}
4538
4539
Antoine Pitrou152efa22010-05-16 18:19:27 +00004540static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004541 {"check_hostname", (getter) get_check_hostname,
4542 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004543 {"_host_flags", (getter) get_host_flags,
4544 (setter) set_host_flags, NULL},
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004545#if SSL_CTRL_GET_MAX_PROTO_VERSION
4546 {"minimum_version", (getter) get_minimum_version,
4547 (setter) set_minimum_version, NULL},
4548 {"maximum_version", (getter) get_maximum_version,
4549 (setter) set_maximum_version, NULL},
4550#endif
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004551 {"sni_callback", (getter) get_sni_callback,
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004552 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004553 {"options", (getter) get_options,
4554 (setter) set_options, NULL},
Christian Heimes2756ef32018-09-23 09:22:52 +02004555 {"post_handshake_auth", (getter) get_post_handshake_auth,
4556#ifdef TLS1_3_VERSION
4557 (setter) set_post_handshake_auth,
4558#else
4559 NULL,
4560#endif
4561 NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004562 {"protocol", (getter) get_protocol,
4563 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004564 {"verify_flags", (getter) get_verify_flags,
4565 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004566 {"verify_mode", (getter) get_verify_mode,
4567 (setter) set_verify_mode, NULL},
4568 {NULL}, /* sentinel */
4569};
4570
4571static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004572 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4573 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4574 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4575 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4576 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4577 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4578 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4579 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4580 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4581 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4582 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004583 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4584 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004585 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004586 {NULL, NULL} /* sentinel */
4587};
4588
4589static PyTypeObject PySSLContext_Type = {
4590 PyVarObject_HEAD_INIT(NULL, 0)
4591 "_ssl._SSLContext", /*tp_name*/
4592 sizeof(PySSLContext), /*tp_basicsize*/
4593 0, /*tp_itemsize*/
4594 (destructor)context_dealloc, /*tp_dealloc*/
4595 0, /*tp_print*/
4596 0, /*tp_getattr*/
4597 0, /*tp_setattr*/
4598 0, /*tp_reserved*/
4599 0, /*tp_repr*/
4600 0, /*tp_as_number*/
4601 0, /*tp_as_sequence*/
4602 0, /*tp_as_mapping*/
4603 0, /*tp_hash*/
4604 0, /*tp_call*/
4605 0, /*tp_str*/
4606 0, /*tp_getattro*/
4607 0, /*tp_setattro*/
4608 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004609 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004610 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004611 (traverseproc) context_traverse, /*tp_traverse*/
4612 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004613 0, /*tp_richcompare*/
4614 0, /*tp_weaklistoffset*/
4615 0, /*tp_iter*/
4616 0, /*tp_iternext*/
4617 context_methods, /*tp_methods*/
4618 0, /*tp_members*/
4619 context_getsetlist, /*tp_getset*/
4620 0, /*tp_base*/
4621 0, /*tp_dict*/
4622 0, /*tp_descr_get*/
4623 0, /*tp_descr_set*/
4624 0, /*tp_dictoffset*/
4625 0, /*tp_init*/
4626 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004627 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004628};
4629
4630
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004631/*
4632 * MemoryBIO objects
4633 */
4634
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004635/*[clinic input]
4636@classmethod
4637_ssl.MemoryBIO.__new__
4638
4639[clinic start generated code]*/
4640
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004641static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004642_ssl_MemoryBIO_impl(PyTypeObject *type)
4643/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004644{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004645 BIO *bio;
4646 PySSLMemoryBIO *self;
4647
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004648 bio = BIO_new(BIO_s_mem());
4649 if (bio == NULL) {
4650 PyErr_SetString(PySSLErrorObject,
4651 "failed to allocate BIO");
4652 return NULL;
4653 }
4654 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4655 * just that no data is currently available. The SSL routines should retry
4656 * the read, which we can achieve by calling BIO_set_retry_read(). */
4657 BIO_set_retry_read(bio);
4658 BIO_set_mem_eof_return(bio, -1);
4659
4660 assert(type != NULL && type->tp_alloc != NULL);
4661 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4662 if (self == NULL) {
4663 BIO_free(bio);
4664 return NULL;
4665 }
4666 self->bio = bio;
4667 self->eof_written = 0;
4668
4669 return (PyObject *) self;
4670}
4671
4672static void
4673memory_bio_dealloc(PySSLMemoryBIO *self)
4674{
4675 BIO_free(self->bio);
4676 Py_TYPE(self)->tp_free(self);
4677}
4678
4679static PyObject *
4680memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4681{
Segev Finer5cff6372017-07-27 01:19:17 +03004682 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004683}
4684
4685PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4686"The number of bytes pending in the memory BIO.");
4687
4688static PyObject *
4689memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4690{
4691 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4692 && self->eof_written);
4693}
4694
4695PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4696"Whether the memory BIO is at EOF.");
4697
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004698/*[clinic input]
4699_ssl.MemoryBIO.read
4700 size as len: int = -1
4701 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004702
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004703Read up to size bytes from the memory BIO.
4704
4705If size is not specified, read the entire buffer.
4706If the return value is an empty bytes instance, this means either
4707EOF or that no data is available. Use the "eof" property to
4708distinguish between the two.
4709[clinic start generated code]*/
4710
4711static PyObject *
4712_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4713/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4714{
4715 int avail, nbytes;
4716 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004717
Segev Finer5cff6372017-07-27 01:19:17 +03004718 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004719 if ((len < 0) || (len > avail))
4720 len = avail;
4721
4722 result = PyBytes_FromStringAndSize(NULL, len);
4723 if ((result == NULL) || (len == 0))
4724 return result;
4725
4726 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004727 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004728 Py_DECREF(result);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004729 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004730 return NULL;
4731 }
4732
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004733 /* There should never be any short reads but check anyway. */
4734 if (nbytes < len) {
4735 _PyBytes_Resize(&result, nbytes);
4736 }
4737
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004738 return result;
4739}
4740
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004741/*[clinic input]
4742_ssl.MemoryBIO.write
4743 b: Py_buffer
4744 /
4745
4746Writes the bytes b into the memory BIO.
4747
4748Returns the number of bytes written.
4749[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004750
4751static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004752_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4753/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004754{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004755 int nbytes;
4756
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004757 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004758 PyErr_Format(PyExc_OverflowError,
4759 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004760 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004761 }
4762
4763 if (self->eof_written) {
4764 PyErr_SetString(PySSLErrorObject,
4765 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004766 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004767 }
4768
Segev Finer5cff6372017-07-27 01:19:17 +03004769 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004770 if (nbytes < 0) {
4771 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004772 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004773 }
4774
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004775 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004776}
4777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004778/*[clinic input]
4779_ssl.MemoryBIO.write_eof
4780
4781Write an EOF marker to the memory BIO.
4782
4783When all data has been read, the "eof" property will be True.
4784[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004785
4786static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004787_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4788/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004789{
4790 self->eof_written = 1;
4791 /* After an EOF is written, a zero return from read() should be a real EOF
4792 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4793 BIO_clear_retry_flags(self->bio);
4794 BIO_set_mem_eof_return(self->bio, 0);
4795
4796 Py_RETURN_NONE;
4797}
4798
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004799static PyGetSetDef memory_bio_getsetlist[] = {
4800 {"pending", (getter) memory_bio_get_pending, NULL,
4801 PySSL_memory_bio_pending_doc},
4802 {"eof", (getter) memory_bio_get_eof, NULL,
4803 PySSL_memory_bio_eof_doc},
4804 {NULL}, /* sentinel */
4805};
4806
4807static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004808 _SSL_MEMORYBIO_READ_METHODDEF
4809 _SSL_MEMORYBIO_WRITE_METHODDEF
4810 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004811 {NULL, NULL} /* sentinel */
4812};
4813
4814static PyTypeObject PySSLMemoryBIO_Type = {
4815 PyVarObject_HEAD_INIT(NULL, 0)
4816 "_ssl.MemoryBIO", /*tp_name*/
4817 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4818 0, /*tp_itemsize*/
4819 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4820 0, /*tp_print*/
4821 0, /*tp_getattr*/
4822 0, /*tp_setattr*/
4823 0, /*tp_reserved*/
4824 0, /*tp_repr*/
4825 0, /*tp_as_number*/
4826 0, /*tp_as_sequence*/
4827 0, /*tp_as_mapping*/
4828 0, /*tp_hash*/
4829 0, /*tp_call*/
4830 0, /*tp_str*/
4831 0, /*tp_getattro*/
4832 0, /*tp_setattro*/
4833 0, /*tp_as_buffer*/
4834 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4835 0, /*tp_doc*/
4836 0, /*tp_traverse*/
4837 0, /*tp_clear*/
4838 0, /*tp_richcompare*/
4839 0, /*tp_weaklistoffset*/
4840 0, /*tp_iter*/
4841 0, /*tp_iternext*/
4842 memory_bio_methods, /*tp_methods*/
4843 0, /*tp_members*/
4844 memory_bio_getsetlist, /*tp_getset*/
4845 0, /*tp_base*/
4846 0, /*tp_dict*/
4847 0, /*tp_descr_get*/
4848 0, /*tp_descr_set*/
4849 0, /*tp_dictoffset*/
4850 0, /*tp_init*/
4851 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004852 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004853};
4854
Antoine Pitrou152efa22010-05-16 18:19:27 +00004855
Christian Heimes99a65702016-09-10 23:44:53 +02004856/*
4857 * SSL Session object
4858 */
4859
4860static void
4861PySSLSession_dealloc(PySSLSession *self)
4862{
INADA Naokia6296d32017-08-24 14:55:17 +09004863 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004864 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004865 Py_XDECREF(self->ctx);
4866 if (self->session != NULL) {
4867 SSL_SESSION_free(self->session);
4868 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004869 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004870}
4871
4872static PyObject *
4873PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4874{
4875 int result;
4876
4877 if (left == NULL || right == NULL) {
4878 PyErr_BadInternalCall();
4879 return NULL;
4880 }
4881
4882 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4883 Py_RETURN_NOTIMPLEMENTED;
4884 }
4885
4886 if (left == right) {
4887 result = 0;
4888 } else {
4889 const unsigned char *left_id, *right_id;
4890 unsigned int left_len, right_len;
4891 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4892 &left_len);
4893 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4894 &right_len);
4895 if (left_len == right_len) {
4896 result = memcmp(left_id, right_id, left_len);
4897 } else {
4898 result = 1;
4899 }
4900 }
4901
4902 switch (op) {
4903 case Py_EQ:
4904 if (result == 0) {
4905 Py_RETURN_TRUE;
4906 } else {
4907 Py_RETURN_FALSE;
4908 }
4909 break;
4910 case Py_NE:
4911 if (result != 0) {
4912 Py_RETURN_TRUE;
4913 } else {
4914 Py_RETURN_FALSE;
4915 }
4916 break;
4917 case Py_LT:
4918 case Py_LE:
4919 case Py_GT:
4920 case Py_GE:
4921 Py_RETURN_NOTIMPLEMENTED;
4922 break;
4923 default:
4924 PyErr_BadArgument();
4925 return NULL;
4926 }
4927}
4928
4929static int
4930PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4931{
4932 Py_VISIT(self->ctx);
4933 return 0;
4934}
4935
4936static int
4937PySSLSession_clear(PySSLSession *self)
4938{
4939 Py_CLEAR(self->ctx);
4940 return 0;
4941}
4942
4943
4944static PyObject *
4945PySSLSession_get_time(PySSLSession *self, void *closure) {
4946 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4947}
4948
4949PyDoc_STRVAR(PySSLSession_get_time_doc,
4950"Session creation time (seconds since epoch).");
4951
4952
4953static PyObject *
4954PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4955 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4956}
4957
4958PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4959"Session timeout (delta in seconds).");
4960
4961
4962static PyObject *
4963PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4964 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4965 return PyLong_FromUnsignedLong(hint);
4966}
4967
4968PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4969"Ticket life time hint.");
4970
4971
4972static PyObject *
4973PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4974 const unsigned char *id;
4975 unsigned int len;
4976 id = SSL_SESSION_get_id(self->session, &len);
4977 return PyBytes_FromStringAndSize((const char *)id, len);
4978}
4979
4980PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4981"Session id");
4982
4983
4984static PyObject *
4985PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4986 if (SSL_SESSION_has_ticket(self->session)) {
4987 Py_RETURN_TRUE;
4988 } else {
4989 Py_RETURN_FALSE;
4990 }
4991}
4992
4993PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4994"Does the session contain a ticket?");
4995
4996
4997static PyGetSetDef PySSLSession_getsetlist[] = {
4998 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4999 PySSLSession_get_has_ticket_doc},
5000 {"id", (getter) PySSLSession_get_session_id, NULL,
5001 PySSLSession_get_session_id_doc},
5002 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5003 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5004 {"time", (getter) PySSLSession_get_time, NULL,
5005 PySSLSession_get_time_doc},
5006 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5007 PySSLSession_get_timeout_doc},
5008 {NULL}, /* sentinel */
5009};
5010
5011static PyTypeObject PySSLSession_Type = {
5012 PyVarObject_HEAD_INIT(NULL, 0)
5013 "_ssl.Session", /*tp_name*/
5014 sizeof(PySSLSession), /*tp_basicsize*/
5015 0, /*tp_itemsize*/
5016 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
5017 0, /*tp_print*/
5018 0, /*tp_getattr*/
5019 0, /*tp_setattr*/
5020 0, /*tp_reserved*/
5021 0, /*tp_repr*/
5022 0, /*tp_as_number*/
5023 0, /*tp_as_sequence*/
5024 0, /*tp_as_mapping*/
5025 0, /*tp_hash*/
5026 0, /*tp_call*/
5027 0, /*tp_str*/
5028 0, /*tp_getattro*/
5029 0, /*tp_setattro*/
5030 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005031 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005032 0, /*tp_doc*/
5033 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5034 (inquiry)PySSLSession_clear, /*tp_clear*/
5035 PySSLSession_richcompare, /*tp_richcompare*/
5036 0, /*tp_weaklistoffset*/
5037 0, /*tp_iter*/
5038 0, /*tp_iternext*/
5039 0, /*tp_methods*/
5040 0, /*tp_members*/
5041 PySSLSession_getsetlist, /*tp_getset*/
5042};
5043
5044
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005045/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005046/*[clinic input]
5047_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005048 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005049 entropy: double
5050 /
5051
5052Mix string into the OpenSSL PRNG state.
5053
5054entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305055string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005056[clinic start generated code]*/
5057
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005058static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005059_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005060/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005061{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005062 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005063 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005064
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005065 buf = (const char *)view->buf;
5066 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005067 do {
5068 written = Py_MIN(len, INT_MAX);
5069 RAND_add(buf, (int)written, entropy);
5070 buf += written;
5071 len -= written;
5072 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005073 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005074}
5075
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005076static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005077PySSL_RAND(int len, int pseudo)
5078{
5079 int ok;
5080 PyObject *bytes;
5081 unsigned long err;
5082 const char *errstr;
5083 PyObject *v;
5084
Victor Stinner1e81a392013-12-19 16:47:04 +01005085 if (len < 0) {
5086 PyErr_SetString(PyExc_ValueError, "num must be positive");
5087 return NULL;
5088 }
5089
Victor Stinner99c8b162011-05-24 12:05:19 +02005090 bytes = PyBytes_FromStringAndSize(NULL, len);
5091 if (bytes == NULL)
5092 return NULL;
5093 if (pseudo) {
5094 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5095 if (ok == 0 || ok == 1)
5096 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5097 }
5098 else {
5099 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5100 if (ok == 1)
5101 return bytes;
5102 }
5103 Py_DECREF(bytes);
5104
5105 err = ERR_get_error();
5106 errstr = ERR_reason_error_string(err);
5107 v = Py_BuildValue("(ks)", err, errstr);
5108 if (v != NULL) {
5109 PyErr_SetObject(PySSLErrorObject, v);
5110 Py_DECREF(v);
5111 }
5112 return NULL;
5113}
5114
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005115/*[clinic input]
5116_ssl.RAND_bytes
5117 n: int
5118 /
5119
5120Generate n cryptographically strong pseudo-random bytes.
5121[clinic start generated code]*/
5122
Victor Stinner99c8b162011-05-24 12:05:19 +02005123static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005124_ssl_RAND_bytes_impl(PyObject *module, int n)
5125/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005126{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005127 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005128}
5129
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005130/*[clinic input]
5131_ssl.RAND_pseudo_bytes
5132 n: int
5133 /
5134
5135Generate n pseudo-random bytes.
5136
5137Return a pair (bytes, is_cryptographic). is_cryptographic is True
5138if the bytes generated are cryptographically strong.
5139[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005140
5141static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005142_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5143/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005144{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005145 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005146}
5147
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005148/*[clinic input]
5149_ssl.RAND_status
5150
5151Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5152
5153It is necessary to seed the PRNG with RAND_add() on some platforms before
5154using the ssl() function.
5155[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005156
5157static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005158_ssl_RAND_status_impl(PyObject *module)
5159/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005160{
Christian Heimes217cfd12007-12-02 14:31:20 +00005161 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005162}
5163
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005164#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005165/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005166/*[clinic input]
5167_ssl.RAND_egd
5168 path: object(converter="PyUnicode_FSConverter")
5169 /
5170
5171Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5172
5173Returns number of bytes read. Raises SSLError if connection to EGD
5174fails or if it does not provide enough data to seed PRNG.
5175[clinic start generated code]*/
5176
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005177static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005178_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5179/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005180{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005181 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005182 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005183 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005184 PyErr_SetString(PySSLErrorObject,
5185 "EGD connection failed or EGD did not return "
5186 "enough data to seed the PRNG");
5187 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005188 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005189 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005190}
Christian Heimesa5d07652016-09-24 10:48:05 +02005191/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005192#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005193
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005194
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005195
5196/*[clinic input]
5197_ssl.get_default_verify_paths
5198
5199Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5200
5201The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5202[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005203
5204static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005205_ssl_get_default_verify_paths_impl(PyObject *module)
5206/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005207{
5208 PyObject *ofile_env = NULL;
5209 PyObject *ofile = NULL;
5210 PyObject *odir_env = NULL;
5211 PyObject *odir = NULL;
5212
Benjamin Petersond113c962015-07-18 10:59:13 -07005213#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005214 const char *tmp = (info); \
5215 target = NULL; \
5216 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5217 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5218 target = PyBytes_FromString(tmp); } \
5219 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005220 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005221
Benjamin Petersond113c962015-07-18 10:59:13 -07005222 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5223 CONVERT(X509_get_default_cert_file(), ofile);
5224 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5225 CONVERT(X509_get_default_cert_dir(), odir);
5226#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005227
Christian Heimes200bb1b2013-06-14 15:14:29 +02005228 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005229
5230 error:
5231 Py_XDECREF(ofile_env);
5232 Py_XDECREF(ofile);
5233 Py_XDECREF(odir_env);
5234 Py_XDECREF(odir);
5235 return NULL;
5236}
5237
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005238static PyObject*
5239asn1obj2py(ASN1_OBJECT *obj)
5240{
5241 int nid;
5242 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005243
5244 nid = OBJ_obj2nid(obj);
5245 if (nid == NID_undef) {
5246 PyErr_Format(PyExc_ValueError, "Unknown object");
5247 return NULL;
5248 }
5249 sn = OBJ_nid2sn(nid);
5250 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005251 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005252}
5253
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005254/*[clinic input]
5255_ssl.txt2obj
5256 txt: str
5257 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005258
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005259Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5260
5261By default objects are looked up by OID. With name=True short and
5262long name are also matched.
5263[clinic start generated code]*/
5264
5265static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005266_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5267/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005268{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005269 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005270 ASN1_OBJECT *obj;
5271
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005272 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5273 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005274 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005275 return NULL;
5276 }
5277 result = asn1obj2py(obj);
5278 ASN1_OBJECT_free(obj);
5279 return result;
5280}
5281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005282/*[clinic input]
5283_ssl.nid2obj
5284 nid: int
5285 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005286
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005287Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5288[clinic start generated code]*/
5289
5290static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005291_ssl_nid2obj_impl(PyObject *module, int nid)
5292/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005293{
5294 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005295 ASN1_OBJECT *obj;
5296
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005297 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005298 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005299 return NULL;
5300 }
5301 obj = OBJ_nid2obj(nid);
5302 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005303 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005304 return NULL;
5305 }
5306 result = asn1obj2py(obj);
5307 ASN1_OBJECT_free(obj);
5308 return result;
5309}
5310
Christian Heimes46bebee2013-06-09 19:03:31 +02005311#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005312
5313static PyObject*
5314certEncodingType(DWORD encodingType)
5315{
5316 static PyObject *x509_asn = NULL;
5317 static PyObject *pkcs_7_asn = NULL;
5318
5319 if (x509_asn == NULL) {
5320 x509_asn = PyUnicode_InternFromString("x509_asn");
5321 if (x509_asn == NULL)
5322 return NULL;
5323 }
5324 if (pkcs_7_asn == NULL) {
5325 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5326 if (pkcs_7_asn == NULL)
5327 return NULL;
5328 }
5329 switch(encodingType) {
5330 case X509_ASN_ENCODING:
5331 Py_INCREF(x509_asn);
5332 return x509_asn;
5333 case PKCS_7_ASN_ENCODING:
5334 Py_INCREF(pkcs_7_asn);
5335 return pkcs_7_asn;
5336 default:
5337 return PyLong_FromLong(encodingType);
5338 }
5339}
5340
5341static PyObject*
5342parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5343{
5344 CERT_ENHKEY_USAGE *usage;
5345 DWORD size, error, i;
5346 PyObject *retval;
5347
5348 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5349 error = GetLastError();
5350 if (error == CRYPT_E_NOT_FOUND) {
5351 Py_RETURN_TRUE;
5352 }
5353 return PyErr_SetFromWindowsErr(error);
5354 }
5355
5356 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5357 if (usage == NULL) {
5358 return PyErr_NoMemory();
5359 }
5360
5361 /* Now get the actual enhanced usage property */
5362 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5363 PyMem_Free(usage);
5364 error = GetLastError();
5365 if (error == CRYPT_E_NOT_FOUND) {
5366 Py_RETURN_TRUE;
5367 }
5368 return PyErr_SetFromWindowsErr(error);
5369 }
5370 retval = PySet_New(NULL);
5371 if (retval == NULL) {
5372 goto error;
5373 }
5374 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5375 if (usage->rgpszUsageIdentifier[i]) {
5376 PyObject *oid;
5377 int err;
5378 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5379 if (oid == NULL) {
5380 Py_CLEAR(retval);
5381 goto error;
5382 }
5383 err = PySet_Add(retval, oid);
5384 Py_DECREF(oid);
5385 if (err == -1) {
5386 Py_CLEAR(retval);
5387 goto error;
5388 }
5389 }
5390 }
5391 error:
5392 PyMem_Free(usage);
5393 return retval;
5394}
5395
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005396/*[clinic input]
5397_ssl.enum_certificates
5398 store_name: str
5399
5400Retrieve certificates from Windows' cert store.
5401
5402store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5403more cert storages, too. The function returns a list of (bytes,
5404encoding_type, trust) tuples. The encoding_type flag can be interpreted
5405with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5406a set of OIDs or the boolean True.
5407[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005408
Christian Heimes46bebee2013-06-09 19:03:31 +02005409static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005410_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5411/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005412{
Christian Heimes46bebee2013-06-09 19:03:31 +02005413 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005414 PCCERT_CONTEXT pCertCtx = NULL;
5415 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005416 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005417
Christian Heimes44109d72013-11-22 01:51:30 +01005418 result = PyList_New(0);
5419 if (result == NULL) {
5420 return NULL;
5421 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005422 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5423 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5424 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005425 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005426 Py_DECREF(result);
5427 return PyErr_SetFromWindowsErr(GetLastError());
5428 }
5429
Christian Heimes44109d72013-11-22 01:51:30 +01005430 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5431 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5432 pCertCtx->cbCertEncoded);
5433 if (!cert) {
5434 Py_CLEAR(result);
5435 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005436 }
Christian Heimes44109d72013-11-22 01:51:30 +01005437 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5438 Py_CLEAR(result);
5439 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005440 }
Christian Heimes44109d72013-11-22 01:51:30 +01005441 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5442 if (keyusage == Py_True) {
5443 Py_DECREF(keyusage);
5444 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005445 }
Christian Heimes44109d72013-11-22 01:51:30 +01005446 if (keyusage == NULL) {
5447 Py_CLEAR(result);
5448 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005449 }
Christian Heimes44109d72013-11-22 01:51:30 +01005450 if ((tup = PyTuple_New(3)) == NULL) {
5451 Py_CLEAR(result);
5452 break;
5453 }
5454 PyTuple_SET_ITEM(tup, 0, cert);
5455 cert = NULL;
5456 PyTuple_SET_ITEM(tup, 1, enc);
5457 enc = NULL;
5458 PyTuple_SET_ITEM(tup, 2, keyusage);
5459 keyusage = NULL;
5460 if (PyList_Append(result, tup) < 0) {
5461 Py_CLEAR(result);
5462 break;
5463 }
5464 Py_CLEAR(tup);
5465 }
5466 if (pCertCtx) {
5467 /* loop ended with an error, need to clean up context manually */
5468 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005469 }
5470
5471 /* In error cases cert, enc and tup may not be NULL */
5472 Py_XDECREF(cert);
5473 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005474 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005475 Py_XDECREF(tup);
5476
5477 if (!CertCloseStore(hStore, 0)) {
5478 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005479 Py_XDECREF(result);
5480 return PyErr_SetFromWindowsErr(GetLastError());
5481 }
5482 return result;
5483}
5484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005485/*[clinic input]
5486_ssl.enum_crls
5487 store_name: str
5488
5489Retrieve CRLs from Windows' cert store.
5490
5491store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5492more cert storages, too. The function returns a list of (bytes,
5493encoding_type) tuples. The encoding_type flag can be interpreted with
5494X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5495[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005496
5497static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005498_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5499/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005500{
Christian Heimes44109d72013-11-22 01:51:30 +01005501 HCERTSTORE hStore = NULL;
5502 PCCRL_CONTEXT pCrlCtx = NULL;
5503 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5504 PyObject *result = NULL;
5505
Christian Heimes44109d72013-11-22 01:51:30 +01005506 result = PyList_New(0);
5507 if (result == NULL) {
5508 return NULL;
5509 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005510 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5511 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5512 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005513 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005514 Py_DECREF(result);
5515 return PyErr_SetFromWindowsErr(GetLastError());
5516 }
Christian Heimes44109d72013-11-22 01:51:30 +01005517
5518 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5519 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5520 pCrlCtx->cbCrlEncoded);
5521 if (!crl) {
5522 Py_CLEAR(result);
5523 break;
5524 }
5525 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5526 Py_CLEAR(result);
5527 break;
5528 }
5529 if ((tup = PyTuple_New(2)) == NULL) {
5530 Py_CLEAR(result);
5531 break;
5532 }
5533 PyTuple_SET_ITEM(tup, 0, crl);
5534 crl = NULL;
5535 PyTuple_SET_ITEM(tup, 1, enc);
5536 enc = NULL;
5537
5538 if (PyList_Append(result, tup) < 0) {
5539 Py_CLEAR(result);
5540 break;
5541 }
5542 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005543 }
Christian Heimes44109d72013-11-22 01:51:30 +01005544 if (pCrlCtx) {
5545 /* loop ended with an error, need to clean up context manually */
5546 CertFreeCRLContext(pCrlCtx);
5547 }
5548
5549 /* In error cases cert, enc and tup may not be NULL */
5550 Py_XDECREF(crl);
5551 Py_XDECREF(enc);
5552 Py_XDECREF(tup);
5553
5554 if (!CertCloseStore(hStore, 0)) {
5555 /* This error case might shadow another exception.*/
5556 Py_XDECREF(result);
5557 return PyErr_SetFromWindowsErr(GetLastError());
5558 }
5559 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005560}
Christian Heimes44109d72013-11-22 01:51:30 +01005561
5562#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005563
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005564/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005565static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005566 _SSL__TEST_DECODE_CERT_METHODDEF
5567 _SSL_RAND_ADD_METHODDEF
5568 _SSL_RAND_BYTES_METHODDEF
5569 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5570 _SSL_RAND_EGD_METHODDEF
5571 _SSL_RAND_STATUS_METHODDEF
5572 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5573 _SSL_ENUM_CERTIFICATES_METHODDEF
5574 _SSL_ENUM_CRLS_METHODDEF
5575 _SSL_TXT2OBJ_METHODDEF
5576 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005577 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005578};
5579
5580
Christian Heimes598894f2016-09-05 23:19:05 +02005581#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005582
5583/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005584 * of the Python C thread library
5585 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5586 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005587
5588static PyThread_type_lock *_ssl_locks = NULL;
5589
Christian Heimes4d98ca92013-08-19 17:36:29 +02005590#if OPENSSL_VERSION_NUMBER >= 0x10000000
5591/* use new CRYPTO_THREADID API. */
5592static void
5593_ssl_threadid_callback(CRYPTO_THREADID *id)
5594{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005595 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005596}
5597#else
5598/* deprecated CRYPTO_set_id_callback() API. */
5599static unsigned long
5600_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005601 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005602}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005603#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005604
Bill Janssen6e027db2007-11-15 22:23:56 +00005605static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005606 (int mode, int n, const char *file, int line) {
5607 /* this function is needed to perform locking on shared data
5608 structures. (Note that OpenSSL uses a number of global data
5609 structures that will be implicitly shared whenever multiple
5610 threads use OpenSSL.) Multi-threaded applications will
5611 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005613 locking_function() must be able to handle up to
5614 CRYPTO_num_locks() different mutex locks. It sets the n-th
5615 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005617 file and line are the file number of the function setting the
5618 lock. They can be useful for debugging.
5619 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005621 if ((_ssl_locks == NULL) ||
5622 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5623 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005625 if (mode & CRYPTO_LOCK) {
5626 PyThread_acquire_lock(_ssl_locks[n], 1);
5627 } else {
5628 PyThread_release_lock(_ssl_locks[n]);
5629 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005630}
5631
5632static int _setup_ssl_threads(void) {
5633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005634 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005636 if (_ssl_locks == NULL) {
5637 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005638 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5639 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005640 if (_ssl_locks == NULL) {
5641 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005642 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005643 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005644 for (i = 0; i < _ssl_locks_count; i++) {
5645 _ssl_locks[i] = PyThread_allocate_lock();
5646 if (_ssl_locks[i] == NULL) {
5647 unsigned int j;
5648 for (j = 0; j < i; j++) {
5649 PyThread_free_lock(_ssl_locks[j]);
5650 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005651 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005652 return 0;
5653 }
5654 }
5655 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005656#if OPENSSL_VERSION_NUMBER >= 0x10000000
5657 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5658#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005659 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005660#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005661 }
5662 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005663}
5664
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005665#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005666
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005667PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005668"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005669for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005670
Martin v. Löwis1a214512008-06-11 05:26:20 +00005671
5672static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005673 PyModuleDef_HEAD_INIT,
5674 "_ssl",
5675 module_doc,
5676 -1,
5677 PySSL_methods,
5678 NULL,
5679 NULL,
5680 NULL,
5681 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005682};
5683
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005684
5685static void
5686parse_openssl_version(unsigned long libver,
5687 unsigned int *major, unsigned int *minor,
5688 unsigned int *fix, unsigned int *patch,
5689 unsigned int *status)
5690{
5691 *status = libver & 0xF;
5692 libver >>= 4;
5693 *patch = libver & 0xFF;
5694 libver >>= 8;
5695 *fix = libver & 0xFF;
5696 libver >>= 8;
5697 *minor = libver & 0xFF;
5698 libver >>= 8;
5699 *major = libver & 0xFF;
5700}
5701
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005702PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005703PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005704{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005705 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005706 unsigned long libver;
5707 unsigned int major, minor, fix, patch, status;
5708 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005709 struct py_ssl_error_code *errcode;
5710 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005711
Antoine Pitrou152efa22010-05-16 18:19:27 +00005712 if (PyType_Ready(&PySSLContext_Type) < 0)
5713 return NULL;
5714 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005715 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005716 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5717 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005718 if (PyType_Ready(&PySSLSession_Type) < 0)
5719 return NULL;
5720
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005722 m = PyModule_Create(&_sslmodule);
5723 if (m == NULL)
5724 return NULL;
5725 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005726
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005727 /* Load _socket module and its C API */
5728 socket_api = PySocketModule_ImportModuleAndAPI();
5729 if (!socket_api)
5730 return NULL;
5731 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005732
Christian Heimesc941e622017-09-05 15:47:11 +02005733#ifndef OPENSSL_VERSION_1_1
5734 /* Load all algorithms and initialize cpuid */
5735 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005736 /* Init OpenSSL */
5737 SSL_load_error_strings();
5738 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005739#endif
5740
Christian Heimes598894f2016-09-05 23:19:05 +02005741#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005742 /* note that this will start threading if not already started */
5743 if (!_setup_ssl_threads()) {
5744 return NULL;
5745 }
Christian Heimes598894f2016-09-05 23:19:05 +02005746#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5747 /* OpenSSL 1.1.0 builtin thread support is enabled */
5748 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005749#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005751 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005752 sslerror_type_slots[0].pfunc = PyExc_OSError;
5753 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005754 if (PySSLErrorObject == NULL)
5755 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005756
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005757 /* ssl.CertificateError used to be a subclass of ValueError */
5758 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5759 if (bases == NULL)
5760 return NULL;
5761 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5762 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5763 bases, NULL);
5764 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005765 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5766 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5767 PySSLErrorObject, NULL);
5768 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5769 "ssl.SSLWantReadError", SSLWantReadError_doc,
5770 PySSLErrorObject, NULL);
5771 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5772 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5773 PySSLErrorObject, NULL);
5774 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5775 "ssl.SSLSyscallError", SSLSyscallError_doc,
5776 PySSLErrorObject, NULL);
5777 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5778 "ssl.SSLEOFError", SSLEOFError_doc,
5779 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005780 if (PySSLCertVerificationErrorObject == NULL
5781 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005782 || PySSLWantReadErrorObject == NULL
5783 || PySSLWantWriteErrorObject == NULL
5784 || PySSLSyscallErrorObject == NULL
5785 || PySSLEOFErrorObject == NULL)
5786 return NULL;
5787 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005788 || PyDict_SetItemString(d, "SSLCertVerificationError",
5789 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005790 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5791 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5792 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5793 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5794 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005795 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005796 if (PyDict_SetItemString(d, "_SSLContext",
5797 (PyObject *)&PySSLContext_Type) != 0)
5798 return NULL;
5799 if (PyDict_SetItemString(d, "_SSLSocket",
5800 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005801 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005802 if (PyDict_SetItemString(d, "MemoryBIO",
5803 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5804 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005805 if (PyDict_SetItemString(d, "SSLSession",
5806 (PyObject *)&PySSLSession_Type) != 0)
5807 return NULL;
5808
Christian Heimes892d66e2018-01-29 14:10:18 +01005809 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5810 PY_SSL_DEFAULT_CIPHER_STRING);
5811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005812 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5813 PY_SSL_ERROR_ZERO_RETURN);
5814 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5815 PY_SSL_ERROR_WANT_READ);
5816 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5817 PY_SSL_ERROR_WANT_WRITE);
5818 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5819 PY_SSL_ERROR_WANT_X509_LOOKUP);
5820 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5821 PY_SSL_ERROR_SYSCALL);
5822 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5823 PY_SSL_ERROR_SSL);
5824 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5825 PY_SSL_ERROR_WANT_CONNECT);
5826 /* non ssl.h errorcodes */
5827 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5828 PY_SSL_ERROR_EOF);
5829 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5830 PY_SSL_ERROR_INVALID_ERROR_CODE);
5831 /* cert requirements */
5832 PyModule_AddIntConstant(m, "CERT_NONE",
5833 PY_SSL_CERT_NONE);
5834 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5835 PY_SSL_CERT_OPTIONAL);
5836 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5837 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005838 /* CRL verification for verification_flags */
5839 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5840 0);
5841 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5842 X509_V_FLAG_CRL_CHECK);
5843 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5844 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5845 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5846 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005847#ifdef X509_V_FLAG_TRUSTED_FIRST
5848 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5849 X509_V_FLAG_TRUSTED_FIRST);
5850#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005851
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005852 /* Alert Descriptions from ssl.h */
5853 /* note RESERVED constants no longer intended for use have been removed */
5854 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5855
5856#define ADD_AD_CONSTANT(s) \
5857 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5858 SSL_AD_##s)
5859
5860 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5861 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5862 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5863 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5864 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5865 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5866 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5867 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5868 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5869 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5870 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5871 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5872 ADD_AD_CONSTANT(UNKNOWN_CA);
5873 ADD_AD_CONSTANT(ACCESS_DENIED);
5874 ADD_AD_CONSTANT(DECODE_ERROR);
5875 ADD_AD_CONSTANT(DECRYPT_ERROR);
5876 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5877 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5878 ADD_AD_CONSTANT(INTERNAL_ERROR);
5879 ADD_AD_CONSTANT(USER_CANCELLED);
5880 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005881 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005882#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5883 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5884#endif
5885#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5886 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5887#endif
5888#ifdef SSL_AD_UNRECOGNIZED_NAME
5889 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5890#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005891#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5892 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5893#endif
5894#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5895 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5896#endif
5897#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5898 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5899#endif
5900
5901#undef ADD_AD_CONSTANT
5902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005903 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005904#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005905 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5906 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005907#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005908#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005909 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5910 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005911#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005912 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005913 PY_SSL_VERSION_TLS);
5914 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5915 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005916 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5917 PY_SSL_VERSION_TLS_CLIENT);
5918 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5919 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005920 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5921 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005922#if HAVE_TLSv1_2
5923 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5924 PY_SSL_VERSION_TLS1_1);
5925 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5926 PY_SSL_VERSION_TLS1_2);
5927#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005928
Antoine Pitroub5218772010-05-21 09:56:06 +00005929 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005930 PyModule_AddIntConstant(m, "OP_ALL",
5931 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005932 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5933 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5934 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005935#if HAVE_TLSv1_2
5936 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5937 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5938#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005939#ifdef SSL_OP_NO_TLSv1_3
5940 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5941#else
5942 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5943#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005944 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5945 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005946 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005947 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005948#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005949 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005950#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005951#ifdef SSL_OP_NO_COMPRESSION
5952 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5953 SSL_OP_NO_COMPRESSION);
5954#endif
Miss Islington (bot)2614ed42018-02-27 00:17:49 -08005955#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5956 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5957 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5958#endif
Miss Islington (bot)e2db6ad2018-05-16 07:26:19 -07005959#ifdef SSL_OP_NO_RENEGOTIATION
5960 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5961 SSL_OP_NO_RENEGOTIATION);
5962#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005963
Christian Heimes61d478c2018-01-27 15:51:38 +01005964#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5965 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5966 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5967#endif
5968#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5969 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5970 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5971#endif
5972#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5973 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5974 X509_CHECK_FLAG_NO_WILDCARDS);
5975#endif
5976#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5977 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5978 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5979#endif
5980#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5981 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5982 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5983#endif
5984#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5985 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5986 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5987#endif
5988
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005989 /* protocol versions */
5990 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5991 PY_PROTO_MINIMUM_SUPPORTED);
5992 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5993 PY_PROTO_MAXIMUM_SUPPORTED);
5994 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5995 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5996 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5997 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5998 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005999
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006000#define addbool(m, v, b) \
6001 Py_INCREF((b) ? Py_True : Py_False); \
6002 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
6003
6004#if HAVE_SNI
6005 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006006#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006007 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006008#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006009
6010 addbool(m, "HAS_TLS_UNIQUE", 1);
6011
6012#ifndef OPENSSL_NO_ECDH
6013 addbool(m, "HAS_ECDH", 1);
6014#else
6015 addbool(m, "HAS_ECDH", 0);
6016#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006017
Miss Islington (bot)96177412018-02-25 04:18:43 -08006018#if HAVE_NPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006019 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006020#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006021 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006022#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006023
Miss Islington (bot)96177412018-02-25 04:18:43 -08006024#if HAVE_ALPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006025 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006026#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006027 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006028#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006029
6030#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6031 addbool(m, "HAS_SSLv2", 1);
6032#else
6033 addbool(m, "HAS_SSLv2", 0);
6034#endif
6035
6036#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6037 addbool(m, "HAS_SSLv3", 1);
6038#else
6039 addbool(m, "HAS_SSLv3", 0);
6040#endif
6041
6042#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6043 addbool(m, "HAS_TLSv1", 1);
6044#else
6045 addbool(m, "HAS_TLSv1", 0);
6046#endif
6047
6048#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6049 addbool(m, "HAS_TLSv1_1", 1);
6050#else
6051 addbool(m, "HAS_TLSv1_1", 0);
6052#endif
6053
6054#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6055 addbool(m, "HAS_TLSv1_2", 1);
6056#else
6057 addbool(m, "HAS_TLSv1_2", 0);
6058#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006059
Christian Heimescb5b68a2017-09-07 18:07:00 -07006060#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006061 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006062#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006063 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006064#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006065
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006066 /* Mappings for error codes */
6067 err_codes_to_names = PyDict_New();
6068 err_names_to_codes = PyDict_New();
6069 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6070 return NULL;
6071 errcode = error_codes;
6072 while (errcode->mnemonic != NULL) {
6073 PyObject *mnemo, *key;
6074 mnemo = PyUnicode_FromString(errcode->mnemonic);
6075 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6076 if (mnemo == NULL || key == NULL)
6077 return NULL;
6078 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6079 return NULL;
6080 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6081 return NULL;
6082 Py_DECREF(key);
6083 Py_DECREF(mnemo);
6084 errcode++;
6085 }
6086 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6087 return NULL;
6088 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6089 return NULL;
6090
6091 lib_codes_to_names = PyDict_New();
6092 if (lib_codes_to_names == NULL)
6093 return NULL;
6094 libcode = library_codes;
6095 while (libcode->library != NULL) {
6096 PyObject *mnemo, *key;
6097 key = PyLong_FromLong(libcode->code);
6098 mnemo = PyUnicode_FromString(libcode->library);
6099 if (key == NULL || mnemo == NULL)
6100 return NULL;
6101 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6102 return NULL;
6103 Py_DECREF(key);
6104 Py_DECREF(mnemo);
6105 libcode++;
6106 }
6107 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6108 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006110 /* OpenSSL version */
6111 /* SSLeay() gives us the version of the library linked against,
6112 which could be different from the headers version.
6113 */
6114 libver = SSLeay();
6115 r = PyLong_FromUnsignedLong(libver);
6116 if (r == NULL)
6117 return NULL;
6118 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6119 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006120 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006121 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6122 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6123 return NULL;
6124 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6125 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6126 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006127
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006128 libver = OPENSSL_VERSION_NUMBER;
6129 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6130 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6131 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6132 return NULL;
6133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006134 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006135}