blob: 9894ad821d63e8c3e81843ec2ca4c0d863b1a515 [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);
Miss Islington (bot)cb272842018-12-17 07:10:20 -08003629 if (arg == NULL) {
3630 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3631 return -1;
3632 }
Christian Heimes2756ef32018-09-23 09:22:52 +02003633 int pha = PyObject_IsTrue(arg);
3634
3635 if (pha == -1) {
3636 return -1;
3637 }
3638 self->post_handshake_auth = pha;
3639
3640 /* client-side socket setting, ignored by server-side */
3641 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3642
3643 /* server-side socket setting, ignored by client-side */
3644 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3645 if (pha) {
3646 mode |= SSL_VERIFY_POST_HANDSHAKE;
3647 } else {
3648 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3649 }
3650 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3651
3652 return 0;
3653}
3654#endif
3655
3656static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003657get_protocol(PySSLContext *self, void *c) {
3658 return PyLong_FromLong(self->protocol);
3659}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003660
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003661typedef struct {
3662 PyThreadState *thread_state;
3663 PyObject *callable;
3664 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003665 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003666 int error;
3667} _PySSLPasswordInfo;
3668
3669static int
3670_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3671 const char *bad_type_error)
3672{
3673 /* Set the password and size fields of a _PySSLPasswordInfo struct
3674 from a unicode, bytes, or byte array object.
3675 The password field will be dynamically allocated and must be freed
3676 by the caller */
3677 PyObject *password_bytes = NULL;
3678 const char *data = NULL;
3679 Py_ssize_t size;
3680
3681 if (PyUnicode_Check(password)) {
3682 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3683 if (!password_bytes) {
3684 goto error;
3685 }
3686 data = PyBytes_AS_STRING(password_bytes);
3687 size = PyBytes_GET_SIZE(password_bytes);
3688 } else if (PyBytes_Check(password)) {
3689 data = PyBytes_AS_STRING(password);
3690 size = PyBytes_GET_SIZE(password);
3691 } else if (PyByteArray_Check(password)) {
3692 data = PyByteArray_AS_STRING(password);
3693 size = PyByteArray_GET_SIZE(password);
3694 } else {
3695 PyErr_SetString(PyExc_TypeError, bad_type_error);
3696 goto error;
3697 }
3698
Victor Stinner9ee02032013-06-23 15:08:23 +02003699 if (size > (Py_ssize_t)INT_MAX) {
3700 PyErr_Format(PyExc_ValueError,
3701 "password cannot be longer than %d bytes", INT_MAX);
3702 goto error;
3703 }
3704
Victor Stinner11ebff22013-07-07 17:07:52 +02003705 PyMem_Free(pw_info->password);
3706 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003707 if (!pw_info->password) {
3708 PyErr_SetString(PyExc_MemoryError,
3709 "unable to allocate password buffer");
3710 goto error;
3711 }
3712 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003713 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003714
3715 Py_XDECREF(password_bytes);
3716 return 1;
3717
3718error:
3719 Py_XDECREF(password_bytes);
3720 return 0;
3721}
3722
3723static int
3724_password_callback(char *buf, int size, int rwflag, void *userdata)
3725{
3726 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3727 PyObject *fn_ret = NULL;
3728
3729 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3730
3731 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003732 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003733 if (!fn_ret) {
3734 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3735 core python API, so we could use it to add a frame here */
3736 goto error;
3737 }
3738
3739 if (!_pwinfo_set(pw_info, fn_ret,
3740 "password callback must return a string")) {
3741 goto error;
3742 }
3743 Py_CLEAR(fn_ret);
3744 }
3745
3746 if (pw_info->size > size) {
3747 PyErr_Format(PyExc_ValueError,
3748 "password cannot be longer than %d bytes", size);
3749 goto error;
3750 }
3751
3752 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3753 memcpy(buf, pw_info->password, pw_info->size);
3754 return pw_info->size;
3755
3756error:
3757 Py_XDECREF(fn_ret);
3758 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3759 pw_info->error = 1;
3760 return -1;
3761}
3762
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003763/*[clinic input]
3764_ssl._SSLContext.load_cert_chain
3765 certfile: object
3766 keyfile: object = NULL
3767 password: object = NULL
3768
3769[clinic start generated code]*/
3770
Antoine Pitroub5218772010-05-21 09:56:06 +00003771static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003772_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3773 PyObject *keyfile, PyObject *password)
3774/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003775{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003776 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003777 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3778 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003779 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003780 int r;
3781
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003782 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003783 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003784 if (keyfile == Py_None)
3785 keyfile = NULL;
3786 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3787 PyErr_SetString(PyExc_TypeError,
3788 "certfile should be a valid filesystem path");
3789 return NULL;
3790 }
3791 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3792 PyErr_SetString(PyExc_TypeError,
3793 "keyfile should be a valid filesystem path");
3794 goto error;
3795 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003796 if (password && password != Py_None) {
3797 if (PyCallable_Check(password)) {
3798 pw_info.callable = password;
3799 } else if (!_pwinfo_set(&pw_info, password,
3800 "password should be a string or callable")) {
3801 goto error;
3802 }
3803 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3804 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3805 }
3806 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003807 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3808 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003809 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003810 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003811 if (pw_info.error) {
3812 ERR_clear_error();
3813 /* the password callback has already set the error information */
3814 }
3815 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003816 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003817 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003818 }
3819 else {
3820 _setSSLError(NULL, 0, __FILE__, __LINE__);
3821 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003822 goto error;
3823 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003824 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003825 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003826 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3827 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003828 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3829 Py_CLEAR(keyfile_bytes);
3830 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003831 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003832 if (pw_info.error) {
3833 ERR_clear_error();
3834 /* the password callback has already set the error information */
3835 }
3836 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003837 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003838 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003839 }
3840 else {
3841 _setSSLError(NULL, 0, __FILE__, __LINE__);
3842 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003843 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003844 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003845 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003846 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003847 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003848 if (r != 1) {
3849 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003850 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003851 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003852 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3853 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003854 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003855 Py_RETURN_NONE;
3856
3857error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003858 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3859 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003860 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003861 Py_XDECREF(keyfile_bytes);
3862 Py_XDECREF(certfile_bytes);
3863 return NULL;
3864}
3865
Christian Heimesefff7062013-11-21 03:35:02 +01003866/* internal helper function, returns -1 on error
3867 */
3868static int
3869_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3870 int filetype)
3871{
3872 BIO *biobuf = NULL;
3873 X509_STORE *store;
3874 int retval = 0, err, loaded = 0;
3875
3876 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3877
3878 if (len <= 0) {
3879 PyErr_SetString(PyExc_ValueError,
3880 "Empty certificate data");
3881 return -1;
3882 } else if (len > INT_MAX) {
3883 PyErr_SetString(PyExc_OverflowError,
3884 "Certificate data is too long.");
3885 return -1;
3886 }
3887
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003888 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003889 if (biobuf == NULL) {
3890 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3891 return -1;
3892 }
3893
3894 store = SSL_CTX_get_cert_store(self->ctx);
3895 assert(store != NULL);
3896
3897 while (1) {
3898 X509 *cert = NULL;
3899 int r;
3900
3901 if (filetype == SSL_FILETYPE_ASN1) {
3902 cert = d2i_X509_bio(biobuf, NULL);
3903 } else {
3904 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003905 SSL_CTX_get_default_passwd_cb(self->ctx),
3906 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3907 );
Christian Heimesefff7062013-11-21 03:35:02 +01003908 }
3909 if (cert == NULL) {
3910 break;
3911 }
3912 r = X509_STORE_add_cert(store, cert);
3913 X509_free(cert);
3914 if (!r) {
3915 err = ERR_peek_last_error();
3916 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3917 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3918 /* cert already in hash table, not an error */
3919 ERR_clear_error();
3920 } else {
3921 break;
3922 }
3923 }
3924 loaded++;
3925 }
3926
3927 err = ERR_peek_last_error();
3928 if ((filetype == SSL_FILETYPE_ASN1) &&
3929 (loaded > 0) &&
3930 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3931 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3932 /* EOF ASN1 file, not an error */
3933 ERR_clear_error();
3934 retval = 0;
3935 } else if ((filetype == SSL_FILETYPE_PEM) &&
3936 (loaded > 0) &&
3937 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3938 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3939 /* EOF PEM file, not an error */
3940 ERR_clear_error();
3941 retval = 0;
3942 } else {
3943 _setSSLError(NULL, 0, __FILE__, __LINE__);
3944 retval = -1;
3945 }
3946
3947 BIO_free(biobuf);
3948 return retval;
3949}
3950
3951
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003952/*[clinic input]
3953_ssl._SSLContext.load_verify_locations
3954 cafile: object = NULL
3955 capath: object = NULL
3956 cadata: object = NULL
3957
3958[clinic start generated code]*/
3959
Antoine Pitrou152efa22010-05-16 18:19:27 +00003960static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003961_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3962 PyObject *cafile,
3963 PyObject *capath,
3964 PyObject *cadata)
3965/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003967 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3968 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003969 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003970
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003971 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003972 if (cafile == Py_None)
3973 cafile = NULL;
3974 if (capath == Py_None)
3975 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003976 if (cadata == Py_None)
3977 cadata = NULL;
3978
3979 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003980 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003981 "cafile, capath and cadata cannot be all omitted");
3982 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003983 }
3984 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3985 PyErr_SetString(PyExc_TypeError,
3986 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003987 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003988 }
3989 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003990 PyErr_SetString(PyExc_TypeError,
3991 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003992 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003993 }
Christian Heimesefff7062013-11-21 03:35:02 +01003994
3995 /* validata cadata type and load cadata */
3996 if (cadata) {
3997 Py_buffer buf;
3998 PyObject *cadata_ascii = NULL;
3999
4000 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
4001 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4002 PyBuffer_Release(&buf);
4003 PyErr_SetString(PyExc_TypeError,
4004 "cadata should be a contiguous buffer with "
4005 "a single dimension");
4006 goto error;
4007 }
4008 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4009 PyBuffer_Release(&buf);
4010 if (r == -1) {
4011 goto error;
4012 }
4013 } else {
4014 PyErr_Clear();
4015 cadata_ascii = PyUnicode_AsASCIIString(cadata);
4016 if (cadata_ascii == NULL) {
4017 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004018 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01004019 "bytes-like object");
4020 goto error;
4021 }
4022 r = _add_ca_certs(self,
4023 PyBytes_AS_STRING(cadata_ascii),
4024 PyBytes_GET_SIZE(cadata_ascii),
4025 SSL_FILETYPE_PEM);
4026 Py_DECREF(cadata_ascii);
4027 if (r == -1) {
4028 goto error;
4029 }
4030 }
4031 }
4032
4033 /* load cafile or capath */
4034 if (cafile || capath) {
4035 if (cafile)
4036 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4037 if (capath)
4038 capath_buf = PyBytes_AS_STRING(capath_bytes);
4039 PySSL_BEGIN_ALLOW_THREADS
4040 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4041 PySSL_END_ALLOW_THREADS
4042 if (r != 1) {
4043 ok = 0;
4044 if (errno != 0) {
4045 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004046 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004047 }
4048 else {
4049 _setSSLError(NULL, 0, __FILE__, __LINE__);
4050 }
4051 goto error;
4052 }
4053 }
4054 goto end;
4055
4056 error:
4057 ok = 0;
4058 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004059 Py_XDECREF(cafile_bytes);
4060 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004061 if (ok) {
4062 Py_RETURN_NONE;
4063 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004064 return NULL;
4065 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004066}
4067
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004068/*[clinic input]
4069_ssl._SSLContext.load_dh_params
4070 path as filepath: object
4071 /
4072
4073[clinic start generated code]*/
4074
Antoine Pitrou152efa22010-05-16 18:19:27 +00004075static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4077/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004078{
4079 FILE *f;
4080 DH *dh;
4081
Victor Stinnerdaf45552013-08-28 00:53:59 +02004082 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004083 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004084 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004085
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004086 errno = 0;
4087 PySSL_BEGIN_ALLOW_THREADS
4088 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004089 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004090 PySSL_END_ALLOW_THREADS
4091 if (dh == NULL) {
4092 if (errno != 0) {
4093 ERR_clear_error();
4094 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4095 }
4096 else {
4097 _setSSLError(NULL, 0, __FILE__, __LINE__);
4098 }
4099 return NULL;
4100 }
4101 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4102 _setSSLError(NULL, 0, __FILE__, __LINE__);
4103 DH_free(dh);
4104 Py_RETURN_NONE;
4105}
4106
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004107/*[clinic input]
4108_ssl._SSLContext._wrap_socket
4109 sock: object(subclass_of="PySocketModule.Sock_Type")
4110 server_side: int
4111 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004112 *
4113 owner: object = None
4114 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004115
4116[clinic start generated code]*/
4117
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004118static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004119_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004120 int server_side, PyObject *hostname_obj,
4121 PyObject *owner, PyObject *session)
4122/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004123{
Antoine Pitroud5323212010-10-22 18:19:07 +00004124 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004126
Antoine Pitroud5323212010-10-22 18:19:07 +00004127 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004128 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004130 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004131 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004132 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004133
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004134 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4135 server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004136 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004137 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004138 if (hostname != NULL)
4139 PyMem_Free(hostname);
4140 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004141}
4142
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004143/*[clinic input]
4144_ssl._SSLContext._wrap_bio
4145 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4146 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4147 server_side: int
4148 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004149 *
4150 owner: object = None
4151 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004152
4153[clinic start generated code]*/
4154
Antoine Pitroub0182c82010-10-12 20:09:02 +00004155static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004156_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4157 PySSLMemoryBIO *outgoing, int server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004158 PyObject *hostname_obj, PyObject *owner,
4159 PyObject *session)
4160/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004161{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004162 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004163 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004164
4165 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004166 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004167 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004168 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004169 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004170 }
4171
4172 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004173 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004174 incoming, outgoing);
4175
4176 PyMem_Free(hostname);
4177 return res;
4178}
4179
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004180/*[clinic input]
4181_ssl._SSLContext.session_stats
4182[clinic start generated code]*/
4183
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4186/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004187{
4188 int r;
4189 PyObject *value, *stats = PyDict_New();
4190 if (!stats)
4191 return NULL;
4192
4193#define ADD_STATS(SSL_NAME, KEY_NAME) \
4194 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4195 if (value == NULL) \
4196 goto error; \
4197 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4198 Py_DECREF(value); \
4199 if (r < 0) \
4200 goto error;
4201
4202 ADD_STATS(number, "number");
4203 ADD_STATS(connect, "connect");
4204 ADD_STATS(connect_good, "connect_good");
4205 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4206 ADD_STATS(accept, "accept");
4207 ADD_STATS(accept_good, "accept_good");
4208 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4209 ADD_STATS(accept, "accept");
4210 ADD_STATS(hits, "hits");
4211 ADD_STATS(misses, "misses");
4212 ADD_STATS(timeouts, "timeouts");
4213 ADD_STATS(cache_full, "cache_full");
4214
4215#undef ADD_STATS
4216
4217 return stats;
4218
4219error:
4220 Py_DECREF(stats);
4221 return NULL;
4222}
4223
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004224/*[clinic input]
4225_ssl._SSLContext.set_default_verify_paths
4226[clinic start generated code]*/
4227
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004228static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004229_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4230/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004231{
4232 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4233 _setSSLError(NULL, 0, __FILE__, __LINE__);
4234 return NULL;
4235 }
4236 Py_RETURN_NONE;
4237}
4238
Antoine Pitrou501da612011-12-21 09:27:41 +01004239#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004240/*[clinic input]
4241_ssl._SSLContext.set_ecdh_curve
4242 name: object
4243 /
4244
4245[clinic start generated code]*/
4246
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004247static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004248_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4249/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004250{
4251 PyObject *name_bytes;
4252 int nid;
4253 EC_KEY *key;
4254
4255 if (!PyUnicode_FSConverter(name, &name_bytes))
4256 return NULL;
4257 assert(PyBytes_Check(name_bytes));
4258 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4259 Py_DECREF(name_bytes);
4260 if (nid == 0) {
4261 PyErr_Format(PyExc_ValueError,
4262 "unknown elliptic curve name %R", name);
4263 return NULL;
4264 }
4265 key = EC_KEY_new_by_curve_name(nid);
4266 if (key == NULL) {
4267 _setSSLError(NULL, 0, __FILE__, __LINE__);
4268 return NULL;
4269 }
4270 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4271 EC_KEY_free(key);
4272 Py_RETURN_NONE;
4273}
Antoine Pitrou501da612011-12-21 09:27:41 +01004274#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004275
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004276#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004277static int
4278_servername_callback(SSL *s, int *al, void *args)
4279{
4280 int ret;
4281 PySSLContext *ssl_ctx = (PySSLContext *) args;
4282 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004283 PyObject *result;
4284 /* The high-level ssl.SSLSocket object */
4285 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004286 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004287 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004288
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004289 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004290 /* remove race condition in this the call back while if removing the
4291 * callback is in progress */
4292 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004293 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004294 }
4295
4296 ssl = SSL_get_app_data(s);
4297 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004298
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004299 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004300 * SSL connection and that has a .context attribute that can be changed to
4301 * identify the requested hostname. Since the official API is the Python
4302 * level API we want to pass the callback a Python level object rather than
4303 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4304 * SSLObject) that will be passed. Otherwise if there's a socket then that
4305 * will be passed. If both do not exist only then the C-level object is
4306 * passed. */
4307 if (ssl->owner)
4308 ssl_socket = PyWeakref_GetObject(ssl->owner);
4309 else if (ssl->Socket)
4310 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4311 else
4312 ssl_socket = (PyObject *) ssl;
4313
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004314 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004315 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004316 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004317
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004318 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004319 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004320 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004321 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004322 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004323 PyObject *servername_bytes;
4324 PyObject *servername_str;
4325
4326 servername_bytes = PyBytes_FromString(servername);
4327 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004328 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4329 goto error;
4330 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004331 /* server_hostname was encoded to an A-label by our caller; put it
4332 * back into a str object, but still as an A-label (bpo-28414)
4333 */
4334 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4335 Py_DECREF(servername_bytes);
4336 if (servername_str == NULL) {
4337 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004338 goto error;
4339 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004340 result = PyObject_CallFunctionObjArgs(
4341 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4342 ssl_ctx, NULL);
4343 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004344 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004345 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004346
4347 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004348 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004349 *al = SSL_AD_HANDSHAKE_FAILURE;
4350 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4351 }
4352 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004353 /* Result may be None, a SSLContext or an integer
4354 * None and SSLContext are OK, integer or other values are an error.
4355 */
4356 if (result == Py_None) {
4357 ret = SSL_TLSEXT_ERR_OK;
4358 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004359 *al = (int) PyLong_AsLong(result);
4360 if (PyErr_Occurred()) {
4361 PyErr_WriteUnraisable(result);
4362 *al = SSL_AD_INTERNAL_ERROR;
4363 }
4364 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4365 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004366 Py_DECREF(result);
4367 }
4368
4369 PyGILState_Release(gstate);
4370 return ret;
4371
4372error:
4373 Py_DECREF(ssl_socket);
4374 *al = SSL_AD_INTERNAL_ERROR;
4375 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4376 PyGILState_Release(gstate);
4377 return ret;
4378}
Antoine Pitroua5963382013-03-30 16:39:00 +01004379#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004380
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004381static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004382get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004383{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004384 PyObject *cb = self->set_sni_cb;
4385 if (cb == NULL) {
4386 Py_RETURN_NONE;
4387 }
4388 Py_INCREF(cb);
4389 return cb;
4390}
4391
4392static int
4393set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4394{
4395 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4396 PyErr_SetString(PyExc_ValueError,
4397 "sni_callback cannot be set on TLS_CLIENT context");
4398 return -1;
4399 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004400#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004401 Py_CLEAR(self->set_sni_cb);
4402 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004403 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4404 }
4405 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004406 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004407 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4408 PyErr_SetString(PyExc_TypeError,
4409 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004410 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004411 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004412 Py_INCREF(arg);
4413 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004414 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4415 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4416 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004417 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004418#else
4419 PyErr_SetString(PyExc_NotImplementedError,
4420 "The TLS extension servername callback, "
4421 "SSL_CTX_set_tlsext_servername_callback, "
4422 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004423 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004424#endif
4425}
4426
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004427PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4428"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4429\n\
4430If the argument is None then the callback is disabled. The method is called\n\
4431with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4432See RFC 6066 for details of the SNI extension.");
4433
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004434/*[clinic input]
4435_ssl._SSLContext.cert_store_stats
4436
4437Returns quantities of loaded X.509 certificates.
4438
4439X.509 certificates with a CA extension and certificate revocation lists
4440inside the context's cert store.
4441
4442NOTE: Certificates in a capath directory aren't loaded unless they have
4443been used at least once.
4444[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004445
4446static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004447_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4448/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004449{
4450 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004451 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004452 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004453 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004454
4455 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004456 objs = X509_STORE_get0_objects(store);
4457 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4458 obj = sk_X509_OBJECT_value(objs, i);
4459 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004460 case X509_LU_X509:
4461 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004462 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004463 ca++;
4464 }
4465 break;
4466 case X509_LU_CRL:
4467 crl++;
4468 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004469 default:
4470 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4471 * As far as I can tell they are internal states and never
4472 * stored in a cert store */
4473 break;
4474 }
4475 }
4476 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4477 "x509_ca", ca);
4478}
4479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480/*[clinic input]
4481_ssl._SSLContext.get_ca_certs
4482 binary_form: bool = False
4483
4484Returns a list of dicts with information of loaded CA certs.
4485
4486If the optional argument is True, returns a DER-encoded copy of the CA
4487certificate.
4488
4489NOTE: Certificates in a capath directory aren't loaded unless they have
4490been used at least once.
4491[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004492
4493static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004494_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4495/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004496{
4497 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004498 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004499 PyObject *ci = NULL, *rlist = NULL;
4500 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004501
4502 if ((rlist = PyList_New(0)) == NULL) {
4503 return NULL;
4504 }
4505
4506 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004507 objs = X509_STORE_get0_objects(store);
4508 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004509 X509_OBJECT *obj;
4510 X509 *cert;
4511
Christian Heimes598894f2016-09-05 23:19:05 +02004512 obj = sk_X509_OBJECT_value(objs, i);
4513 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004514 /* not a x509 cert */
4515 continue;
4516 }
4517 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004518 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004519 if (!X509_check_ca(cert)) {
4520 continue;
4521 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004522 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004523 ci = _certificate_to_der(cert);
4524 } else {
4525 ci = _decode_certificate(cert);
4526 }
4527 if (ci == NULL) {
4528 goto error;
4529 }
4530 if (PyList_Append(rlist, ci) == -1) {
4531 goto error;
4532 }
4533 Py_CLEAR(ci);
4534 }
4535 return rlist;
4536
4537 error:
4538 Py_XDECREF(ci);
4539 Py_XDECREF(rlist);
4540 return NULL;
4541}
4542
4543
Antoine Pitrou152efa22010-05-16 18:19:27 +00004544static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004545 {"check_hostname", (getter) get_check_hostname,
4546 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004547 {"_host_flags", (getter) get_host_flags,
4548 (setter) set_host_flags, NULL},
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004549#if SSL_CTRL_GET_MAX_PROTO_VERSION
4550 {"minimum_version", (getter) get_minimum_version,
4551 (setter) set_minimum_version, NULL},
4552 {"maximum_version", (getter) get_maximum_version,
4553 (setter) set_maximum_version, NULL},
4554#endif
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004555 {"sni_callback", (getter) get_sni_callback,
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004556 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004557 {"options", (getter) get_options,
4558 (setter) set_options, NULL},
Christian Heimes2756ef32018-09-23 09:22:52 +02004559 {"post_handshake_auth", (getter) get_post_handshake_auth,
4560#ifdef TLS1_3_VERSION
4561 (setter) set_post_handshake_auth,
4562#else
4563 NULL,
4564#endif
4565 NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004566 {"protocol", (getter) get_protocol,
4567 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004568 {"verify_flags", (getter) get_verify_flags,
4569 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004570 {"verify_mode", (getter) get_verify_mode,
4571 (setter) set_verify_mode, NULL},
4572 {NULL}, /* sentinel */
4573};
4574
4575static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004576 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4577 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4578 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4579 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4580 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4581 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4582 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4583 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4584 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4585 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4586 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004587 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4588 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004589 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004590 {NULL, NULL} /* sentinel */
4591};
4592
4593static PyTypeObject PySSLContext_Type = {
4594 PyVarObject_HEAD_INIT(NULL, 0)
4595 "_ssl._SSLContext", /*tp_name*/
4596 sizeof(PySSLContext), /*tp_basicsize*/
4597 0, /*tp_itemsize*/
4598 (destructor)context_dealloc, /*tp_dealloc*/
4599 0, /*tp_print*/
4600 0, /*tp_getattr*/
4601 0, /*tp_setattr*/
4602 0, /*tp_reserved*/
4603 0, /*tp_repr*/
4604 0, /*tp_as_number*/
4605 0, /*tp_as_sequence*/
4606 0, /*tp_as_mapping*/
4607 0, /*tp_hash*/
4608 0, /*tp_call*/
4609 0, /*tp_str*/
4610 0, /*tp_getattro*/
4611 0, /*tp_setattro*/
4612 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004613 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004614 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004615 (traverseproc) context_traverse, /*tp_traverse*/
4616 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004617 0, /*tp_richcompare*/
4618 0, /*tp_weaklistoffset*/
4619 0, /*tp_iter*/
4620 0, /*tp_iternext*/
4621 context_methods, /*tp_methods*/
4622 0, /*tp_members*/
4623 context_getsetlist, /*tp_getset*/
4624 0, /*tp_base*/
4625 0, /*tp_dict*/
4626 0, /*tp_descr_get*/
4627 0, /*tp_descr_set*/
4628 0, /*tp_dictoffset*/
4629 0, /*tp_init*/
4630 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004631 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004632};
4633
4634
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004635/*
4636 * MemoryBIO objects
4637 */
4638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004639/*[clinic input]
4640@classmethod
4641_ssl.MemoryBIO.__new__
4642
4643[clinic start generated code]*/
4644
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004645static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004646_ssl_MemoryBIO_impl(PyTypeObject *type)
4647/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004648{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004649 BIO *bio;
4650 PySSLMemoryBIO *self;
4651
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004652 bio = BIO_new(BIO_s_mem());
4653 if (bio == NULL) {
4654 PyErr_SetString(PySSLErrorObject,
4655 "failed to allocate BIO");
4656 return NULL;
4657 }
4658 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4659 * just that no data is currently available. The SSL routines should retry
4660 * the read, which we can achieve by calling BIO_set_retry_read(). */
4661 BIO_set_retry_read(bio);
4662 BIO_set_mem_eof_return(bio, -1);
4663
4664 assert(type != NULL && type->tp_alloc != NULL);
4665 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4666 if (self == NULL) {
4667 BIO_free(bio);
4668 return NULL;
4669 }
4670 self->bio = bio;
4671 self->eof_written = 0;
4672
4673 return (PyObject *) self;
4674}
4675
4676static void
4677memory_bio_dealloc(PySSLMemoryBIO *self)
4678{
4679 BIO_free(self->bio);
4680 Py_TYPE(self)->tp_free(self);
4681}
4682
4683static PyObject *
4684memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4685{
Segev Finer5cff6372017-07-27 01:19:17 +03004686 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004687}
4688
4689PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4690"The number of bytes pending in the memory BIO.");
4691
4692static PyObject *
4693memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4694{
4695 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4696 && self->eof_written);
4697}
4698
4699PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4700"Whether the memory BIO is at EOF.");
4701
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004702/*[clinic input]
4703_ssl.MemoryBIO.read
4704 size as len: int = -1
4705 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004706
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004707Read up to size bytes from the memory BIO.
4708
4709If size is not specified, read the entire buffer.
4710If the return value is an empty bytes instance, this means either
4711EOF or that no data is available. Use the "eof" property to
4712distinguish between the two.
4713[clinic start generated code]*/
4714
4715static PyObject *
4716_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4717/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4718{
4719 int avail, nbytes;
4720 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004721
Segev Finer5cff6372017-07-27 01:19:17 +03004722 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004723 if ((len < 0) || (len > avail))
4724 len = avail;
4725
4726 result = PyBytes_FromStringAndSize(NULL, len);
4727 if ((result == NULL) || (len == 0))
4728 return result;
4729
4730 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004731 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004732 Py_DECREF(result);
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004733 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004734 return NULL;
4735 }
4736
Miss Islington (bot)4ec9f642018-10-19 16:14:42 -07004737 /* There should never be any short reads but check anyway. */
4738 if (nbytes < len) {
4739 _PyBytes_Resize(&result, nbytes);
4740 }
4741
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004742 return result;
4743}
4744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004745/*[clinic input]
4746_ssl.MemoryBIO.write
4747 b: Py_buffer
4748 /
4749
4750Writes the bytes b into the memory BIO.
4751
4752Returns the number of bytes written.
4753[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004754
4755static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004756_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4757/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004758{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004759 int nbytes;
4760
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004761 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004762 PyErr_Format(PyExc_OverflowError,
4763 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004764 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004765 }
4766
4767 if (self->eof_written) {
4768 PyErr_SetString(PySSLErrorObject,
4769 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004770 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004771 }
4772
Segev Finer5cff6372017-07-27 01:19:17 +03004773 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004774 if (nbytes < 0) {
4775 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004776 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004777 }
4778
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004779 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004780}
4781
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004782/*[clinic input]
4783_ssl.MemoryBIO.write_eof
4784
4785Write an EOF marker to the memory BIO.
4786
4787When all data has been read, the "eof" property will be True.
4788[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004789
4790static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004791_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4792/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004793{
4794 self->eof_written = 1;
4795 /* After an EOF is written, a zero return from read() should be a real EOF
4796 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4797 BIO_clear_retry_flags(self->bio);
4798 BIO_set_mem_eof_return(self->bio, 0);
4799
4800 Py_RETURN_NONE;
4801}
4802
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004803static PyGetSetDef memory_bio_getsetlist[] = {
4804 {"pending", (getter) memory_bio_get_pending, NULL,
4805 PySSL_memory_bio_pending_doc},
4806 {"eof", (getter) memory_bio_get_eof, NULL,
4807 PySSL_memory_bio_eof_doc},
4808 {NULL}, /* sentinel */
4809};
4810
4811static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004812 _SSL_MEMORYBIO_READ_METHODDEF
4813 _SSL_MEMORYBIO_WRITE_METHODDEF
4814 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004815 {NULL, NULL} /* sentinel */
4816};
4817
4818static PyTypeObject PySSLMemoryBIO_Type = {
4819 PyVarObject_HEAD_INIT(NULL, 0)
4820 "_ssl.MemoryBIO", /*tp_name*/
4821 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4822 0, /*tp_itemsize*/
4823 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4824 0, /*tp_print*/
4825 0, /*tp_getattr*/
4826 0, /*tp_setattr*/
4827 0, /*tp_reserved*/
4828 0, /*tp_repr*/
4829 0, /*tp_as_number*/
4830 0, /*tp_as_sequence*/
4831 0, /*tp_as_mapping*/
4832 0, /*tp_hash*/
4833 0, /*tp_call*/
4834 0, /*tp_str*/
4835 0, /*tp_getattro*/
4836 0, /*tp_setattro*/
4837 0, /*tp_as_buffer*/
4838 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4839 0, /*tp_doc*/
4840 0, /*tp_traverse*/
4841 0, /*tp_clear*/
4842 0, /*tp_richcompare*/
4843 0, /*tp_weaklistoffset*/
4844 0, /*tp_iter*/
4845 0, /*tp_iternext*/
4846 memory_bio_methods, /*tp_methods*/
4847 0, /*tp_members*/
4848 memory_bio_getsetlist, /*tp_getset*/
4849 0, /*tp_base*/
4850 0, /*tp_dict*/
4851 0, /*tp_descr_get*/
4852 0, /*tp_descr_set*/
4853 0, /*tp_dictoffset*/
4854 0, /*tp_init*/
4855 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004856 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004857};
4858
Antoine Pitrou152efa22010-05-16 18:19:27 +00004859
Christian Heimes99a65702016-09-10 23:44:53 +02004860/*
4861 * SSL Session object
4862 */
4863
4864static void
4865PySSLSession_dealloc(PySSLSession *self)
4866{
INADA Naokia6296d32017-08-24 14:55:17 +09004867 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004868 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004869 Py_XDECREF(self->ctx);
4870 if (self->session != NULL) {
4871 SSL_SESSION_free(self->session);
4872 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004873 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004874}
4875
4876static PyObject *
4877PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4878{
4879 int result;
4880
4881 if (left == NULL || right == NULL) {
4882 PyErr_BadInternalCall();
4883 return NULL;
4884 }
4885
4886 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4887 Py_RETURN_NOTIMPLEMENTED;
4888 }
4889
4890 if (left == right) {
4891 result = 0;
4892 } else {
4893 const unsigned char *left_id, *right_id;
4894 unsigned int left_len, right_len;
4895 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4896 &left_len);
4897 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4898 &right_len);
4899 if (left_len == right_len) {
4900 result = memcmp(left_id, right_id, left_len);
4901 } else {
4902 result = 1;
4903 }
4904 }
4905
4906 switch (op) {
4907 case Py_EQ:
4908 if (result == 0) {
4909 Py_RETURN_TRUE;
4910 } else {
4911 Py_RETURN_FALSE;
4912 }
4913 break;
4914 case Py_NE:
4915 if (result != 0) {
4916 Py_RETURN_TRUE;
4917 } else {
4918 Py_RETURN_FALSE;
4919 }
4920 break;
4921 case Py_LT:
4922 case Py_LE:
4923 case Py_GT:
4924 case Py_GE:
4925 Py_RETURN_NOTIMPLEMENTED;
4926 break;
4927 default:
4928 PyErr_BadArgument();
4929 return NULL;
4930 }
4931}
4932
4933static int
4934PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4935{
4936 Py_VISIT(self->ctx);
4937 return 0;
4938}
4939
4940static int
4941PySSLSession_clear(PySSLSession *self)
4942{
4943 Py_CLEAR(self->ctx);
4944 return 0;
4945}
4946
4947
4948static PyObject *
4949PySSLSession_get_time(PySSLSession *self, void *closure) {
4950 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4951}
4952
4953PyDoc_STRVAR(PySSLSession_get_time_doc,
4954"Session creation time (seconds since epoch).");
4955
4956
4957static PyObject *
4958PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4959 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4960}
4961
4962PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4963"Session timeout (delta in seconds).");
4964
4965
4966static PyObject *
4967PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4968 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4969 return PyLong_FromUnsignedLong(hint);
4970}
4971
4972PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4973"Ticket life time hint.");
4974
4975
4976static PyObject *
4977PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4978 const unsigned char *id;
4979 unsigned int len;
4980 id = SSL_SESSION_get_id(self->session, &len);
4981 return PyBytes_FromStringAndSize((const char *)id, len);
4982}
4983
4984PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4985"Session id");
4986
4987
4988static PyObject *
4989PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4990 if (SSL_SESSION_has_ticket(self->session)) {
4991 Py_RETURN_TRUE;
4992 } else {
4993 Py_RETURN_FALSE;
4994 }
4995}
4996
4997PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4998"Does the session contain a ticket?");
4999
5000
5001static PyGetSetDef PySSLSession_getsetlist[] = {
5002 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5003 PySSLSession_get_has_ticket_doc},
5004 {"id", (getter) PySSLSession_get_session_id, NULL,
5005 PySSLSession_get_session_id_doc},
5006 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5007 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5008 {"time", (getter) PySSLSession_get_time, NULL,
5009 PySSLSession_get_time_doc},
5010 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5011 PySSLSession_get_timeout_doc},
5012 {NULL}, /* sentinel */
5013};
5014
5015static PyTypeObject PySSLSession_Type = {
5016 PyVarObject_HEAD_INIT(NULL, 0)
5017 "_ssl.Session", /*tp_name*/
5018 sizeof(PySSLSession), /*tp_basicsize*/
5019 0, /*tp_itemsize*/
5020 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
5021 0, /*tp_print*/
5022 0, /*tp_getattr*/
5023 0, /*tp_setattr*/
5024 0, /*tp_reserved*/
5025 0, /*tp_repr*/
5026 0, /*tp_as_number*/
5027 0, /*tp_as_sequence*/
5028 0, /*tp_as_mapping*/
5029 0, /*tp_hash*/
5030 0, /*tp_call*/
5031 0, /*tp_str*/
5032 0, /*tp_getattro*/
5033 0, /*tp_setattro*/
5034 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005035 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005036 0, /*tp_doc*/
5037 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5038 (inquiry)PySSLSession_clear, /*tp_clear*/
5039 PySSLSession_richcompare, /*tp_richcompare*/
5040 0, /*tp_weaklistoffset*/
5041 0, /*tp_iter*/
5042 0, /*tp_iternext*/
5043 0, /*tp_methods*/
5044 0, /*tp_members*/
5045 PySSLSession_getsetlist, /*tp_getset*/
5046};
5047
5048
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005049/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050/*[clinic input]
5051_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005052 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005053 entropy: double
5054 /
5055
5056Mix string into the OpenSSL PRNG state.
5057
5058entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305059string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005060[clinic start generated code]*/
5061
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005062static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005063_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005064/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005065{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005066 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005067 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005069 buf = (const char *)view->buf;
5070 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005071 do {
5072 written = Py_MIN(len, INT_MAX);
5073 RAND_add(buf, (int)written, entropy);
5074 buf += written;
5075 len -= written;
5076 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005077 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005078}
5079
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005080static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005081PySSL_RAND(int len, int pseudo)
5082{
5083 int ok;
5084 PyObject *bytes;
5085 unsigned long err;
5086 const char *errstr;
5087 PyObject *v;
5088
Victor Stinner1e81a392013-12-19 16:47:04 +01005089 if (len < 0) {
5090 PyErr_SetString(PyExc_ValueError, "num must be positive");
5091 return NULL;
5092 }
5093
Victor Stinner99c8b162011-05-24 12:05:19 +02005094 bytes = PyBytes_FromStringAndSize(NULL, len);
5095 if (bytes == NULL)
5096 return NULL;
5097 if (pseudo) {
5098 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5099 if (ok == 0 || ok == 1)
5100 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5101 }
5102 else {
5103 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5104 if (ok == 1)
5105 return bytes;
5106 }
5107 Py_DECREF(bytes);
5108
5109 err = ERR_get_error();
5110 errstr = ERR_reason_error_string(err);
5111 v = Py_BuildValue("(ks)", err, errstr);
5112 if (v != NULL) {
5113 PyErr_SetObject(PySSLErrorObject, v);
5114 Py_DECREF(v);
5115 }
5116 return NULL;
5117}
5118
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005119/*[clinic input]
5120_ssl.RAND_bytes
5121 n: int
5122 /
5123
5124Generate n cryptographically strong pseudo-random bytes.
5125[clinic start generated code]*/
5126
Victor Stinner99c8b162011-05-24 12:05:19 +02005127static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005128_ssl_RAND_bytes_impl(PyObject *module, int n)
5129/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005130{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005131 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005132}
5133
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005134/*[clinic input]
5135_ssl.RAND_pseudo_bytes
5136 n: int
5137 /
5138
5139Generate n pseudo-random bytes.
5140
5141Return a pair (bytes, is_cryptographic). is_cryptographic is True
5142if the bytes generated are cryptographically strong.
5143[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005144
5145static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005146_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5147/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005148{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005149 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005150}
5151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005152/*[clinic input]
5153_ssl.RAND_status
5154
5155Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5156
5157It is necessary to seed the PRNG with RAND_add() on some platforms before
5158using the ssl() function.
5159[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005160
5161static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005162_ssl_RAND_status_impl(PyObject *module)
5163/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005164{
Christian Heimes217cfd12007-12-02 14:31:20 +00005165 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005166}
5167
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005168#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005169/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005170/*[clinic input]
5171_ssl.RAND_egd
5172 path: object(converter="PyUnicode_FSConverter")
5173 /
5174
5175Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5176
5177Returns number of bytes read. Raises SSLError if connection to EGD
5178fails or if it does not provide enough data to seed PRNG.
5179[clinic start generated code]*/
5180
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005181static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005182_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5183/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005184{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005185 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005186 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005187 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005188 PyErr_SetString(PySSLErrorObject,
5189 "EGD connection failed or EGD did not return "
5190 "enough data to seed the PRNG");
5191 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005192 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005193 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005194}
Christian Heimesa5d07652016-09-24 10:48:05 +02005195/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005196#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005197
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005199
5200/*[clinic input]
5201_ssl.get_default_verify_paths
5202
5203Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5204
5205The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5206[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005207
5208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005209_ssl_get_default_verify_paths_impl(PyObject *module)
5210/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005211{
5212 PyObject *ofile_env = NULL;
5213 PyObject *ofile = NULL;
5214 PyObject *odir_env = NULL;
5215 PyObject *odir = NULL;
5216
Benjamin Petersond113c962015-07-18 10:59:13 -07005217#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005218 const char *tmp = (info); \
5219 target = NULL; \
5220 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5221 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5222 target = PyBytes_FromString(tmp); } \
5223 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005224 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005225
Benjamin Petersond113c962015-07-18 10:59:13 -07005226 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5227 CONVERT(X509_get_default_cert_file(), ofile);
5228 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5229 CONVERT(X509_get_default_cert_dir(), odir);
5230#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005231
Christian Heimes200bb1b2013-06-14 15:14:29 +02005232 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005233
5234 error:
5235 Py_XDECREF(ofile_env);
5236 Py_XDECREF(ofile);
5237 Py_XDECREF(odir_env);
5238 Py_XDECREF(odir);
5239 return NULL;
5240}
5241
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005242static PyObject*
5243asn1obj2py(ASN1_OBJECT *obj)
5244{
5245 int nid;
5246 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005247
5248 nid = OBJ_obj2nid(obj);
5249 if (nid == NID_undef) {
5250 PyErr_Format(PyExc_ValueError, "Unknown object");
5251 return NULL;
5252 }
5253 sn = OBJ_nid2sn(nid);
5254 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005255 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005256}
5257
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005258/*[clinic input]
5259_ssl.txt2obj
5260 txt: str
5261 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005262
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005263Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5264
5265By default objects are looked up by OID. With name=True short and
5266long name are also matched.
5267[clinic start generated code]*/
5268
5269static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005270_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5271/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005272{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005273 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005274 ASN1_OBJECT *obj;
5275
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005276 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5277 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005278 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005279 return NULL;
5280 }
5281 result = asn1obj2py(obj);
5282 ASN1_OBJECT_free(obj);
5283 return result;
5284}
5285
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005286/*[clinic input]
5287_ssl.nid2obj
5288 nid: int
5289 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005290
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005291Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5292[clinic start generated code]*/
5293
5294static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005295_ssl_nid2obj_impl(PyObject *module, int nid)
5296/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005297{
5298 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005299 ASN1_OBJECT *obj;
5300
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005301 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005302 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005303 return NULL;
5304 }
5305 obj = OBJ_nid2obj(nid);
5306 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005307 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005308 return NULL;
5309 }
5310 result = asn1obj2py(obj);
5311 ASN1_OBJECT_free(obj);
5312 return result;
5313}
5314
Christian Heimes46bebee2013-06-09 19:03:31 +02005315#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005316
5317static PyObject*
5318certEncodingType(DWORD encodingType)
5319{
5320 static PyObject *x509_asn = NULL;
5321 static PyObject *pkcs_7_asn = NULL;
5322
5323 if (x509_asn == NULL) {
5324 x509_asn = PyUnicode_InternFromString("x509_asn");
5325 if (x509_asn == NULL)
5326 return NULL;
5327 }
5328 if (pkcs_7_asn == NULL) {
5329 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5330 if (pkcs_7_asn == NULL)
5331 return NULL;
5332 }
5333 switch(encodingType) {
5334 case X509_ASN_ENCODING:
5335 Py_INCREF(x509_asn);
5336 return x509_asn;
5337 case PKCS_7_ASN_ENCODING:
5338 Py_INCREF(pkcs_7_asn);
5339 return pkcs_7_asn;
5340 default:
5341 return PyLong_FromLong(encodingType);
5342 }
5343}
5344
5345static PyObject*
5346parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5347{
5348 CERT_ENHKEY_USAGE *usage;
5349 DWORD size, error, i;
5350 PyObject *retval;
5351
5352 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5353 error = GetLastError();
5354 if (error == CRYPT_E_NOT_FOUND) {
5355 Py_RETURN_TRUE;
5356 }
5357 return PyErr_SetFromWindowsErr(error);
5358 }
5359
5360 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5361 if (usage == NULL) {
5362 return PyErr_NoMemory();
5363 }
5364
5365 /* Now get the actual enhanced usage property */
5366 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5367 PyMem_Free(usage);
5368 error = GetLastError();
5369 if (error == CRYPT_E_NOT_FOUND) {
5370 Py_RETURN_TRUE;
5371 }
5372 return PyErr_SetFromWindowsErr(error);
5373 }
5374 retval = PySet_New(NULL);
5375 if (retval == NULL) {
5376 goto error;
5377 }
5378 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5379 if (usage->rgpszUsageIdentifier[i]) {
5380 PyObject *oid;
5381 int err;
5382 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5383 if (oid == NULL) {
5384 Py_CLEAR(retval);
5385 goto error;
5386 }
5387 err = PySet_Add(retval, oid);
5388 Py_DECREF(oid);
5389 if (err == -1) {
5390 Py_CLEAR(retval);
5391 goto error;
5392 }
5393 }
5394 }
5395 error:
5396 PyMem_Free(usage);
5397 return retval;
5398}
5399
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005400/*[clinic input]
5401_ssl.enum_certificates
5402 store_name: str
5403
5404Retrieve certificates from Windows' cert store.
5405
5406store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5407more cert storages, too. The function returns a list of (bytes,
5408encoding_type, trust) tuples. The encoding_type flag can be interpreted
5409with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5410a set of OIDs or the boolean True.
5411[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005412
Christian Heimes46bebee2013-06-09 19:03:31 +02005413static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005414_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5415/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005416{
Christian Heimes46bebee2013-06-09 19:03:31 +02005417 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005418 PCCERT_CONTEXT pCertCtx = NULL;
5419 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005420 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005421
Christian Heimes44109d72013-11-22 01:51:30 +01005422 result = PyList_New(0);
5423 if (result == NULL) {
5424 return NULL;
5425 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005426 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5427 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5428 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005429 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005430 Py_DECREF(result);
5431 return PyErr_SetFromWindowsErr(GetLastError());
5432 }
5433
Christian Heimes44109d72013-11-22 01:51:30 +01005434 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5435 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5436 pCertCtx->cbCertEncoded);
5437 if (!cert) {
5438 Py_CLEAR(result);
5439 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005440 }
Christian Heimes44109d72013-11-22 01:51:30 +01005441 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5442 Py_CLEAR(result);
5443 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005444 }
Christian Heimes44109d72013-11-22 01:51:30 +01005445 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5446 if (keyusage == Py_True) {
5447 Py_DECREF(keyusage);
5448 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005449 }
Christian Heimes44109d72013-11-22 01:51:30 +01005450 if (keyusage == NULL) {
5451 Py_CLEAR(result);
5452 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005453 }
Christian Heimes44109d72013-11-22 01:51:30 +01005454 if ((tup = PyTuple_New(3)) == NULL) {
5455 Py_CLEAR(result);
5456 break;
5457 }
5458 PyTuple_SET_ITEM(tup, 0, cert);
5459 cert = NULL;
5460 PyTuple_SET_ITEM(tup, 1, enc);
5461 enc = NULL;
5462 PyTuple_SET_ITEM(tup, 2, keyusage);
5463 keyusage = NULL;
5464 if (PyList_Append(result, tup) < 0) {
5465 Py_CLEAR(result);
5466 break;
5467 }
5468 Py_CLEAR(tup);
5469 }
5470 if (pCertCtx) {
5471 /* loop ended with an error, need to clean up context manually */
5472 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005473 }
5474
5475 /* In error cases cert, enc and tup may not be NULL */
5476 Py_XDECREF(cert);
5477 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005478 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005479 Py_XDECREF(tup);
5480
5481 if (!CertCloseStore(hStore, 0)) {
5482 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005483 Py_XDECREF(result);
5484 return PyErr_SetFromWindowsErr(GetLastError());
5485 }
5486 return result;
5487}
5488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005489/*[clinic input]
5490_ssl.enum_crls
5491 store_name: str
5492
5493Retrieve CRLs from Windows' cert store.
5494
5495store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5496more cert storages, too. The function returns a list of (bytes,
5497encoding_type) tuples. The encoding_type flag can be interpreted with
5498X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5499[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005500
5501static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005502_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5503/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005504{
Christian Heimes44109d72013-11-22 01:51:30 +01005505 HCERTSTORE hStore = NULL;
5506 PCCRL_CONTEXT pCrlCtx = NULL;
5507 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5508 PyObject *result = NULL;
5509
Christian Heimes44109d72013-11-22 01:51:30 +01005510 result = PyList_New(0);
5511 if (result == NULL) {
5512 return NULL;
5513 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005514 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5515 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5516 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005517 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005518 Py_DECREF(result);
5519 return PyErr_SetFromWindowsErr(GetLastError());
5520 }
Christian Heimes44109d72013-11-22 01:51:30 +01005521
5522 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5523 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5524 pCrlCtx->cbCrlEncoded);
5525 if (!crl) {
5526 Py_CLEAR(result);
5527 break;
5528 }
5529 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5530 Py_CLEAR(result);
5531 break;
5532 }
5533 if ((tup = PyTuple_New(2)) == NULL) {
5534 Py_CLEAR(result);
5535 break;
5536 }
5537 PyTuple_SET_ITEM(tup, 0, crl);
5538 crl = NULL;
5539 PyTuple_SET_ITEM(tup, 1, enc);
5540 enc = NULL;
5541
5542 if (PyList_Append(result, tup) < 0) {
5543 Py_CLEAR(result);
5544 break;
5545 }
5546 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005547 }
Christian Heimes44109d72013-11-22 01:51:30 +01005548 if (pCrlCtx) {
5549 /* loop ended with an error, need to clean up context manually */
5550 CertFreeCRLContext(pCrlCtx);
5551 }
5552
5553 /* In error cases cert, enc and tup may not be NULL */
5554 Py_XDECREF(crl);
5555 Py_XDECREF(enc);
5556 Py_XDECREF(tup);
5557
5558 if (!CertCloseStore(hStore, 0)) {
5559 /* This error case might shadow another exception.*/
5560 Py_XDECREF(result);
5561 return PyErr_SetFromWindowsErr(GetLastError());
5562 }
5563 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005564}
Christian Heimes44109d72013-11-22 01:51:30 +01005565
5566#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005567
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005568/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005569static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005570 _SSL__TEST_DECODE_CERT_METHODDEF
5571 _SSL_RAND_ADD_METHODDEF
5572 _SSL_RAND_BYTES_METHODDEF
5573 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5574 _SSL_RAND_EGD_METHODDEF
5575 _SSL_RAND_STATUS_METHODDEF
5576 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5577 _SSL_ENUM_CERTIFICATES_METHODDEF
5578 _SSL_ENUM_CRLS_METHODDEF
5579 _SSL_TXT2OBJ_METHODDEF
5580 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005581 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005582};
5583
5584
Christian Heimes598894f2016-09-05 23:19:05 +02005585#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005586
5587/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005588 * of the Python C thread library
5589 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5590 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005591
5592static PyThread_type_lock *_ssl_locks = NULL;
5593
Christian Heimes4d98ca92013-08-19 17:36:29 +02005594#if OPENSSL_VERSION_NUMBER >= 0x10000000
5595/* use new CRYPTO_THREADID API. */
5596static void
5597_ssl_threadid_callback(CRYPTO_THREADID *id)
5598{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005599 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005600}
5601#else
5602/* deprecated CRYPTO_set_id_callback() API. */
5603static unsigned long
5604_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005605 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005606}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005607#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005608
Bill Janssen6e027db2007-11-15 22:23:56 +00005609static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005610 (int mode, int n, const char *file, int line) {
5611 /* this function is needed to perform locking on shared data
5612 structures. (Note that OpenSSL uses a number of global data
5613 structures that will be implicitly shared whenever multiple
5614 threads use OpenSSL.) Multi-threaded applications will
5615 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005617 locking_function() must be able to handle up to
5618 CRYPTO_num_locks() different mutex locks. It sets the n-th
5619 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005621 file and line are the file number of the function setting the
5622 lock. They can be useful for debugging.
5623 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005625 if ((_ssl_locks == NULL) ||
5626 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5627 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005629 if (mode & CRYPTO_LOCK) {
5630 PyThread_acquire_lock(_ssl_locks[n], 1);
5631 } else {
5632 PyThread_release_lock(_ssl_locks[n]);
5633 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005634}
5635
5636static int _setup_ssl_threads(void) {
5637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005638 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005640 if (_ssl_locks == NULL) {
5641 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005642 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5643 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005644 if (_ssl_locks == NULL) {
5645 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005646 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005647 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005648 for (i = 0; i < _ssl_locks_count; i++) {
5649 _ssl_locks[i] = PyThread_allocate_lock();
5650 if (_ssl_locks[i] == NULL) {
5651 unsigned int j;
5652 for (j = 0; j < i; j++) {
5653 PyThread_free_lock(_ssl_locks[j]);
5654 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005655 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005656 return 0;
5657 }
5658 }
5659 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005660#if OPENSSL_VERSION_NUMBER >= 0x10000000
5661 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5662#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005663 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005664#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005665 }
5666 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005667}
5668
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005669#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005670
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005671PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005672"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005673for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005674
Martin v. Löwis1a214512008-06-11 05:26:20 +00005675
5676static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005677 PyModuleDef_HEAD_INIT,
5678 "_ssl",
5679 module_doc,
5680 -1,
5681 PySSL_methods,
5682 NULL,
5683 NULL,
5684 NULL,
5685 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005686};
5687
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005688
5689static void
5690parse_openssl_version(unsigned long libver,
5691 unsigned int *major, unsigned int *minor,
5692 unsigned int *fix, unsigned int *patch,
5693 unsigned int *status)
5694{
5695 *status = libver & 0xF;
5696 libver >>= 4;
5697 *patch = libver & 0xFF;
5698 libver >>= 8;
5699 *fix = libver & 0xFF;
5700 libver >>= 8;
5701 *minor = libver & 0xFF;
5702 libver >>= 8;
5703 *major = libver & 0xFF;
5704}
5705
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005706PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005707PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005708{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005709 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005710 unsigned long libver;
5711 unsigned int major, minor, fix, patch, status;
5712 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005713 struct py_ssl_error_code *errcode;
5714 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005715
Antoine Pitrou152efa22010-05-16 18:19:27 +00005716 if (PyType_Ready(&PySSLContext_Type) < 0)
5717 return NULL;
5718 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005719 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005720 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5721 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005722 if (PyType_Ready(&PySSLSession_Type) < 0)
5723 return NULL;
5724
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005725
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005726 m = PyModule_Create(&_sslmodule);
5727 if (m == NULL)
5728 return NULL;
5729 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005731 /* Load _socket module and its C API */
5732 socket_api = PySocketModule_ImportModuleAndAPI();
5733 if (!socket_api)
5734 return NULL;
5735 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005736
Christian Heimesc941e622017-09-05 15:47:11 +02005737#ifndef OPENSSL_VERSION_1_1
5738 /* Load all algorithms and initialize cpuid */
5739 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005740 /* Init OpenSSL */
5741 SSL_load_error_strings();
5742 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005743#endif
5744
Christian Heimes598894f2016-09-05 23:19:05 +02005745#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005746 /* note that this will start threading if not already started */
5747 if (!_setup_ssl_threads()) {
5748 return NULL;
5749 }
Christian Heimes598894f2016-09-05 23:19:05 +02005750#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5751 /* OpenSSL 1.1.0 builtin thread support is enabled */
5752 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005753#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005755 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005756 sslerror_type_slots[0].pfunc = PyExc_OSError;
5757 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005758 if (PySSLErrorObject == NULL)
5759 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005760
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005761 /* ssl.CertificateError used to be a subclass of ValueError */
5762 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5763 if (bases == NULL)
5764 return NULL;
5765 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5766 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5767 bases, NULL);
5768 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005769 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5770 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5771 PySSLErrorObject, NULL);
5772 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5773 "ssl.SSLWantReadError", SSLWantReadError_doc,
5774 PySSLErrorObject, NULL);
5775 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5776 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5777 PySSLErrorObject, NULL);
5778 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5779 "ssl.SSLSyscallError", SSLSyscallError_doc,
5780 PySSLErrorObject, NULL);
5781 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5782 "ssl.SSLEOFError", SSLEOFError_doc,
5783 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005784 if (PySSLCertVerificationErrorObject == NULL
5785 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005786 || PySSLWantReadErrorObject == NULL
5787 || PySSLWantWriteErrorObject == NULL
5788 || PySSLSyscallErrorObject == NULL
5789 || PySSLEOFErrorObject == NULL)
5790 return NULL;
5791 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005792 || PyDict_SetItemString(d, "SSLCertVerificationError",
5793 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005794 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5795 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5796 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5797 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5798 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005799 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005800 if (PyDict_SetItemString(d, "_SSLContext",
5801 (PyObject *)&PySSLContext_Type) != 0)
5802 return NULL;
5803 if (PyDict_SetItemString(d, "_SSLSocket",
5804 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005805 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005806 if (PyDict_SetItemString(d, "MemoryBIO",
5807 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5808 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005809 if (PyDict_SetItemString(d, "SSLSession",
5810 (PyObject *)&PySSLSession_Type) != 0)
5811 return NULL;
5812
Christian Heimes892d66e2018-01-29 14:10:18 +01005813 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5814 PY_SSL_DEFAULT_CIPHER_STRING);
5815
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005816 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5817 PY_SSL_ERROR_ZERO_RETURN);
5818 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5819 PY_SSL_ERROR_WANT_READ);
5820 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5821 PY_SSL_ERROR_WANT_WRITE);
5822 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5823 PY_SSL_ERROR_WANT_X509_LOOKUP);
5824 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5825 PY_SSL_ERROR_SYSCALL);
5826 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5827 PY_SSL_ERROR_SSL);
5828 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5829 PY_SSL_ERROR_WANT_CONNECT);
5830 /* non ssl.h errorcodes */
5831 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5832 PY_SSL_ERROR_EOF);
5833 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5834 PY_SSL_ERROR_INVALID_ERROR_CODE);
5835 /* cert requirements */
5836 PyModule_AddIntConstant(m, "CERT_NONE",
5837 PY_SSL_CERT_NONE);
5838 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5839 PY_SSL_CERT_OPTIONAL);
5840 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5841 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005842 /* CRL verification for verification_flags */
5843 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5844 0);
5845 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5846 X509_V_FLAG_CRL_CHECK);
5847 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5848 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5849 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5850 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005851#ifdef X509_V_FLAG_TRUSTED_FIRST
5852 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5853 X509_V_FLAG_TRUSTED_FIRST);
5854#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005855
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005856 /* Alert Descriptions from ssl.h */
5857 /* note RESERVED constants no longer intended for use have been removed */
5858 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5859
5860#define ADD_AD_CONSTANT(s) \
5861 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5862 SSL_AD_##s)
5863
5864 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5865 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5866 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5867 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5868 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5869 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5870 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5871 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5872 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5873 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5874 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5875 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5876 ADD_AD_CONSTANT(UNKNOWN_CA);
5877 ADD_AD_CONSTANT(ACCESS_DENIED);
5878 ADD_AD_CONSTANT(DECODE_ERROR);
5879 ADD_AD_CONSTANT(DECRYPT_ERROR);
5880 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5881 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5882 ADD_AD_CONSTANT(INTERNAL_ERROR);
5883 ADD_AD_CONSTANT(USER_CANCELLED);
5884 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005885 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005886#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5887 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5888#endif
5889#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5890 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5891#endif
5892#ifdef SSL_AD_UNRECOGNIZED_NAME
5893 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5894#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005895#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5896 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5897#endif
5898#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5899 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5900#endif
5901#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5902 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5903#endif
5904
5905#undef ADD_AD_CONSTANT
5906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005907 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005908#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005909 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5910 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005911#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005912#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005913 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5914 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005915#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005916 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005917 PY_SSL_VERSION_TLS);
5918 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5919 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005920 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5921 PY_SSL_VERSION_TLS_CLIENT);
5922 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5923 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005924 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5925 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005926#if HAVE_TLSv1_2
5927 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5928 PY_SSL_VERSION_TLS1_1);
5929 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5930 PY_SSL_VERSION_TLS1_2);
5931#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005932
Antoine Pitroub5218772010-05-21 09:56:06 +00005933 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005934 PyModule_AddIntConstant(m, "OP_ALL",
5935 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005936 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5937 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5938 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005939#if HAVE_TLSv1_2
5940 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5941 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5942#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005943#ifdef SSL_OP_NO_TLSv1_3
5944 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5945#else
5946 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5947#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005948 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5949 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005950 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005951 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005952#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005953 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005954#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005955#ifdef SSL_OP_NO_COMPRESSION
5956 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5957 SSL_OP_NO_COMPRESSION);
5958#endif
Miss Islington (bot)2614ed42018-02-27 00:17:49 -08005959#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5960 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5961 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5962#endif
Miss Islington (bot)e2db6ad2018-05-16 07:26:19 -07005963#ifdef SSL_OP_NO_RENEGOTIATION
5964 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5965 SSL_OP_NO_RENEGOTIATION);
5966#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005967
Christian Heimes61d478c2018-01-27 15:51:38 +01005968#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5969 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5970 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5971#endif
5972#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5973 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5974 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5975#endif
5976#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5977 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5978 X509_CHECK_FLAG_NO_WILDCARDS);
5979#endif
5980#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5981 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5982 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5983#endif
5984#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5985 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5986 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5987#endif
5988#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5989 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5990 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5991#endif
5992
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005993 /* protocol versions */
5994 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5995 PY_PROTO_MINIMUM_SUPPORTED);
5996 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5997 PY_PROTO_MAXIMUM_SUPPORTED);
5998 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5999 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6000 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6001 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6002 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006003
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006004#define addbool(m, v, b) \
6005 Py_INCREF((b) ? Py_True : Py_False); \
6006 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
6007
6008#if HAVE_SNI
6009 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006010#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006011 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006012#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006013
6014 addbool(m, "HAS_TLS_UNIQUE", 1);
6015
6016#ifndef OPENSSL_NO_ECDH
6017 addbool(m, "HAS_ECDH", 1);
6018#else
6019 addbool(m, "HAS_ECDH", 0);
6020#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006021
Miss Islington (bot)96177412018-02-25 04:18:43 -08006022#if HAVE_NPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006023 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006024#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006025 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006026#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006027
Miss Islington (bot)96177412018-02-25 04:18:43 -08006028#if HAVE_ALPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006029 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006030#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006031 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006032#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006033
6034#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6035 addbool(m, "HAS_SSLv2", 1);
6036#else
6037 addbool(m, "HAS_SSLv2", 0);
6038#endif
6039
6040#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6041 addbool(m, "HAS_SSLv3", 1);
6042#else
6043 addbool(m, "HAS_SSLv3", 0);
6044#endif
6045
6046#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6047 addbool(m, "HAS_TLSv1", 1);
6048#else
6049 addbool(m, "HAS_TLSv1", 0);
6050#endif
6051
6052#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6053 addbool(m, "HAS_TLSv1_1", 1);
6054#else
6055 addbool(m, "HAS_TLSv1_1", 0);
6056#endif
6057
6058#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6059 addbool(m, "HAS_TLSv1_2", 1);
6060#else
6061 addbool(m, "HAS_TLSv1_2", 0);
6062#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006063
Christian Heimescb5b68a2017-09-07 18:07:00 -07006064#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006065 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006066#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08006067 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006068#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006069
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006070 /* Mappings for error codes */
6071 err_codes_to_names = PyDict_New();
6072 err_names_to_codes = PyDict_New();
6073 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6074 return NULL;
6075 errcode = error_codes;
6076 while (errcode->mnemonic != NULL) {
6077 PyObject *mnemo, *key;
6078 mnemo = PyUnicode_FromString(errcode->mnemonic);
6079 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6080 if (mnemo == NULL || key == NULL)
6081 return NULL;
6082 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6083 return NULL;
6084 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6085 return NULL;
6086 Py_DECREF(key);
6087 Py_DECREF(mnemo);
6088 errcode++;
6089 }
6090 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6091 return NULL;
6092 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6093 return NULL;
6094
6095 lib_codes_to_names = PyDict_New();
6096 if (lib_codes_to_names == NULL)
6097 return NULL;
6098 libcode = library_codes;
6099 while (libcode->library != NULL) {
6100 PyObject *mnemo, *key;
6101 key = PyLong_FromLong(libcode->code);
6102 mnemo = PyUnicode_FromString(libcode->library);
6103 if (key == NULL || mnemo == NULL)
6104 return NULL;
6105 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6106 return NULL;
6107 Py_DECREF(key);
6108 Py_DECREF(mnemo);
6109 libcode++;
6110 }
6111 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6112 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006113
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006114 /* OpenSSL version */
6115 /* SSLeay() gives us the version of the library linked against,
6116 which could be different from the headers version.
6117 */
6118 libver = SSLeay();
6119 r = PyLong_FromUnsignedLong(libver);
6120 if (r == NULL)
6121 return NULL;
6122 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6123 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006124 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006125 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6126 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6127 return NULL;
6128 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6129 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6130 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006131
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006132 libver = OPENSSL_VERSION_NUMBER;
6133 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6134 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6135 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6136 return NULL;
6137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006138 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006139}