blob: 4e3352d9e6616ec77329f2fa60cc5daaf8443066 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010078/* SSL error object */
79static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070080static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010081static PyObject *PySSLZeroReturnErrorObject;
82static PyObject *PySSLWantReadErrorObject;
83static PyObject *PySSLWantWriteErrorObject;
84static PyObject *PySSLSyscallErrorObject;
85static PyObject *PySSLEOFErrorObject;
86
87/* Error mappings */
88static PyObject *err_codes_to_names;
89static PyObject *err_names_to_codes;
90static PyObject *lib_codes_to_names;
91
92struct py_ssl_error_code {
93 const char *mnemonic;
94 int library, reason;
95};
96struct py_ssl_library_code {
97 const char *library;
98 int code;
99};
100
Steve Dower68d663c2017-07-17 11:15:48 +0200101#if defined(MS_WINDOWS) && defined(Py_DEBUG)
102/* Debug builds on Windows rely on getting errno directly from OpenSSL.
103 * However, because it uses a different CRT, we need to transfer the
104 * value of errno from OpenSSL into our debug CRT.
105 *
106 * Don't be fooled - this is horribly ugly code. The only reasonable
107 * alternative is to do both debug and release builds of OpenSSL, which
108 * requires much uglier code to transform their automatically generated
109 * makefile. This is the lesser of all the evils.
110 */
111
112static void _PySSLFixErrno(void) {
113 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
114 if (!ucrtbase) {
115 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
116 * have a catastrophic failure, but this function is not the
117 * place to raise it. */
118 return;
119 }
120
121 typedef int *(__stdcall *errno_func)(void);
122 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
123 if (ssl_errno) {
124 errno = *ssl_errno();
125 *ssl_errno() = 0;
126 } else {
127 errno = ENOTRECOVERABLE;
128 }
129}
130
131#undef _PySSL_FIX_ERRNO
132#define _PySSL_FIX_ERRNO _PySSLFixErrno()
133#endif
134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135/* Include generated data (error codes) */
136#include "_ssl_data.h"
137
Christian Heimes598894f2016-09-05 23:19:05 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
139# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100140# define PY_OPENSSL_1_1_API 1
141#endif
142
143/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
144#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
145# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200146#endif
147
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
149 http://www.openssl.org/news/changelog.html
150 */
151#if OPENSSL_VERSION_NUMBER >= 0x10001000L
152# define HAVE_TLSv1_2 1
153#else
154# define HAVE_TLSv1_2 0
155#endif
156
Christian Heimes470fba12013-11-28 15:12:15 +0100157/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100158 * This includes the SSL_set_SSL_CTX() function.
159 */
160#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
161# define HAVE_SNI 1
162#else
163# define HAVE_SNI 0
164#endif
165
Benjamin Petersond3308222015-09-27 00:09:02 -0700166#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Christian Heimes6cdb7952018-02-24 22:12:40 +0100172/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
173 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
174 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
175 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100182#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100183# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100184#else
Christian Heimes29eab552018-02-25 12:31:33 +0100185# define HAVE_NPN 0
186#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100187
Victor Stinner524714e2016-07-22 17:43:59 +0200188#ifndef INVALID_SOCKET /* MS defines this */
189#define INVALID_SOCKET (-1)
190#endif
191
Christian Heimes4ca07392018-03-24 15:41:37 +0100192/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
193#ifndef OPENSSL_VERSION_1_1
194#define HAVE_OPENSSL_CRYPTO_LOCK
195#endif
196
197#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200198#define OPENSSL_NO_SSL2
199#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100200
201#ifndef PY_OPENSSL_1_1_API
202/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200203
204#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200205#define TLS_client_method SSLv23_client_method
206#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
209{
210 return ne->set;
211}
212
213#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200214/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200215static int COMP_get_type(const COMP_METHOD *meth)
216{
217 return meth->type;
218}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200219/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200220#endif
221
222static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
223{
224 return ctx->default_passwd_callback;
225}
226
227static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
228{
229 return ctx->default_passwd_callback_userdata;
230}
231
232static int X509_OBJECT_get_type(X509_OBJECT *x)
233{
234 return x->type;
235}
236
237static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
238{
239 return x->data.x509;
240}
241
242static int BIO_up_ref(BIO *b)
243{
244 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
245 return 1;
246}
247
248static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
249 return store->objs;
250}
251
Christian Heimes99a65702016-09-10 23:44:53 +0200252static int
253SSL_SESSION_has_ticket(const SSL_SESSION *s)
254{
255 return (s->tlsext_ticklen > 0) ? 1 : 0;
256}
257
258static unsigned long
259SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
260{
261 return s->tlsext_tick_lifetime_hint;
262}
263
Christian Heimes4ca07392018-03-24 15:41:37 +0100264#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200265
Christian Heimes892d66e2018-01-29 14:10:18 +0100266/* Default cipher suites */
267#ifndef PY_SSL_DEFAULT_CIPHERS
268#define PY_SSL_DEFAULT_CIPHERS 1
269#endif
270
271#if PY_SSL_DEFAULT_CIPHERS == 0
272 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
273 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
274 #endif
275#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200276/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100277 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
278 * !aNULL:!eNULL: really no NULL ciphers
279 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
280 * !aDSS: no authentication with discrete logarithm DSA algorithm
281 * !SRP:!PSK: no secure remote password or pre-shared key authentication
282 */
283 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
284#elif PY_SSL_DEFAULT_CIPHERS == 2
285/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
286 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
287#else
288 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
289#endif
290
Christian Heimes598894f2016-09-05 23:19:05 +0200291
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000292enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 /* these mirror ssl.h */
294 PY_SSL_ERROR_NONE,
295 PY_SSL_ERROR_SSL,
296 PY_SSL_ERROR_WANT_READ,
297 PY_SSL_ERROR_WANT_WRITE,
298 PY_SSL_ERROR_WANT_X509_LOOKUP,
299 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
300 PY_SSL_ERROR_ZERO_RETURN,
301 PY_SSL_ERROR_WANT_CONNECT,
302 /* start of non ssl.h errorcodes */
303 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
304 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
305 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000306};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000307
Thomas Woutersed03b412007-08-28 21:37:11 +0000308enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 PY_SSL_CLIENT,
310 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000311};
312
313enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 PY_SSL_CERT_NONE,
315 PY_SSL_CERT_OPTIONAL,
316 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000317};
318
319enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200321 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200322 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100323#if HAVE_TLSv1_2
324 PY_SSL_VERSION_TLS1,
325 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200328 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000329#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS_CLIENT=0x10,
331 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100332};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200333
Christian Heimes698dde12018-02-27 11:54:43 +0100334enum py_proto_version {
335 PY_PROTO_MINIMUM_SUPPORTED = -2,
336 PY_PROTO_SSLv3 = SSL3_VERSION,
337 PY_PROTO_TLSv1 = TLS1_VERSION,
338 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
339 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
340#ifdef TLS1_3_VERSION
341 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
342#else
343 PY_PROTO_TLSv1_3 = 0x304,
344#endif
345 PY_PROTO_MAXIMUM_SUPPORTED = -1,
346
347/* OpenSSL has no dedicated API to set the minimum version to the maximum
348 * available version, and the other way around. We have to figure out the
349 * minimum and maximum available version on our own and hope for the best.
350 */
351#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
352 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
353#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
354 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
355#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
357#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
359#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
361#else
362 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
363#endif
364
365#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
366 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
367#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
368 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
369#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
371#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
373#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
375#else
376 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
377#endif
378};
379
380
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000381/* serves as a flag to see whether we've initialized the SSL thread support. */
382/* 0 means no, greater than 0 means yes */
383
384static unsigned int _ssl_locks_count = 0;
385
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386/* SSL socket object */
387
388#define X509_NAME_MAXLEN 256
389
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000390/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
391 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
392 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
393#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000394# define HAVE_SSL_CTX_CLEAR_OPTIONS
395#else
396# undef HAVE_SSL_CTX_CLEAR_OPTIONS
397#endif
398
Antoine Pitroud6494802011-07-21 01:11:30 +0200399/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
400 * older SSL, but let's be safe */
401#define PySSL_CB_MAXLEN 128
402
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100403
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000406 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100407#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500408 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100409 int npn_protocols_len;
410#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100411#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300413 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500414#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100415#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100416 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100417#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100418 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100419 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
420 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
421 */
422 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100423 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200424#ifdef TLS1_3_VERSION
425 int post_handshake_auth;
426#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000427} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000428
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700430 int ssl; /* last seen error from SSL */
431 int c; /* last seen error from libc */
432#ifdef MS_WINDOWS
433 int ws; /* last seen error from winsock */
434#endif
435} _PySSLError;
436
437typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438 PyObject_HEAD
439 PyObject *Socket; /* weakref to socket on which we're layered */
440 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100441 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200442 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200443 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200444 PyObject *owner; /* Python level "owner" passed to servername callback */
445 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700446 _PySSLError err; /* last seen error from various sources */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000448
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200449typedef struct {
450 PyObject_HEAD
451 BIO *bio;
452 int eof_written;
453} PySSLMemoryBIO;
454
Christian Heimes99a65702016-09-10 23:44:53 +0200455typedef struct {
456 PyObject_HEAD
457 SSL_SESSION *session;
458 PySSLContext *ctx;
459} PySSLSession;
460
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461static PyTypeObject PySSLContext_Type;
462static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200463static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200464static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000465
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700466static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
467{
468 _PySSLError err = { 0 };
469 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700470#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700471 err.ws = WSAGetLastError();
472 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700473#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700474 err.c = errno;
475 err.ssl = SSL_get_error(ssl, retcode);
476 }
477 return err;
478}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300480/*[clinic input]
481module _ssl
482class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
483class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
484class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200485class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300486[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200487/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300488
489#include "clinic/_ssl.c.h"
490
Victor Stinner14690702015-04-06 22:46:13 +0200491static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000492
Christian Heimes141c5e82018-02-24 21:10:57 +0100493static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
494static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000495#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200496#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200497#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000498
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000499typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000500 SOCKET_IS_NONBLOCKING,
501 SOCKET_IS_BLOCKING,
502 SOCKET_HAS_TIMED_OUT,
503 SOCKET_HAS_BEEN_CLOSED,
504 SOCKET_TOO_LARGE_FOR_SELECT,
505 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000506} timeout_state;
507
Thomas Woutersed03b412007-08-28 21:37:11 +0000508/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000509#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200510#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000511
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512/* Get the socket from a PySSLSocket, if it has one */
513#define GET_SOCKET(obj) ((obj)->Socket ? \
514 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200515
Victor Stinner14690702015-04-06 22:46:13 +0200516/* If sock is NULL, use a timeout of 0 second */
517#define GET_SOCKET_TIMEOUT(sock) \
518 ((sock != NULL) ? (sock)->sock_timeout : 0)
519
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520/*
521 * SSL errors.
522 */
523
524PyDoc_STRVAR(SSLError_doc,
525"An error occurred in the SSL implementation.");
526
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700527PyDoc_STRVAR(SSLCertVerificationError_doc,
528"A certificate could not be verified.");
529
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200530PyDoc_STRVAR(SSLZeroReturnError_doc,
531"SSL/TLS session closed cleanly.");
532
533PyDoc_STRVAR(SSLWantReadError_doc,
534"Non-blocking SSL socket needs to read more data\n"
535"before the requested operation can be completed.");
536
537PyDoc_STRVAR(SSLWantWriteError_doc,
538"Non-blocking SSL socket needs to write more data\n"
539"before the requested operation can be completed.");
540
541PyDoc_STRVAR(SSLSyscallError_doc,
542"System error when attempting SSL operation.");
543
544PyDoc_STRVAR(SSLEOFError_doc,
545"SSL/TLS connection terminated abruptly.");
546
547static PyObject *
548SSLError_str(PyOSErrorObject *self)
549{
550 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
551 Py_INCREF(self->strerror);
552 return self->strerror;
553 }
554 else
555 return PyObject_Str(self->args);
556}
557
558static PyType_Slot sslerror_type_slots[] = {
559 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
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;
Steve Dowerc6fd1c12018-09-17 11:34:47 -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) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700720 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000721
Steve Dowerc6fd1c12018-09-17 11:34:47 -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
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700758 if (err.ws) {
759 return PyErr_SetFromWindowsErr(err.ws);
760 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700761#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -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
Christian Heimes11a14932018-02-24 02:35:08 +0100848 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) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200863 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,
Christian Heimes141c5e82018-02-24 21:10:57 +0100888 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;
Steve Dowerc6fd1c12018-09-17 11:34:47 -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;
Steve Dowerc6fd1c12018-09-17 11:34:47 -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 */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000910
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000912 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000913 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700914 if (self->ssl == NULL) {
915 Py_DECREF(self);
916 _setSSLError(NULL, 0, __FILE__, __LINE__);
917 return NULL;
918 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 SSL_set_app_data(self->ssl, self);
920 if (sock) {
921 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
922 } else {
923 /* BIOs are reference counted and SSL_set_bio borrows our reference.
924 * To prevent a double free in memory_bio_dealloc() we need to take an
925 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200926 BIO_up_ref(inbio->bio);
927 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200928 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
929 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400930 SSL_set_mode(self->ssl,
931 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000932
Christian Heimes61d478c2018-01-27 15:51:38 +0100933 if (server_hostname != NULL) {
934 if (_ssl_configure_hostname(self, server_hostname) < 0) {
935 Py_DECREF(self);
936 return NULL;
937 }
938 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 /* If the socket is in non-blocking mode or timeout mode, set the BIO
940 * to non-blocking mode (blocking is the default)
941 */
Victor Stinnere2452312015-03-28 03:00:46 +0100942 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
944 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
945 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 PySSL_BEGIN_ALLOW_THREADS
948 if (socket_type == PY_SSL_CLIENT)
949 SSL_set_connect_state(self->ssl);
950 else
951 SSL_set_accept_state(self->ssl);
952 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000953
Antoine Pitroud6494802011-07-21 01:11:30 +0200954 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200955 if (sock != NULL) {
956 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
957 if (self->Socket == NULL) {
958 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200959 return NULL;
960 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100961 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100962 if (owner && owner != Py_None) {
963 if (PySSL_set_owner(self, owner, NULL) == -1) {
964 Py_DECREF(self);
965 return NULL;
966 }
967 }
968 if (session && session != Py_None) {
969 if (PySSL_set_session(self, session, NULL) == -1) {
970 Py_DECREF(self);
971 return NULL;
972 }
973 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000975}
976
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000977/* SSL object methods */
978
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300979/*[clinic input]
980_ssl._SSLSocket.do_handshake
981[clinic start generated code]*/
982
983static PyObject *
984_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
985/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000986{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700988 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200990 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200991 _PyTime_t timeout, deadline = 0;
992 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000993
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200994 if (sock) {
995 if (((PyObject*)sock) == Py_None) {
996 _setSSLError("Underlying socket connection gone",
997 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
998 return NULL;
999 }
1000 Py_INCREF(sock);
1001
1002 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001003 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001004 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1005 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001007
Victor Stinner14690702015-04-06 22:46:13 +02001008 timeout = GET_SOCKET_TIMEOUT(sock);
1009 has_timeout = (timeout > 0);
1010 if (has_timeout)
1011 deadline = _PyTime_GetMonotonicClock() + timeout;
1012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 /* Actually negotiate SSL connection */
1014 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001015 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001016 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001017 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001018 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001020 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001021
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001022 if (PyErr_CheckSignals())
1023 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001024
Victor Stinner14690702015-04-06 22:46:13 +02001025 if (has_timeout)
1026 timeout = deadline - _PyTime_GetMonotonicClock();
1027
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001028 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001029 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001030 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001031 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 } else {
1033 sockstate = SOCKET_OPERATION_OK;
1034 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001037 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001038 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001039 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1041 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001042 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001043 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1045 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001046 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001047 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1049 break;
1050 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001051 } while (err.ssl == SSL_ERROR_WANT_READ ||
1052 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001053 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 if (ret < 1)
1055 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001056
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001057 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001058
1059error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001060 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001061 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001062}
1063
Thomas Woutersed03b412007-08-28 21:37:11 +00001064static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001065_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1066{
1067 char buf[X509_NAME_MAXLEN];
1068 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001070 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001071
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001072 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 if (buflen < 0) {
1074 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001075 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001077 /* initial buffer is too small for oid + terminating null byte */
1078 if (buflen > X509_NAME_MAXLEN - 1) {
1079 /* make OBJ_obj2txt() calculate the required buflen */
1080 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1081 /* allocate len + 1 for terminating NULL byte */
1082 namebuf = PyMem_Malloc(buflen + 1);
1083 if (namebuf == NULL) {
1084 PyErr_NoMemory();
1085 return NULL;
1086 }
1087 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1088 if (buflen < 0) {
1089 _setSSLError(NULL, 0, __FILE__, __LINE__);
1090 goto done;
1091 }
1092 }
1093 if (!buflen && no_name) {
1094 Py_INCREF(Py_None);
1095 name_obj = Py_None;
1096 }
1097 else {
1098 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1099 }
1100
1101 done:
1102 if (buf != namebuf) {
1103 PyMem_Free(namebuf);
1104 }
1105 return name_obj;
1106}
1107
1108static PyObject *
1109_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1110{
1111 Py_ssize_t buflen;
1112 unsigned char *valuebuf = NULL;
1113 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001114
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1116 if (buflen < 0) {
1117 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001118 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001120 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001123}
1124
1125static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001127{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1129 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1130 PyObject *rdnt;
1131 PyObject *attr = NULL; /* tuple to hold an attribute */
1132 int entry_count = X509_NAME_entry_count(xname);
1133 X509_NAME_ENTRY *entry;
1134 ASN1_OBJECT *name;
1135 ASN1_STRING *value;
1136 int index_counter;
1137 int rdn_level = -1;
1138 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 dn = PyList_New(0);
1141 if (dn == NULL)
1142 return NULL;
1143 /* now create another tuple to hold the top-level RDN */
1144 rdn = PyList_New(0);
1145 if (rdn == NULL)
1146 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 for (index_counter = 0;
1149 index_counter < entry_count;
1150 index_counter++)
1151 {
1152 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001153
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 /* check to see if we've gotten to a new RDN */
1155 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001156 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 /* yes, new RDN */
1158 /* add old RDN to DN */
1159 rdnt = PyList_AsTuple(rdn);
1160 Py_DECREF(rdn);
1161 if (rdnt == NULL)
1162 goto fail0;
1163 retcode = PyList_Append(dn, rdnt);
1164 Py_DECREF(rdnt);
1165 if (retcode < 0)
1166 goto fail0;
1167 /* create new RDN */
1168 rdn = PyList_New(0);
1169 if (rdn == NULL)
1170 goto fail0;
1171 }
1172 }
Christian Heimes598894f2016-09-05 23:19:05 +02001173 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 /* now add this attribute to the current RDN */
1176 name = X509_NAME_ENTRY_get_object(entry);
1177 value = X509_NAME_ENTRY_get_data(entry);
1178 attr = _create_tuple_for_attribute(name, value);
1179 /*
1180 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1181 entry->set,
1182 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1183 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1184 */
1185 if (attr == NULL)
1186 goto fail1;
1187 retcode = PyList_Append(rdn, attr);
1188 Py_DECREF(attr);
1189 if (retcode < 0)
1190 goto fail1;
1191 }
1192 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001193 if (rdn != NULL) {
1194 if (PyList_GET_SIZE(rdn) > 0) {
1195 rdnt = PyList_AsTuple(rdn);
1196 Py_DECREF(rdn);
1197 if (rdnt == NULL)
1198 goto fail0;
1199 retcode = PyList_Append(dn, rdnt);
1200 Py_DECREF(rdnt);
1201 if (retcode < 0)
1202 goto fail0;
1203 }
1204 else {
1205 Py_DECREF(rdn);
1206 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 /* convert list to tuple */
1210 rdnt = PyList_AsTuple(dn);
1211 Py_DECREF(dn);
1212 if (rdnt == NULL)
1213 return NULL;
1214 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215
1216 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001218
1219 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 Py_XDECREF(dn);
1221 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222}
1223
1224static PyObject *
1225_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 /* this code follows the procedure outlined in
1228 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1229 function to extract the STACK_OF(GENERAL_NAME),
1230 then iterates through the stack to add the
1231 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001233 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001235 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 GENERAL_NAMES *names = NULL;
1237 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 BIO *biobuf = NULL;
1239 char buf[2048];
1240 char *vptr;
1241 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 if (certificate == NULL)
1244 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 /* get a memory buffer */
1247 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001248 if (biobuf == NULL) {
1249 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1250 return NULL;
1251 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001253 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1254 certificate, NID_subject_alt_name, NULL, NULL);
1255 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 if (peer_alt_names == Py_None) {
1257 peer_alt_names = PyList_New(0);
1258 if (peer_alt_names == NULL)
1259 goto fail;
1260 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001264 int gntype;
1265 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001268 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001269 switch (gntype) {
1270 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 /* we special-case DirName as a tuple of
1272 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 t = PyTuple_New(2);
1275 if (t == NULL) {
1276 goto fail;
1277 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 v = PyUnicode_FromString("DirName");
1280 if (v == NULL) {
1281 Py_DECREF(t);
1282 goto fail;
1283 }
1284 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 v = _create_tuple_for_X509_NAME (name->d.dirn);
1287 if (v == NULL) {
1288 Py_DECREF(t);
1289 goto fail;
1290 }
1291 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001292 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001293
Christian Heimes824f7f32013-08-17 00:54:47 +02001294 case GEN_EMAIL:
1295 case GEN_DNS:
1296 case GEN_URI:
1297 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1298 correctly, CVE-2013-4238 */
1299 t = PyTuple_New(2);
1300 if (t == NULL)
1301 goto fail;
1302 switch (gntype) {
1303 case GEN_EMAIL:
1304 v = PyUnicode_FromString("email");
1305 as = name->d.rfc822Name;
1306 break;
1307 case GEN_DNS:
1308 v = PyUnicode_FromString("DNS");
1309 as = name->d.dNSName;
1310 break;
1311 case GEN_URI:
1312 v = PyUnicode_FromString("URI");
1313 as = name->d.uniformResourceIdentifier;
1314 break;
1315 }
1316 if (v == NULL) {
1317 Py_DECREF(t);
1318 goto fail;
1319 }
1320 PyTuple_SET_ITEM(t, 0, v);
1321 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1322 ASN1_STRING_length(as));
1323 if (v == NULL) {
1324 Py_DECREF(t);
1325 goto fail;
1326 }
1327 PyTuple_SET_ITEM(t, 1, v);
1328 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329
Christian Heimes1c03abd2016-09-06 23:25:35 +02001330 case GEN_RID:
1331 t = PyTuple_New(2);
1332 if (t == NULL)
1333 goto fail;
1334
1335 v = PyUnicode_FromString("Registered ID");
1336 if (v == NULL) {
1337 Py_DECREF(t);
1338 goto fail;
1339 }
1340 PyTuple_SET_ITEM(t, 0, v);
1341
1342 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1343 if (len < 0) {
1344 Py_DECREF(t);
1345 _setSSLError(NULL, 0, __FILE__, __LINE__);
1346 goto fail;
1347 } else if (len >= (int)sizeof(buf)) {
1348 v = PyUnicode_FromString("<INVALID>");
1349 } else {
1350 v = PyUnicode_FromStringAndSize(buf, len);
1351 }
1352 if (v == NULL) {
1353 Py_DECREF(t);
1354 goto fail;
1355 }
1356 PyTuple_SET_ITEM(t, 1, v);
1357 break;
1358
Christian Heimes824f7f32013-08-17 00:54:47 +02001359 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001361 switch (gntype) {
1362 /* check for new general name type */
1363 case GEN_OTHERNAME:
1364 case GEN_X400:
1365 case GEN_EDIPARTY:
1366 case GEN_IPADD:
1367 case GEN_RID:
1368 break;
1369 default:
1370 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1371 "Unknown general name type %d",
1372 gntype) == -1) {
1373 goto fail;
1374 }
1375 break;
1376 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 (void) BIO_reset(biobuf);
1378 GENERAL_NAME_print(biobuf, name);
1379 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1380 if (len < 0) {
1381 _setSSLError(NULL, 0, __FILE__, __LINE__);
1382 goto fail;
1383 }
1384 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001385 if (vptr == NULL) {
1386 PyErr_Format(PyExc_ValueError,
1387 "Invalid value %.200s",
1388 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001390 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 t = PyTuple_New(2);
1392 if (t == NULL)
1393 goto fail;
1394 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1395 if (v == NULL) {
1396 Py_DECREF(t);
1397 goto fail;
1398 }
1399 PyTuple_SET_ITEM(t, 0, v);
1400 v = PyUnicode_FromStringAndSize((vptr + 1),
1401 (len - (vptr - buf + 1)));
1402 if (v == NULL) {
1403 Py_DECREF(t);
1404 goto fail;
1405 }
1406 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001407 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001409
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001411
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412 if (PyList_Append(peer_alt_names, t) < 0) {
1413 Py_DECREF(t);
1414 goto fail;
1415 }
1416 Py_DECREF(t);
1417 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001418 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 }
1420 BIO_free(biobuf);
1421 if (peer_alt_names != Py_None) {
1422 v = PyList_AsTuple(peer_alt_names);
1423 Py_DECREF(peer_alt_names);
1424 return v;
1425 } else {
1426 return peer_alt_names;
1427 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001428
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001429
1430 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 if (biobuf != NULL)
1432 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 if (peer_alt_names != Py_None) {
1435 Py_XDECREF(peer_alt_names);
1436 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001437
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001438 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001439}
1440
1441static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001442_get_aia_uri(X509 *certificate, int nid) {
1443 PyObject *lst = NULL, *ostr = NULL;
1444 int i, result;
1445 AUTHORITY_INFO_ACCESS *info;
1446
1447 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001448 if (info == NULL)
1449 return Py_None;
1450 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1451 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001452 return Py_None;
1453 }
1454
1455 if ((lst = PyList_New(0)) == NULL) {
1456 goto fail;
1457 }
1458
1459 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1460 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1461 ASN1_IA5STRING *uri;
1462
1463 if ((OBJ_obj2nid(ad->method) != nid) ||
1464 (ad->location->type != GEN_URI)) {
1465 continue;
1466 }
1467 uri = ad->location->d.uniformResourceIdentifier;
1468 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1469 uri->length);
1470 if (ostr == NULL) {
1471 goto fail;
1472 }
1473 result = PyList_Append(lst, ostr);
1474 Py_DECREF(ostr);
1475 if (result < 0) {
1476 goto fail;
1477 }
1478 }
1479 AUTHORITY_INFO_ACCESS_free(info);
1480
1481 /* convert to tuple or None */
1482 if (PyList_Size(lst) == 0) {
1483 Py_DECREF(lst);
1484 return Py_None;
1485 } else {
1486 PyObject *tup;
1487 tup = PyList_AsTuple(lst);
1488 Py_DECREF(lst);
1489 return tup;
1490 }
1491
1492 fail:
1493 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001494 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001495 return NULL;
1496}
1497
1498static PyObject *
1499_get_crl_dp(X509 *certificate) {
1500 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001501 int i, j;
1502 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001503
Christian Heimes598894f2016-09-05 23:19:05 +02001504 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001505
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001506 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001507 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001508
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001509 lst = PyList_New(0);
1510 if (lst == NULL)
1511 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001512
1513 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1514 DIST_POINT *dp;
1515 STACK_OF(GENERAL_NAME) *gns;
1516
1517 dp = sk_DIST_POINT_value(dps, i);
1518 gns = dp->distpoint->name.fullname;
1519
1520 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1521 GENERAL_NAME *gn;
1522 ASN1_IA5STRING *uri;
1523 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001524 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001525
1526 gn = sk_GENERAL_NAME_value(gns, j);
1527 if (gn->type != GEN_URI) {
1528 continue;
1529 }
1530 uri = gn->d.uniformResourceIdentifier;
1531 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1532 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001533 if (ouri == NULL)
1534 goto done;
1535
1536 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001537 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001538 if (err < 0)
1539 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001540 }
1541 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001542
1543 /* Convert to tuple. */
1544 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1545
1546 done:
1547 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001548 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001549 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001550}
1551
1552static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001553_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 PyObject *retval = NULL;
1556 BIO *biobuf = NULL;
1557 PyObject *peer;
1558 PyObject *peer_alt_names = NULL;
1559 PyObject *issuer;
1560 PyObject *version;
1561 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001562 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 ASN1_INTEGER *serialNumber;
1564 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001565 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 ASN1_TIME *notBefore, *notAfter;
1567 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001568
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 retval = PyDict_New();
1570 if (retval == NULL)
1571 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 peer = _create_tuple_for_X509_NAME(
1574 X509_get_subject_name(certificate));
1575 if (peer == NULL)
1576 goto fail0;
1577 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1578 Py_DECREF(peer);
1579 goto fail0;
1580 }
1581 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001582
Antoine Pitroufb046912010-11-09 20:21:19 +00001583 issuer = _create_tuple_for_X509_NAME(
1584 X509_get_issuer_name(certificate));
1585 if (issuer == NULL)
1586 goto fail0;
1587 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001588 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001589 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001590 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001591 Py_DECREF(issuer);
1592
1593 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001594 if (version == NULL)
1595 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001596 if (PyDict_SetItemString(retval, "version", version) < 0) {
1597 Py_DECREF(version);
1598 goto fail0;
1599 }
1600 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001601
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 /* get a memory buffer */
1603 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001604 if (biobuf == NULL) {
1605 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1606 goto fail0;
1607 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001608
Antoine Pitroufb046912010-11-09 20:21:19 +00001609 (void) BIO_reset(biobuf);
1610 serialNumber = X509_get_serialNumber(certificate);
1611 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1612 i2a_ASN1_INTEGER(biobuf, serialNumber);
1613 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1614 if (len < 0) {
1615 _setSSLError(NULL, 0, __FILE__, __LINE__);
1616 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001617 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001618 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1619 if (sn_obj == NULL)
1620 goto fail1;
1621 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1622 Py_DECREF(sn_obj);
1623 goto fail1;
1624 }
1625 Py_DECREF(sn_obj);
1626
1627 (void) BIO_reset(biobuf);
1628 notBefore = X509_get_notBefore(certificate);
1629 ASN1_TIME_print(biobuf, notBefore);
1630 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1631 if (len < 0) {
1632 _setSSLError(NULL, 0, __FILE__, __LINE__);
1633 goto fail1;
1634 }
1635 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1636 if (pnotBefore == NULL)
1637 goto fail1;
1638 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1639 Py_DECREF(pnotBefore);
1640 goto fail1;
1641 }
1642 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 (void) BIO_reset(biobuf);
1645 notAfter = X509_get_notAfter(certificate);
1646 ASN1_TIME_print(biobuf, notAfter);
1647 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1648 if (len < 0) {
1649 _setSSLError(NULL, 0, __FILE__, __LINE__);
1650 goto fail1;
1651 }
1652 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1653 if (pnotAfter == NULL)
1654 goto fail1;
1655 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1656 Py_DECREF(pnotAfter);
1657 goto fail1;
1658 }
1659 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001660
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001661 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 peer_alt_names = _get_peer_alt_names(certificate);
1664 if (peer_alt_names == NULL)
1665 goto fail1;
1666 else if (peer_alt_names != Py_None) {
1667 if (PyDict_SetItemString(retval, "subjectAltName",
1668 peer_alt_names) < 0) {
1669 Py_DECREF(peer_alt_names);
1670 goto fail1;
1671 }
1672 Py_DECREF(peer_alt_names);
1673 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001674
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001675 /* Authority Information Access: OCSP URIs */
1676 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1677 if (obj == NULL) {
1678 goto fail1;
1679 } else if (obj != Py_None) {
1680 result = PyDict_SetItemString(retval, "OCSP", obj);
1681 Py_DECREF(obj);
1682 if (result < 0) {
1683 goto fail1;
1684 }
1685 }
1686
1687 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1688 if (obj == NULL) {
1689 goto fail1;
1690 } else if (obj != Py_None) {
1691 result = PyDict_SetItemString(retval, "caIssuers", obj);
1692 Py_DECREF(obj);
1693 if (result < 0) {
1694 goto fail1;
1695 }
1696 }
1697
1698 /* CDP (CRL distribution points) */
1699 obj = _get_crl_dp(certificate);
1700 if (obj == NULL) {
1701 goto fail1;
1702 } else if (obj != Py_None) {
1703 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1704 Py_DECREF(obj);
1705 if (result < 0) {
1706 goto fail1;
1707 }
1708 }
1709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001710 BIO_free(biobuf);
1711 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001712
1713 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 if (biobuf != NULL)
1715 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001716 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001717 Py_XDECREF(retval);
1718 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001719}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001720
Christian Heimes9a5395a2013-06-17 15:44:12 +02001721static PyObject *
1722_certificate_to_der(X509 *certificate)
1723{
1724 unsigned char *bytes_buf = NULL;
1725 int len;
1726 PyObject *retval;
1727
1728 bytes_buf = NULL;
1729 len = i2d_X509(certificate, &bytes_buf);
1730 if (len < 0) {
1731 _setSSLError(NULL, 0, __FILE__, __LINE__);
1732 return NULL;
1733 }
1734 /* this is actually an immutable bytes sequence */
1735 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1736 OPENSSL_free(bytes_buf);
1737 return retval;
1738}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001740/*[clinic input]
1741_ssl._test_decode_cert
1742 path: object(converter="PyUnicode_FSConverter")
1743 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745[clinic start generated code]*/
1746
1747static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001748_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1749/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001750{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 X509 *x=NULL;
1753 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1756 PyErr_SetString(PySSLErrorObject,
1757 "Can't malloc memory to read file");
1758 goto fail0;
1759 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001760
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001761 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001762 PyErr_SetString(PySSLErrorObject,
1763 "Can't open file");
1764 goto fail0;
1765 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001767 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1768 if (x == NULL) {
1769 PyErr_SetString(PySSLErrorObject,
1770 "Error decoding PEM-encoded file");
1771 goto fail0;
1772 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001773
Antoine Pitroufb046912010-11-09 20:21:19 +00001774 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001775 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001776
1777 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001778 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 if (cert != NULL) BIO_free(cert);
1780 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781}
1782
1783
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001784/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001785_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001786 der as binary_mode: bool = False
1787 /
1788
1789Returns the certificate for the peer.
1790
1791If no certificate was provided, returns None. If a certificate was
1792provided, but not validated, returns an empty dictionary. Otherwise
1793returns a dict containing information about the peer certificate.
1794
1795If the optional argument is True, returns a DER-encoded copy of the
1796peer certificate, or None if no certificate was provided. This will
1797return the certificate even if it wasn't validated.
1798[clinic start generated code]*/
1799
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001800static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001801_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1802/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001803{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001805 X509 *peer_cert;
1806 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001807
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001809 PyErr_SetString(PyExc_ValueError,
1810 "handshake not done yet");
1811 return NULL;
1812 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001813 peer_cert = SSL_get_peer_certificate(self->ssl);
1814 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001816
Antoine Pitrou721738f2012-08-15 23:20:39 +02001817 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001819 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001821 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001823 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001825 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001827 X509_free(peer_cert);
1828 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001829}
1830
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001831static PyObject *
1832cipher_to_tuple(const SSL_CIPHER *cipher)
1833{
1834 const char *cipher_name, *cipher_protocol;
1835 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 if (retval == NULL)
1837 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001838
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001839 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001841 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 PyTuple_SET_ITEM(retval, 0, Py_None);
1843 } else {
1844 v = PyUnicode_FromString(cipher_name);
1845 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001846 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 PyTuple_SET_ITEM(retval, 0, v);
1848 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001849
1850 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001852 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 PyTuple_SET_ITEM(retval, 1, Py_None);
1854 } else {
1855 v = PyUnicode_FromString(cipher_protocol);
1856 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001857 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 PyTuple_SET_ITEM(retval, 1, v);
1859 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001860
1861 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001863 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001866 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001867
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001868 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 Py_DECREF(retval);
1870 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001871}
1872
Christian Heimes25bfcd52016-09-06 00:04:45 +02001873#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1874static PyObject *
1875cipher_to_dict(const SSL_CIPHER *cipher)
1876{
1877 const char *cipher_name, *cipher_protocol;
1878
1879 unsigned long cipher_id;
1880 int alg_bits, strength_bits, len;
1881 char buf[512] = {0};
1882#if OPENSSL_VERSION_1_1
1883 int aead, nid;
1884 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1885#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001886
1887 /* can be NULL */
1888 cipher_name = SSL_CIPHER_get_name(cipher);
1889 cipher_protocol = SSL_CIPHER_get_version(cipher);
1890 cipher_id = SSL_CIPHER_get_id(cipher);
1891 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001892 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1893 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001894 if (len > 1 && buf[len-1] == '\n')
1895 buf[len-1] = '\0';
1896 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1897
1898#if OPENSSL_VERSION_1_1
1899 aead = SSL_CIPHER_is_aead(cipher);
1900 nid = SSL_CIPHER_get_cipher_nid(cipher);
1901 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1902 nid = SSL_CIPHER_get_digest_nid(cipher);
1903 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1904 nid = SSL_CIPHER_get_kx_nid(cipher);
1905 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1906 nid = SSL_CIPHER_get_auth_nid(cipher);
1907 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1908#endif
1909
Victor Stinner410b9882016-09-12 12:00:23 +02001910 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001911 "{sksssssssisi"
1912#if OPENSSL_VERSION_1_1
1913 "sOssssssss"
1914#endif
1915 "}",
1916 "id", cipher_id,
1917 "name", cipher_name,
1918 "protocol", cipher_protocol,
1919 "description", buf,
1920 "strength_bits", strength_bits,
1921 "alg_bits", alg_bits
1922#if OPENSSL_VERSION_1_1
1923 ,"aead", aead ? Py_True : Py_False,
1924 "symmetric", skcipher,
1925 "digest", digest,
1926 "kea", kx,
1927 "auth", auth
1928#endif
1929 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001930}
1931#endif
1932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001933/*[clinic input]
1934_ssl._SSLSocket.shared_ciphers
1935[clinic start generated code]*/
1936
1937static PyObject *
1938_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1939/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001940{
1941 STACK_OF(SSL_CIPHER) *ciphers;
1942 int i;
1943 PyObject *res;
1944
Christian Heimes598894f2016-09-05 23:19:05 +02001945 ciphers = SSL_get_ciphers(self->ssl);
1946 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001947 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001948 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1949 if (!res)
1950 return NULL;
1951 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1952 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1953 if (!tup) {
1954 Py_DECREF(res);
1955 return NULL;
1956 }
1957 PyList_SET_ITEM(res, i, tup);
1958 }
1959 return res;
1960}
1961
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001962/*[clinic input]
1963_ssl._SSLSocket.cipher
1964[clinic start generated code]*/
1965
1966static PyObject *
1967_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1968/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001969{
1970 const SSL_CIPHER *current;
1971
1972 if (self->ssl == NULL)
1973 Py_RETURN_NONE;
1974 current = SSL_get_current_cipher(self->ssl);
1975 if (current == NULL)
1976 Py_RETURN_NONE;
1977 return cipher_to_tuple(current);
1978}
1979
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001980/*[clinic input]
1981_ssl._SSLSocket.version
1982[clinic start generated code]*/
1983
1984static PyObject *
1985_ssl__SSLSocket_version_impl(PySSLSocket *self)
1986/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001987{
1988 const char *version;
1989
1990 if (self->ssl == NULL)
1991 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001992 if (!SSL_is_init_finished(self->ssl)) {
1993 /* handshake not finished */
1994 Py_RETURN_NONE;
1995 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001996 version = SSL_get_version(self->ssl);
1997 if (!strcmp(version, "unknown"))
1998 Py_RETURN_NONE;
1999 return PyUnicode_FromString(version);
2000}
2001
Christian Heimes29eab552018-02-25 12:31:33 +01002002#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002003/*[clinic input]
2004_ssl._SSLSocket.selected_npn_protocol
2005[clinic start generated code]*/
2006
2007static PyObject *
2008_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2009/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2010{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002011 const unsigned char *out;
2012 unsigned int outlen;
2013
Victor Stinner4569cd52013-06-23 14:58:43 +02002014 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002015 &out, &outlen);
2016
2017 if (out == NULL)
2018 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002019 return PyUnicode_FromStringAndSize((char *)out, outlen);
2020}
2021#endif
2022
Christian Heimes29eab552018-02-25 12:31:33 +01002023#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002024/*[clinic input]
2025_ssl._SSLSocket.selected_alpn_protocol
2026[clinic start generated code]*/
2027
2028static PyObject *
2029_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2030/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2031{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002032 const unsigned char *out;
2033 unsigned int outlen;
2034
2035 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2036
2037 if (out == NULL)
2038 Py_RETURN_NONE;
2039 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002040}
2041#endif
2042
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002043/*[clinic input]
2044_ssl._SSLSocket.compression
2045[clinic start generated code]*/
2046
2047static PyObject *
2048_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2049/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2050{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002051#ifdef OPENSSL_NO_COMP
2052 Py_RETURN_NONE;
2053#else
2054 const COMP_METHOD *comp_method;
2055 const char *short_name;
2056
2057 if (self->ssl == NULL)
2058 Py_RETURN_NONE;
2059 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002060 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002061 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002062 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002063 if (short_name == NULL)
2064 Py_RETURN_NONE;
2065 return PyUnicode_DecodeFSDefault(short_name);
2066#endif
2067}
2068
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002069static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2070 Py_INCREF(self->ctx);
2071 return self->ctx;
2072}
2073
2074static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2075 void *closure) {
2076
2077 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002078#if !HAVE_SNI
2079 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2080 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002081 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002082#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002083 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002084 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002086#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002087 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002088 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002089 return -1;
2090 }
2091
2092 return 0;
2093}
2094
2095PyDoc_STRVAR(PySSL_set_context_doc,
2096"_setter_context(ctx)\n\
2097\
2098This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002099used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002100on the SSLContext to change the certificate information associated with the\n\
2101SSLSocket before the cryptographic exchange handshake messages\n");
2102
2103
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002104static PyObject *
2105PySSL_get_server_side(PySSLSocket *self, void *c)
2106{
2107 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2108}
2109
2110PyDoc_STRVAR(PySSL_get_server_side_doc,
2111"Whether this is a server-side socket.");
2112
2113static PyObject *
2114PySSL_get_server_hostname(PySSLSocket *self, void *c)
2115{
2116 if (self->server_hostname == NULL)
2117 Py_RETURN_NONE;
2118 Py_INCREF(self->server_hostname);
2119 return self->server_hostname;
2120}
2121
2122PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2123"The currently set server hostname (for SNI).");
2124
2125static PyObject *
2126PySSL_get_owner(PySSLSocket *self, void *c)
2127{
2128 PyObject *owner;
2129
2130 if (self->owner == NULL)
2131 Py_RETURN_NONE;
2132
2133 owner = PyWeakref_GetObject(self->owner);
2134 Py_INCREF(owner);
2135 return owner;
2136}
2137
2138static int
2139PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2140{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002141 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002142 if (self->owner == NULL)
2143 return -1;
2144 return 0;
2145}
2146
2147PyDoc_STRVAR(PySSL_get_owner_doc,
2148"The Python-level owner of this object.\
2149Passed as \"self\" in servername callback.");
2150
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002151
Antoine Pitrou152efa22010-05-16 18:19:27 +00002152static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002153{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002154 if (self->ssl)
2155 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002157 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002158 Py_XDECREF(self->server_hostname);
2159 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002161}
2162
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002163/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002164 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002165 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002166 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002167
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002168static int
Victor Stinner14690702015-04-06 22:46:13 +02002169PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002170{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002171 int rc;
2172#ifdef HAVE_POLL
2173 struct pollfd pollfd;
2174 _PyTime_t ms;
2175#else
2176 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 fd_set fds;
2178 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002179#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002182 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002183 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002184 else if (timeout < 0) {
2185 if (s->sock_timeout > 0)
2186 return SOCKET_HAS_TIMED_OUT;
2187 else
2188 return SOCKET_IS_BLOCKING;
2189 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002191 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002192 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002194
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 /* Prefer poll, if available, since you can poll() any fd
2196 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002197#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002198 pollfd.fd = s->sock_fd;
2199 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002200
Victor Stinner14690702015-04-06 22:46:13 +02002201 /* timeout is in seconds, poll() uses milliseconds */
2202 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002203 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002204
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002205 PySSL_BEGIN_ALLOW_THREADS
2206 rc = poll(&pollfd, 1, (int)ms);
2207 PySSL_END_ALLOW_THREADS
2208#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002210 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002212
Victor Stinner14690702015-04-06 22:46:13 +02002213 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002214
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002215 FD_ZERO(&fds);
2216 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002217
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002218 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002220 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002222 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002224 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002226#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2229 (when we are able to write or when there's something to read) */
2230 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002231}
2232
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002233/*[clinic input]
2234_ssl._SSLSocket.write
2235 b: Py_buffer
2236 /
2237
2238Writes the bytes-like object b into the SSL object.
2239
2240Returns the number of bytes written.
2241[clinic start generated code]*/
2242
2243static PyObject *
2244_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2245/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002246{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 int len;
2248 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002249 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002251 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002252 _PyTime_t timeout, deadline = 0;
2253 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002254
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002255 if (sock != NULL) {
2256 if (((PyObject*)sock) == Py_None) {
2257 _setSSLError("Underlying socket connection gone",
2258 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2259 return NULL;
2260 }
2261 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 }
2263
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002264 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002265 PyErr_Format(PyExc_OverflowError,
2266 "string longer than %d bytes", INT_MAX);
2267 goto error;
2268 }
2269
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002270 if (sock != NULL) {
2271 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002272 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002273 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2274 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2275 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276
Victor Stinner14690702015-04-06 22:46:13 +02002277 timeout = GET_SOCKET_TIMEOUT(sock);
2278 has_timeout = (timeout > 0);
2279 if (has_timeout)
2280 deadline = _PyTime_GetMonotonicClock() + timeout;
2281
2282 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002284 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 "The write operation timed out");
2286 goto error;
2287 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2288 PyErr_SetString(PySSLErrorObject,
2289 "Underlying socket has been closed.");
2290 goto error;
2291 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2292 PyErr_SetString(PySSLErrorObject,
2293 "Underlying socket too large for select().");
2294 goto error;
2295 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002299 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002300 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002302 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002303
2304 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002306
Victor Stinner14690702015-04-06 22:46:13 +02002307 if (has_timeout)
2308 timeout = deadline - _PyTime_GetMonotonicClock();
2309
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002310 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002311 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002312 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002313 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 } else {
2315 sockstate = SOCKET_OPERATION_OK;
2316 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002319 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 "The write operation timed out");
2321 goto error;
2322 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2323 PyErr_SetString(PySSLErrorObject,
2324 "Underlying socket has been closed.");
2325 goto error;
2326 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2327 break;
2328 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002329 } while (err.ssl == SSL_ERROR_WANT_READ ||
2330 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002331
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002332 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 if (len > 0)
2334 return PyLong_FromLong(len);
2335 else
2336 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002337
2338error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002339 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002341}
2342
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002343/*[clinic input]
2344_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002345
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002346Returns the number of already decrypted bytes available for read, pending on the connection.
2347[clinic start generated code]*/
2348
2349static PyObject *
2350_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2351/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002352{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002354 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002355
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 PySSL_BEGIN_ALLOW_THREADS
2357 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002358 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002360 self->err = err;
2361
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002362 if (count < 0)
2363 return PySSL_SetError(self, count, __FILE__, __LINE__);
2364 else
2365 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002366}
2367
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002368/*[clinic input]
2369_ssl._SSLSocket.read
2370 size as len: int
2371 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002372 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002373 ]
2374 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002375
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002376Read up to size bytes from the SSL socket.
2377[clinic start generated code]*/
2378
2379static PyObject *
2380_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2381 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002382/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002383{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002386 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002388 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002389 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002390 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002391 _PyTime_t timeout, deadline = 0;
2392 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002393
Martin Panter5503d472016-03-27 05:35:19 +00002394 if (!group_right_1 && len < 0) {
2395 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2396 return NULL;
2397 }
2398
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002399 if (sock != NULL) {
2400 if (((PyObject*)sock) == Py_None) {
2401 _setSSLError("Underlying socket connection gone",
2402 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2403 return NULL;
2404 }
2405 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002406 }
2407
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002408 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002409 dest = PyBytes_FromStringAndSize(NULL, len);
2410 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002411 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002412 if (len == 0) {
2413 Py_XDECREF(sock);
2414 return dest;
2415 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002416 mem = PyBytes_AS_STRING(dest);
2417 }
2418 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002419 mem = buffer->buf;
2420 if (len <= 0 || len > buffer->len) {
2421 len = (int) buffer->len;
2422 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002423 PyErr_SetString(PyExc_OverflowError,
2424 "maximum length can't fit in a C 'int'");
2425 goto error;
2426 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002427 if (len == 0) {
2428 count = 0;
2429 goto done;
2430 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002431 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 }
2433
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002434 if (sock != NULL) {
2435 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002436 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002437 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2438 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2439 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440
Victor Stinner14690702015-04-06 22:46:13 +02002441 timeout = GET_SOCKET_TIMEOUT(sock);
2442 has_timeout = (timeout > 0);
2443 if (has_timeout)
2444 deadline = _PyTime_GetMonotonicClock() + timeout;
2445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 PySSL_BEGIN_ALLOW_THREADS
2448 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002449 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002451 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002452
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 if (PyErr_CheckSignals())
2454 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002455
Victor Stinner14690702015-04-06 22:46:13 +02002456 if (has_timeout)
2457 timeout = deadline - _PyTime_GetMonotonicClock();
2458
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002459 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002460 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002461 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002462 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002463 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002464 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002465 {
2466 count = 0;
2467 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002468 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002469 else
2470 sockstate = SOCKET_OPERATION_OK;
2471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002473 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474 "The read operation timed out");
2475 goto error;
2476 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2477 break;
2478 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002479 } while (err.ssl == SSL_ERROR_WANT_READ ||
2480 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002482 if (count <= 0) {
2483 PySSL_SetError(self, count, __FILE__, __LINE__);
2484 goto error;
2485 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002486
2487done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002488 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002489 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002490 _PyBytes_Resize(&dest, count);
2491 return dest;
2492 }
2493 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002494 return PyLong_FromLong(count);
2495 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002496
2497error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002498 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002499 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002500 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002501 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002502}
2503
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002504/*[clinic input]
2505_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002507Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002508[clinic start generated code]*/
2509
2510static PyObject *
2511_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002512/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002513{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002514 _PySSLError err;
2515 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002516 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002517 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002518 _PyTime_t timeout, deadline = 0;
2519 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002520
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002521 if (sock != NULL) {
2522 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002523 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002524 _setSSLError("Underlying socket connection gone",
2525 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2526 return NULL;
2527 }
2528 Py_INCREF(sock);
2529
2530 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002531 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002532 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2533 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535
Victor Stinner14690702015-04-06 22:46:13 +02002536 timeout = GET_SOCKET_TIMEOUT(sock);
2537 has_timeout = (timeout > 0);
2538 if (has_timeout)
2539 deadline = _PyTime_GetMonotonicClock() + timeout;
2540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002541 while (1) {
2542 PySSL_BEGIN_ALLOW_THREADS
2543 /* Disable read-ahead so that unwrap can work correctly.
2544 * Otherwise OpenSSL might read in too much data,
2545 * eating clear text data that happens to be
2546 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002547 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002548 * function is used and the shutdown_seen_zero != 0
2549 * condition is met.
2550 */
2551 if (self->shutdown_seen_zero)
2552 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002553 ret = SSL_shutdown(self->ssl);
2554 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002555 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002556 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002559 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002561 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 /* Don't loop endlessly; instead preserve legacy
2563 behaviour of trying SSL_shutdown() only twice.
2564 This looks necessary for OpenSSL < 0.9.8m */
2565 if (++zeros > 1)
2566 break;
2567 /* Shutdown was sent, now try receiving */
2568 self->shutdown_seen_zero = 1;
2569 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002570 }
2571
Victor Stinner14690702015-04-06 22:46:13 +02002572 if (has_timeout)
2573 timeout = deadline - _PyTime_GetMonotonicClock();
2574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002575 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002576 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002577 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002578 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002579 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 else
2581 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002583 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002584 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002585 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 "The read operation timed out");
2587 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002588 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002589 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002590 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 }
2592 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2593 PyErr_SetString(PySSLErrorObject,
2594 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002595 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 }
2597 else if (sockstate != SOCKET_OPERATION_OK)
2598 /* Retain the SSL error code */
2599 break;
2600 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002601
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002602 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002603 Py_XDECREF(sock);
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002604 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002605 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002606 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002607 /* It's already INCREF'ed */
2608 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002609 else
2610 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002611
2612error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002613 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002614 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002615}
2616
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002617/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002618_ssl._SSLSocket.get_channel_binding
2619 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002620
Christian Heimes141c5e82018-02-24 21:10:57 +01002621Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002622
Christian Heimes141c5e82018-02-24 21:10:57 +01002623Raise ValueError if the requested `cb_type` is not supported. Return bytes
2624of the data or None if the data is not available (e.g. before the handshake).
2625Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002626[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002627
Antoine Pitroud6494802011-07-21 01:11:30 +02002628static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002629_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2630 const char *cb_type)
2631/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002632{
Antoine Pitroud6494802011-07-21 01:11:30 +02002633 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002634 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002635
Christian Heimes141c5e82018-02-24 21:10:57 +01002636 if (strcmp(cb_type, "tls-unique") == 0) {
2637 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2638 /* if session is resumed XOR we are the client */
2639 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2640 }
2641 else {
2642 /* if a new session XOR we are the server */
2643 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2644 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002645 }
2646 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002647 PyErr_Format(
2648 PyExc_ValueError,
2649 "'%s' channel binding type not implemented",
2650 cb_type
2651 );
2652 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002653 }
2654
2655 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002656 if (len == 0)
2657 Py_RETURN_NONE;
2658
Christian Heimes141c5e82018-02-24 21:10:57 +01002659 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002660}
2661
Christian Heimes9fb051f2018-09-23 08:32:31 +02002662/*[clinic input]
2663_ssl._SSLSocket.verify_client_post_handshake
2664
2665Initiate TLS 1.3 post-handshake authentication
2666[clinic start generated code]*/
2667
2668static PyObject *
2669_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2670/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2671{
2672#ifdef TLS1_3_VERSION
2673 int err = SSL_verify_client_post_handshake(self->ssl);
2674 if (err == 0)
2675 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2676 else
2677 Py_RETURN_NONE;
2678#else
2679 PyErr_SetString(PyExc_NotImplementedError,
2680 "Post-handshake auth is not supported by your "
2681 "OpenSSL version.");
2682 return NULL;
2683#endif
2684}
2685
Christian Heimes99a65702016-09-10 23:44:53 +02002686#ifdef OPENSSL_VERSION_1_1
2687
2688static SSL_SESSION*
2689_ssl_session_dup(SSL_SESSION *session) {
2690 SSL_SESSION *newsession = NULL;
2691 int slen;
2692 unsigned char *senc = NULL, *p;
2693 const unsigned char *const_p;
2694
2695 if (session == NULL) {
2696 PyErr_SetString(PyExc_ValueError, "Invalid session");
2697 goto error;
2698 }
2699
2700 /* get length */
2701 slen = i2d_SSL_SESSION(session, NULL);
2702 if (slen == 0 || slen > 0xFF00) {
2703 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2704 goto error;
2705 }
2706 if ((senc = PyMem_Malloc(slen)) == NULL) {
2707 PyErr_NoMemory();
2708 goto error;
2709 }
2710 p = senc;
2711 if (!i2d_SSL_SESSION(session, &p)) {
2712 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2713 goto error;
2714 }
2715 const_p = senc;
2716 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2717 if (session == NULL) {
2718 goto error;
2719 }
2720 PyMem_Free(senc);
2721 return newsession;
2722 error:
2723 if (senc != NULL) {
2724 PyMem_Free(senc);
2725 }
2726 return NULL;
2727}
2728#endif
2729
2730static PyObject *
2731PySSL_get_session(PySSLSocket *self, void *closure) {
2732 /* get_session can return sessions from a server-side connection,
2733 * it does not check for handshake done or client socket. */
2734 PySSLSession *pysess;
2735 SSL_SESSION *session;
2736
2737#ifdef OPENSSL_VERSION_1_1
2738 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2739 * https://github.com/openssl/openssl/issues/1550 */
2740 session = SSL_get0_session(self->ssl); /* borrowed reference */
2741 if (session == NULL) {
2742 Py_RETURN_NONE;
2743 }
2744 if ((session = _ssl_session_dup(session)) == NULL) {
2745 return NULL;
2746 }
2747#else
2748 session = SSL_get1_session(self->ssl);
2749 if (session == NULL) {
2750 Py_RETURN_NONE;
2751 }
2752#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002753 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002754 if (pysess == NULL) {
2755 SSL_SESSION_free(session);
2756 return NULL;
2757 }
2758
2759 assert(self->ctx);
2760 pysess->ctx = self->ctx;
2761 Py_INCREF(pysess->ctx);
2762 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002763 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002764 return (PyObject *)pysess;
2765}
2766
2767static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2768 void *closure)
2769 {
2770 PySSLSession *pysess;
2771#ifdef OPENSSL_VERSION_1_1
2772 SSL_SESSION *session;
2773#endif
2774 int result;
2775
2776 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002777 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002778 return -1;
2779 }
2780 pysess = (PySSLSession *)value;
2781
2782 if (self->ctx->ctx != pysess->ctx->ctx) {
2783 PyErr_SetString(PyExc_ValueError,
2784 "Session refers to a different SSLContext.");
2785 return -1;
2786 }
2787 if (self->socket_type != PY_SSL_CLIENT) {
2788 PyErr_SetString(PyExc_ValueError,
2789 "Cannot set session for server-side SSLSocket.");
2790 return -1;
2791 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002792 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002793 PyErr_SetString(PyExc_ValueError,
2794 "Cannot set session after handshake.");
2795 return -1;
2796 }
2797#ifdef OPENSSL_VERSION_1_1
2798 /* duplicate session */
2799 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2800 return -1;
2801 }
2802 result = SSL_set_session(self->ssl, session);
2803 /* free duplicate, SSL_set_session() bumps ref count */
2804 SSL_SESSION_free(session);
2805#else
2806 result = SSL_set_session(self->ssl, pysess->session);
2807#endif
2808 if (result == 0) {
2809 _setSSLError(NULL, 0, __FILE__, __LINE__);
2810 return -1;
2811 }
2812 return 0;
2813}
2814
2815PyDoc_STRVAR(PySSL_set_session_doc,
2816"_setter_session(session)\n\
2817\
2818Get / set SSLSession.");
2819
2820static PyObject *
2821PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2822 if (SSL_session_reused(self->ssl)) {
2823 Py_RETURN_TRUE;
2824 } else {
2825 Py_RETURN_FALSE;
2826 }
2827}
2828
2829PyDoc_STRVAR(PySSL_get_session_reused_doc,
2830"Was the client session reused during handshake?");
2831
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002832static PyGetSetDef ssl_getsetlist[] = {
2833 {"context", (getter) PySSL_get_context,
2834 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002835 {"server_side", (getter) PySSL_get_server_side, NULL,
2836 PySSL_get_server_side_doc},
2837 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2838 PySSL_get_server_hostname_doc},
2839 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2840 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002841 {"session", (getter) PySSL_get_session,
2842 (setter) PySSL_set_session, PySSL_set_session_doc},
2843 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2844 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002845 {NULL}, /* sentinel */
2846};
2847
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002848static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002849 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2850 _SSL__SSLSOCKET_WRITE_METHODDEF
2851 _SSL__SSLSOCKET_READ_METHODDEF
2852 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002853 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2854 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002855 _SSL__SSLSOCKET_CIPHER_METHODDEF
2856 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2857 _SSL__SSLSOCKET_VERSION_METHODDEF
2858 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2859 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2860 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2861 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002862 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002863 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002864};
2865
Antoine Pitrou152efa22010-05-16 18:19:27 +00002866static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002867 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002868 "_ssl._SSLSocket", /*tp_name*/
2869 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002870 0, /*tp_itemsize*/
2871 /* methods */
2872 (destructor)PySSL_dealloc, /*tp_dealloc*/
2873 0, /*tp_print*/
2874 0, /*tp_getattr*/
2875 0, /*tp_setattr*/
2876 0, /*tp_reserved*/
2877 0, /*tp_repr*/
2878 0, /*tp_as_number*/
2879 0, /*tp_as_sequence*/
2880 0, /*tp_as_mapping*/
2881 0, /*tp_hash*/
2882 0, /*tp_call*/
2883 0, /*tp_str*/
2884 0, /*tp_getattro*/
2885 0, /*tp_setattro*/
2886 0, /*tp_as_buffer*/
2887 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2888 0, /*tp_doc*/
2889 0, /*tp_traverse*/
2890 0, /*tp_clear*/
2891 0, /*tp_richcompare*/
2892 0, /*tp_weaklistoffset*/
2893 0, /*tp_iter*/
2894 0, /*tp_iternext*/
2895 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002896 0, /*tp_members*/
2897 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002898};
2899
Antoine Pitrou152efa22010-05-16 18:19:27 +00002900
2901/*
2902 * _SSLContext objects
2903 */
2904
Christian Heimes5fe668c2016-09-12 00:01:11 +02002905static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002906_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002907{
2908 int mode;
2909 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2910
2911 switch(n) {
2912 case PY_SSL_CERT_NONE:
2913 mode = SSL_VERIFY_NONE;
2914 break;
2915 case PY_SSL_CERT_OPTIONAL:
2916 mode = SSL_VERIFY_PEER;
2917 break;
2918 case PY_SSL_CERT_REQUIRED:
2919 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2920 break;
2921 default:
2922 PyErr_SetString(PyExc_ValueError,
2923 "invalid value for verify_mode");
2924 return -1;
2925 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02002926#ifdef TLS1_3_VERSION
2927 if (self->post_handshake_auth)
2928 mode |= SSL_VERIFY_POST_HANDSHAKE;
2929#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002930 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002931 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2932 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002933 return 0;
2934}
2935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002936/*[clinic input]
2937@classmethod
2938_ssl._SSLContext.__new__
2939 protocol as proto_version: int
2940 /
2941[clinic start generated code]*/
2942
Antoine Pitrou152efa22010-05-16 18:19:27 +00002943static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002944_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2945/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002946{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002947 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002948 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002950 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002951 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002952#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002953 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002954#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002955
Antoine Pitrou152efa22010-05-16 18:19:27 +00002956 PySSL_BEGIN_ALLOW_THREADS
2957 if (proto_version == PY_SSL_VERSION_TLS1)
2958 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002959#if HAVE_TLSv1_2
2960 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2961 ctx = SSL_CTX_new(TLSv1_1_method());
2962 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2963 ctx = SSL_CTX_new(TLSv1_2_method());
2964#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002965#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002966 else if (proto_version == PY_SSL_VERSION_SSL3)
2967 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002968#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002969#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002970 else if (proto_version == PY_SSL_VERSION_SSL2)
2971 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002972#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002973 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002974 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002975 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2976 ctx = SSL_CTX_new(TLS_client_method());
2977 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2978 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002979 else
2980 proto_version = -1;
2981 PySSL_END_ALLOW_THREADS
2982
2983 if (proto_version == -1) {
2984 PyErr_SetString(PyExc_ValueError,
2985 "invalid protocol version");
2986 return NULL;
2987 }
2988 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002989 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002990 return NULL;
2991 }
2992
2993 assert(type != NULL && type->tp_alloc != NULL);
2994 self = (PySSLContext *) type->tp_alloc(type, 0);
2995 if (self == NULL) {
2996 SSL_CTX_free(ctx);
2997 return NULL;
2998 }
2999 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003000 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003001 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01003002#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003003 self->npn_protocols = NULL;
3004#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003005#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003006 self->alpn_protocols = NULL;
3007#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003008#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003009 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003010#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003011 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003012 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3013 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003014 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003015 Py_DECREF(self);
3016 return NULL;
3017 }
3018 } else {
3019 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003020 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003021 Py_DECREF(self);
3022 return NULL;
3023 }
3024 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003025 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003026 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3027 if (proto_version != PY_SSL_VERSION_SSL2)
3028 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003029 if (proto_version != PY_SSL_VERSION_SSL3)
3030 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003031 /* Minimal security flags for server and client side context.
3032 * Client sockets ignore server-side parameters. */
3033#ifdef SSL_OP_NO_COMPRESSION
3034 options |= SSL_OP_NO_COMPRESSION;
3035#endif
3036#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3037 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3038#endif
3039#ifdef SSL_OP_SINGLE_DH_USE
3040 options |= SSL_OP_SINGLE_DH_USE;
3041#endif
3042#ifdef SSL_OP_SINGLE_ECDH_USE
3043 options |= SSL_OP_SINGLE_ECDH_USE;
3044#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003045 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003046
Semen Zhydenko1295e112017-10-15 21:28:31 +02003047 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003048 * It's far from perfect but gives users a better head start. */
3049 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003050#if PY_SSL_DEFAULT_CIPHERS == 2
3051 /* stick to OpenSSL's default settings */
3052 result = 1;
3053#else
3054 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3055#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003056 } else {
3057 /* SSLv2 needs MD5 */
3058 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3059 }
3060 if (result == 0) {
3061 Py_DECREF(self);
3062 ERR_clear_error();
3063 PyErr_SetString(PySSLErrorObject,
3064 "No cipher can be selected.");
3065 return NULL;
3066 }
3067
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003068#if defined(SSL_MODE_RELEASE_BUFFERS)
3069 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3070 usage for no cost at all. However, don't do this for OpenSSL versions
3071 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3072 2014-0198. I can't find exactly which beta fixed this CVE, so be
3073 conservative and assume it wasn't fixed until release. We do this check
3074 at runtime to avoid problems from the dynamic linker.
3075 See #25672 for more on this. */
3076 libver = SSLeay();
3077 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3078 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3079 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3080 }
3081#endif
3082
3083
Donald Stufft8ae264c2017-03-02 11:45:29 -05003084#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003085 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3086 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003087 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3088 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003089#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003090 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3091#else
3092 {
3093 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3094 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3095 EC_KEY_free(key);
3096 }
3097#endif
3098#endif
3099
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003100#define SID_CTX "Python"
3101 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3102 sizeof(SID_CTX));
3103#undef SID_CTX
3104
Christian Heimes61d478c2018-01-27 15:51:38 +01003105 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003106#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003107 /* Improve trust chain building when cross-signed intermediate
3108 certificates are present. See https://bugs.python.org/issue23476. */
3109 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003110#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003111 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003112
Christian Heimes9fb051f2018-09-23 08:32:31 +02003113#ifdef TLS1_3_VERSION
3114 self->post_handshake_auth = 0;
3115 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3116#endif
3117
Antoine Pitrou152efa22010-05-16 18:19:27 +00003118 return (PyObject *)self;
3119}
3120
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003121static int
3122context_traverse(PySSLContext *self, visitproc visit, void *arg)
3123{
3124#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003125 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003126#endif
3127 return 0;
3128}
3129
3130static int
3131context_clear(PySSLContext *self)
3132{
3133#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003134 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003135#endif
3136 return 0;
3137}
3138
Antoine Pitrou152efa22010-05-16 18:19:27 +00003139static void
3140context_dealloc(PySSLContext *self)
3141{
INADA Naokia6296d32017-08-24 14:55:17 +09003142 /* bpo-31095: UnTrack is needed before calling any callbacks */
3143 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003144 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003145 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003146#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003147 PyMem_FREE(self->npn_protocols);
3148#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003149#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003150 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003151#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003152 Py_TYPE(self)->tp_free(self);
3153}
3154
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003155/*[clinic input]
3156_ssl._SSLContext.set_ciphers
3157 cipherlist: str
3158 /
3159[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003160
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003161static PyObject *
3162_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3163/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3164{
3165 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003166 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003167 /* Clearing the error queue is necessary on some OpenSSL versions,
3168 otherwise the error will be reported again when another SSL call
3169 is done. */
3170 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003171 PyErr_SetString(PySSLErrorObject,
3172 "No cipher can be selected.");
3173 return NULL;
3174 }
3175 Py_RETURN_NONE;
3176}
3177
Christian Heimes25bfcd52016-09-06 00:04:45 +02003178#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3179/*[clinic input]
3180_ssl._SSLContext.get_ciphers
3181[clinic start generated code]*/
3182
3183static PyObject *
3184_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3185/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3186{
3187 SSL *ssl = NULL;
3188 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003189 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003190 int i=0;
3191 PyObject *result = NULL, *dct;
3192
3193 ssl = SSL_new(self->ctx);
3194 if (ssl == NULL) {
3195 _setSSLError(NULL, 0, __FILE__, __LINE__);
3196 goto exit;
3197 }
3198 sk = SSL_get_ciphers(ssl);
3199
3200 result = PyList_New(sk_SSL_CIPHER_num(sk));
3201 if (result == NULL) {
3202 goto exit;
3203 }
3204
3205 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3206 cipher = sk_SSL_CIPHER_value(sk, i);
3207 dct = cipher_to_dict(cipher);
3208 if (dct == NULL) {
3209 Py_CLEAR(result);
3210 goto exit;
3211 }
3212 PyList_SET_ITEM(result, i, dct);
3213 }
3214
3215 exit:
3216 if (ssl != NULL)
3217 SSL_free(ssl);
3218 return result;
3219
3220}
3221#endif
3222
3223
Christian Heimes29eab552018-02-25 12:31:33 +01003224#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003225static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003226do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3227 const unsigned char *server_protocols, unsigned int server_protocols_len,
3228 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003229{
Benjamin Peterson88615022015-01-23 17:30:26 -05003230 int ret;
3231 if (client_protocols == NULL) {
3232 client_protocols = (unsigned char *)"";
3233 client_protocols_len = 0;
3234 }
3235 if (server_protocols == NULL) {
3236 server_protocols = (unsigned char *)"";
3237 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003238 }
3239
Benjamin Peterson88615022015-01-23 17:30:26 -05003240 ret = SSL_select_next_proto(out, outlen,
3241 server_protocols, server_protocols_len,
3242 client_protocols, client_protocols_len);
3243 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3244 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003245
3246 return SSL_TLSEXT_ERR_OK;
3247}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003248#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003249
Christian Heimes29eab552018-02-25 12:31:33 +01003250#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003251/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3252static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003253_advertiseNPN_cb(SSL *s,
3254 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003255 void *args)
3256{
3257 PySSLContext *ssl_ctx = (PySSLContext *) args;
3258
3259 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003260 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003261 *len = 0;
3262 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003263 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003264 *len = ssl_ctx->npn_protocols_len;
3265 }
3266
3267 return SSL_TLSEXT_ERR_OK;
3268}
3269/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3270static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003271_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003272 unsigned char **out, unsigned char *outlen,
3273 const unsigned char *server, unsigned int server_len,
3274 void *args)
3275{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003276 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003277 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003278 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003279}
3280#endif
3281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003282/*[clinic input]
3283_ssl._SSLContext._set_npn_protocols
3284 protos: Py_buffer
3285 /
3286[clinic start generated code]*/
3287
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003288static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003289_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3290 Py_buffer *protos)
3291/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003292{
Christian Heimes29eab552018-02-25 12:31:33 +01003293#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003294 PyMem_Free(self->npn_protocols);
3295 self->npn_protocols = PyMem_Malloc(protos->len);
3296 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003297 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003298 memcpy(self->npn_protocols, protos->buf, protos->len);
3299 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003300
3301 /* set both server and client callbacks, because the context can
3302 * be used to create both types of sockets */
3303 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3304 _advertiseNPN_cb,
3305 self);
3306 SSL_CTX_set_next_proto_select_cb(self->ctx,
3307 _selectNPN_cb,
3308 self);
3309
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003310 Py_RETURN_NONE;
3311#else
3312 PyErr_SetString(PyExc_NotImplementedError,
3313 "The NPN extension requires OpenSSL 1.0.1 or later.");
3314 return NULL;
3315#endif
3316}
3317
Christian Heimes29eab552018-02-25 12:31:33 +01003318#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003319static int
3320_selectALPN_cb(SSL *s,
3321 const unsigned char **out, unsigned char *outlen,
3322 const unsigned char *client_protocols, unsigned int client_protocols_len,
3323 void *args)
3324{
3325 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003326 return do_protocol_selection(1, (unsigned char **)out, outlen,
3327 ctx->alpn_protocols, ctx->alpn_protocols_len,
3328 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003329}
3330#endif
3331
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003332/*[clinic input]
3333_ssl._SSLContext._set_alpn_protocols
3334 protos: Py_buffer
3335 /
3336[clinic start generated code]*/
3337
Benjamin Petersoncca27322015-01-23 16:35:37 -05003338static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003339_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3340 Py_buffer *protos)
3341/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003342{
Christian Heimes29eab552018-02-25 12:31:33 +01003343#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003344 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003345 PyErr_Format(PyExc_OverflowError,
3346 "protocols longer than %d bytes", UINT_MAX);
3347 return NULL;
3348 }
3349
Benjamin Petersoncca27322015-01-23 16:35:37 -05003350 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003351 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003352 if (!self->alpn_protocols)
3353 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003354 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003355 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003356
3357 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3358 return PyErr_NoMemory();
3359 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3360
Benjamin Petersoncca27322015-01-23 16:35:37 -05003361 Py_RETURN_NONE;
3362#else
3363 PyErr_SetString(PyExc_NotImplementedError,
3364 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3365 return NULL;
3366#endif
3367}
3368
Antoine Pitrou152efa22010-05-16 18:19:27 +00003369static PyObject *
3370get_verify_mode(PySSLContext *self, void *c)
3371{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003372 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3373 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3374 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3375 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003376 case SSL_VERIFY_NONE:
3377 return PyLong_FromLong(PY_SSL_CERT_NONE);
3378 case SSL_VERIFY_PEER:
3379 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3380 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3381 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3382 }
3383 PyErr_SetString(PySSLErrorObject,
3384 "invalid return value from SSL_CTX_get_verify_mode");
3385 return NULL;
3386}
3387
3388static int
3389set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3390{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003391 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003392 if (!PyArg_Parse(arg, "i", &n))
3393 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003394 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003395 PyErr_SetString(PyExc_ValueError,
3396 "Cannot set verify_mode to CERT_NONE when "
3397 "check_hostname is enabled.");
3398 return -1;
3399 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003400 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003401}
3402
3403static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003404get_verify_flags(PySSLContext *self, void *c)
3405{
Christian Heimes598894f2016-09-05 23:19:05 +02003406 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003407 unsigned long flags;
3408
Christian Heimes61d478c2018-01-27 15:51:38 +01003409 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003410 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003411 return PyLong_FromUnsignedLong(flags);
3412}
3413
3414static int
3415set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3416{
Christian Heimes598894f2016-09-05 23:19:05 +02003417 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003418 unsigned long new_flags, flags, set, clear;
3419
3420 if (!PyArg_Parse(arg, "k", &new_flags))
3421 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003422 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003423 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003424 clear = flags & ~new_flags;
3425 set = ~flags & new_flags;
3426 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003427 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003428 _setSSLError(NULL, 0, __FILE__, __LINE__);
3429 return -1;
3430 }
3431 }
3432 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003433 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003434 _setSSLError(NULL, 0, __FILE__, __LINE__);
3435 return -1;
3436 }
3437 }
3438 return 0;
3439}
3440
Christian Heimes698dde12018-02-27 11:54:43 +01003441/* Getter and setter for protocol version */
3442#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3443
3444
3445static int
3446set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3447{
3448 long v;
3449 int result;
3450
3451 if (!PyArg_Parse(arg, "l", &v))
3452 return -1;
3453 if (v > INT_MAX) {
3454 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3455 return -1;
3456 }
3457
3458 switch(self->protocol) {
3459 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3460 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3461 case PY_SSL_VERSION_TLS:
3462 break;
3463 default:
3464 PyErr_SetString(
3465 PyExc_ValueError,
3466 "The context's protocol doesn't support modification of "
3467 "highest and lowest version."
3468 );
3469 return -1;
3470 }
3471
3472 if (what == 0) {
3473 switch(v) {
3474 case PY_PROTO_MINIMUM_SUPPORTED:
3475 v = 0;
3476 break;
3477 case PY_PROTO_MAXIMUM_SUPPORTED:
3478 /* Emulate max for set_min_proto_version */
3479 v = PY_PROTO_MAXIMUM_AVAILABLE;
3480 break;
3481 default:
3482 break;
3483 }
3484 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3485 }
3486 else {
3487 switch(v) {
3488 case PY_PROTO_MAXIMUM_SUPPORTED:
3489 v = 0;
3490 break;
3491 case PY_PROTO_MINIMUM_SUPPORTED:
3492 /* Emulate max for set_min_proto_version */
3493 v = PY_PROTO_MINIMUM_AVAILABLE;
3494 break;
3495 default:
3496 break;
3497 }
3498 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3499 }
3500 if (result == 0) {
3501 PyErr_Format(PyExc_ValueError,
3502 "Unsupported protocol version 0x%x", v);
3503 return -1;
3504 }
3505 return 0;
3506}
3507
3508static PyObject *
3509get_minimum_version(PySSLContext *self, void *c)
3510{
3511 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3512 if (v == 0) {
3513 v = PY_PROTO_MINIMUM_SUPPORTED;
3514 }
3515 return PyLong_FromLong(v);
3516}
3517
3518static int
3519set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3520{
3521 return set_min_max_proto_version(self, arg, 0);
3522}
3523
3524static PyObject *
3525get_maximum_version(PySSLContext *self, void *c)
3526{
3527 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3528 if (v == 0) {
3529 v = PY_PROTO_MAXIMUM_SUPPORTED;
3530 }
3531 return PyLong_FromLong(v);
3532}
3533
3534static int
3535set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3536{
3537 return set_min_max_proto_version(self, arg, 1);
3538}
3539#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3540
Christian Heimes22587792013-11-21 23:56:13 +01003541static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003542get_options(PySSLContext *self, void *c)
3543{
3544 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3545}
3546
3547static int
3548set_options(PySSLContext *self, PyObject *arg, void *c)
3549{
3550 long new_opts, opts, set, clear;
3551 if (!PyArg_Parse(arg, "l", &new_opts))
3552 return -1;
3553 opts = SSL_CTX_get_options(self->ctx);
3554 clear = opts & ~new_opts;
3555 set = ~opts & new_opts;
3556 if (clear) {
3557#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3558 SSL_CTX_clear_options(self->ctx, clear);
3559#else
3560 PyErr_SetString(PyExc_ValueError,
3561 "can't clear options before OpenSSL 0.9.8m");
3562 return -1;
3563#endif
3564 }
3565 if (set)
3566 SSL_CTX_set_options(self->ctx, set);
3567 return 0;
3568}
3569
Christian Heimes1aa9a752013-12-02 02:41:19 +01003570static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003571get_host_flags(PySSLContext *self, void *c)
3572{
3573 return PyLong_FromUnsignedLong(self->hostflags);
3574}
3575
3576static int
3577set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3578{
3579 X509_VERIFY_PARAM *param;
3580 unsigned int new_flags = 0;
3581
3582 if (!PyArg_Parse(arg, "I", &new_flags))
3583 return -1;
3584
3585 param = SSL_CTX_get0_param(self->ctx);
3586 self->hostflags = new_flags;
3587 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3588 return 0;
3589}
3590
3591static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003592get_check_hostname(PySSLContext *self, void *c)
3593{
3594 return PyBool_FromLong(self->check_hostname);
3595}
3596
3597static int
3598set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3599{
3600 int check_hostname;
3601 if (!PyArg_Parse(arg, "p", &check_hostname))
3602 return -1;
3603 if (check_hostname &&
3604 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003605 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003606 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003607 return -1;
3608 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003609 }
3610 self->check_hostname = check_hostname;
3611 return 0;
3612}
3613
Christian Heimes11a14932018-02-24 02:35:08 +01003614static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003615get_post_handshake_auth(PySSLContext *self, void *c) {
3616#if TLS1_3_VERSION
3617 return PyBool_FromLong(self->post_handshake_auth);
3618#else
3619 Py_RETURN_NONE;
3620#endif
3621}
3622
3623#if TLS1_3_VERSION
3624static int
3625set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3626 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3627 int mode = SSL_CTX_get_verify_mode(self->ctx);
Zackery Spytz842acaa2018-12-17 07:52:45 -07003628 if (arg == NULL) {
3629 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3630 return -1;
3631 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003632 int pha = PyObject_IsTrue(arg);
3633
3634 if (pha == -1) {
3635 return -1;
3636 }
3637 self->post_handshake_auth = pha;
3638
3639 /* client-side socket setting, ignored by server-side */
3640 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3641
3642 /* server-side socket setting, ignored by client-side */
3643 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3644 if (pha) {
3645 mode |= SSL_VERIFY_POST_HANDSHAKE;
3646 } else {
3647 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3648 }
3649 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3650
3651 return 0;
3652}
3653#endif
3654
3655static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003656get_protocol(PySSLContext *self, void *c) {
3657 return PyLong_FromLong(self->protocol);
3658}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003659
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003660typedef struct {
3661 PyThreadState *thread_state;
3662 PyObject *callable;
3663 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003664 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003665 int error;
3666} _PySSLPasswordInfo;
3667
3668static int
3669_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3670 const char *bad_type_error)
3671{
3672 /* Set the password and size fields of a _PySSLPasswordInfo struct
3673 from a unicode, bytes, or byte array object.
3674 The password field will be dynamically allocated and must be freed
3675 by the caller */
3676 PyObject *password_bytes = NULL;
3677 const char *data = NULL;
3678 Py_ssize_t size;
3679
3680 if (PyUnicode_Check(password)) {
3681 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3682 if (!password_bytes) {
3683 goto error;
3684 }
3685 data = PyBytes_AS_STRING(password_bytes);
3686 size = PyBytes_GET_SIZE(password_bytes);
3687 } else if (PyBytes_Check(password)) {
3688 data = PyBytes_AS_STRING(password);
3689 size = PyBytes_GET_SIZE(password);
3690 } else if (PyByteArray_Check(password)) {
3691 data = PyByteArray_AS_STRING(password);
3692 size = PyByteArray_GET_SIZE(password);
3693 } else {
3694 PyErr_SetString(PyExc_TypeError, bad_type_error);
3695 goto error;
3696 }
3697
Victor Stinner9ee02032013-06-23 15:08:23 +02003698 if (size > (Py_ssize_t)INT_MAX) {
3699 PyErr_Format(PyExc_ValueError,
3700 "password cannot be longer than %d bytes", INT_MAX);
3701 goto error;
3702 }
3703
Victor Stinner11ebff22013-07-07 17:07:52 +02003704 PyMem_Free(pw_info->password);
3705 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003706 if (!pw_info->password) {
3707 PyErr_SetString(PyExc_MemoryError,
3708 "unable to allocate password buffer");
3709 goto error;
3710 }
3711 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003712 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003713
3714 Py_XDECREF(password_bytes);
3715 return 1;
3716
3717error:
3718 Py_XDECREF(password_bytes);
3719 return 0;
3720}
3721
3722static int
3723_password_callback(char *buf, int size, int rwflag, void *userdata)
3724{
3725 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3726 PyObject *fn_ret = NULL;
3727
3728 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3729
3730 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003731 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003732 if (!fn_ret) {
3733 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3734 core python API, so we could use it to add a frame here */
3735 goto error;
3736 }
3737
3738 if (!_pwinfo_set(pw_info, fn_ret,
3739 "password callback must return a string")) {
3740 goto error;
3741 }
3742 Py_CLEAR(fn_ret);
3743 }
3744
3745 if (pw_info->size > size) {
3746 PyErr_Format(PyExc_ValueError,
3747 "password cannot be longer than %d bytes", size);
3748 goto error;
3749 }
3750
3751 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3752 memcpy(buf, pw_info->password, pw_info->size);
3753 return pw_info->size;
3754
3755error:
3756 Py_XDECREF(fn_ret);
3757 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3758 pw_info->error = 1;
3759 return -1;
3760}
3761
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003762/*[clinic input]
3763_ssl._SSLContext.load_cert_chain
3764 certfile: object
3765 keyfile: object = NULL
3766 password: object = NULL
3767
3768[clinic start generated code]*/
3769
Antoine Pitroub5218772010-05-21 09:56:06 +00003770static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003771_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3772 PyObject *keyfile, PyObject *password)
3773/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003774{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003775 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003776 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3777 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003778 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003779 int r;
3780
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003781 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003782 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003783 if (keyfile == Py_None)
3784 keyfile = NULL;
3785 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3786 PyErr_SetString(PyExc_TypeError,
3787 "certfile should be a valid filesystem path");
3788 return NULL;
3789 }
3790 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3791 PyErr_SetString(PyExc_TypeError,
3792 "keyfile should be a valid filesystem path");
3793 goto error;
3794 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003795 if (password && password != Py_None) {
3796 if (PyCallable_Check(password)) {
3797 pw_info.callable = password;
3798 } else if (!_pwinfo_set(&pw_info, password,
3799 "password should be a string or callable")) {
3800 goto error;
3801 }
3802 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3803 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3804 }
3805 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003806 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3807 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003808 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003809 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003810 if (pw_info.error) {
3811 ERR_clear_error();
3812 /* the password callback has already set the error information */
3813 }
3814 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003815 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003816 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003817 }
3818 else {
3819 _setSSLError(NULL, 0, __FILE__, __LINE__);
3820 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003821 goto error;
3822 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003823 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003824 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003825 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3826 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003827 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3828 Py_CLEAR(keyfile_bytes);
3829 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003830 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003831 if (pw_info.error) {
3832 ERR_clear_error();
3833 /* the password callback has already set the error information */
3834 }
3835 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003836 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003837 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003838 }
3839 else {
3840 _setSSLError(NULL, 0, __FILE__, __LINE__);
3841 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003842 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003843 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003844 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003845 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003846 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003847 if (r != 1) {
3848 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003849 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003850 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003851 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3852 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003853 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003854 Py_RETURN_NONE;
3855
3856error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003857 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3858 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003859 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003860 Py_XDECREF(keyfile_bytes);
3861 Py_XDECREF(certfile_bytes);
3862 return NULL;
3863}
3864
Christian Heimesefff7062013-11-21 03:35:02 +01003865/* internal helper function, returns -1 on error
3866 */
3867static int
3868_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3869 int filetype)
3870{
3871 BIO *biobuf = NULL;
3872 X509_STORE *store;
3873 int retval = 0, err, loaded = 0;
3874
3875 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3876
3877 if (len <= 0) {
3878 PyErr_SetString(PyExc_ValueError,
3879 "Empty certificate data");
3880 return -1;
3881 } else if (len > INT_MAX) {
3882 PyErr_SetString(PyExc_OverflowError,
3883 "Certificate data is too long.");
3884 return -1;
3885 }
3886
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003887 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003888 if (biobuf == NULL) {
3889 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3890 return -1;
3891 }
3892
3893 store = SSL_CTX_get_cert_store(self->ctx);
3894 assert(store != NULL);
3895
3896 while (1) {
3897 X509 *cert = NULL;
3898 int r;
3899
3900 if (filetype == SSL_FILETYPE_ASN1) {
3901 cert = d2i_X509_bio(biobuf, NULL);
3902 } else {
3903 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003904 SSL_CTX_get_default_passwd_cb(self->ctx),
3905 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3906 );
Christian Heimesefff7062013-11-21 03:35:02 +01003907 }
3908 if (cert == NULL) {
3909 break;
3910 }
3911 r = X509_STORE_add_cert(store, cert);
3912 X509_free(cert);
3913 if (!r) {
3914 err = ERR_peek_last_error();
3915 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3916 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3917 /* cert already in hash table, not an error */
3918 ERR_clear_error();
3919 } else {
3920 break;
3921 }
3922 }
3923 loaded++;
3924 }
3925
3926 err = ERR_peek_last_error();
3927 if ((filetype == SSL_FILETYPE_ASN1) &&
3928 (loaded > 0) &&
3929 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3930 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3931 /* EOF ASN1 file, not an error */
3932 ERR_clear_error();
3933 retval = 0;
3934 } else if ((filetype == SSL_FILETYPE_PEM) &&
3935 (loaded > 0) &&
3936 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3937 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3938 /* EOF PEM file, not an error */
3939 ERR_clear_error();
3940 retval = 0;
3941 } else {
3942 _setSSLError(NULL, 0, __FILE__, __LINE__);
3943 retval = -1;
3944 }
3945
3946 BIO_free(biobuf);
3947 return retval;
3948}
3949
3950
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003951/*[clinic input]
3952_ssl._SSLContext.load_verify_locations
3953 cafile: object = NULL
3954 capath: object = NULL
3955 cadata: object = NULL
3956
3957[clinic start generated code]*/
3958
Antoine Pitrou152efa22010-05-16 18:19:27 +00003959static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003960_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3961 PyObject *cafile,
3962 PyObject *capath,
3963 PyObject *cadata)
3964/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003965{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3967 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003968 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003969
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003970 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003971 if (cafile == Py_None)
3972 cafile = NULL;
3973 if (capath == Py_None)
3974 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003975 if (cadata == Py_None)
3976 cadata = NULL;
3977
3978 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003979 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003980 "cafile, capath and cadata cannot be all omitted");
3981 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003982 }
3983 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3984 PyErr_SetString(PyExc_TypeError,
3985 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003986 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003987 }
3988 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003989 PyErr_SetString(PyExc_TypeError,
3990 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003991 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003992 }
Christian Heimesefff7062013-11-21 03:35:02 +01003993
3994 /* validata cadata type and load cadata */
3995 if (cadata) {
3996 Py_buffer buf;
3997 PyObject *cadata_ascii = NULL;
3998
3999 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
4000 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4001 PyBuffer_Release(&buf);
4002 PyErr_SetString(PyExc_TypeError,
4003 "cadata should be a contiguous buffer with "
4004 "a single dimension");
4005 goto error;
4006 }
4007 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4008 PyBuffer_Release(&buf);
4009 if (r == -1) {
4010 goto error;
4011 }
4012 } else {
4013 PyErr_Clear();
4014 cadata_ascii = PyUnicode_AsASCIIString(cadata);
4015 if (cadata_ascii == NULL) {
4016 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02004017 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01004018 "bytes-like object");
4019 goto error;
4020 }
4021 r = _add_ca_certs(self,
4022 PyBytes_AS_STRING(cadata_ascii),
4023 PyBytes_GET_SIZE(cadata_ascii),
4024 SSL_FILETYPE_PEM);
4025 Py_DECREF(cadata_ascii);
4026 if (r == -1) {
4027 goto error;
4028 }
4029 }
4030 }
4031
4032 /* load cafile or capath */
4033 if (cafile || capath) {
4034 if (cafile)
4035 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4036 if (capath)
4037 capath_buf = PyBytes_AS_STRING(capath_bytes);
4038 PySSL_BEGIN_ALLOW_THREADS
4039 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4040 PySSL_END_ALLOW_THREADS
4041 if (r != 1) {
4042 ok = 0;
4043 if (errno != 0) {
4044 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004045 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004046 }
4047 else {
4048 _setSSLError(NULL, 0, __FILE__, __LINE__);
4049 }
4050 goto error;
4051 }
4052 }
4053 goto end;
4054
4055 error:
4056 ok = 0;
4057 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004058 Py_XDECREF(cafile_bytes);
4059 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004060 if (ok) {
4061 Py_RETURN_NONE;
4062 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004063 return NULL;
4064 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065}
4066
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004067/*[clinic input]
4068_ssl._SSLContext.load_dh_params
4069 path as filepath: object
4070 /
4071
4072[clinic start generated code]*/
4073
Antoine Pitrou152efa22010-05-16 18:19:27 +00004074static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004075_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4076/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004077{
4078 FILE *f;
4079 DH *dh;
4080
Victor Stinnerdaf45552013-08-28 00:53:59 +02004081 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004082 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004083 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004084
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004085 errno = 0;
4086 PySSL_BEGIN_ALLOW_THREADS
4087 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004088 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004089 PySSL_END_ALLOW_THREADS
4090 if (dh == NULL) {
4091 if (errno != 0) {
4092 ERR_clear_error();
4093 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4094 }
4095 else {
4096 _setSSLError(NULL, 0, __FILE__, __LINE__);
4097 }
4098 return NULL;
4099 }
4100 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4101 _setSSLError(NULL, 0, __FILE__, __LINE__);
4102 DH_free(dh);
4103 Py_RETURN_NONE;
4104}
4105
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004106/*[clinic input]
4107_ssl._SSLContext._wrap_socket
4108 sock: object(subclass_of="PySocketModule.Sock_Type")
4109 server_side: int
4110 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004111 *
4112 owner: object = None
4113 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004114
4115[clinic start generated code]*/
4116
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004117static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004119 int server_side, PyObject *hostname_obj,
4120 PyObject *owner, PyObject *session)
4121/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004122{
Antoine Pitroud5323212010-10-22 18:19:07 +00004123 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004124 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004125
Antoine Pitroud5323212010-10-22 18:19:07 +00004126 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004127 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004128 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004129 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004130 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004131 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004132
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004133 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4134 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004135 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004136 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004137 if (hostname != NULL)
4138 PyMem_Free(hostname);
4139 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004140}
4141
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004142/*[clinic input]
4143_ssl._SSLContext._wrap_bio
4144 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4145 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4146 server_side: int
4147 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004148 *
4149 owner: object = None
4150 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004151
4152[clinic start generated code]*/
4153
Antoine Pitroub0182c82010-10-12 20:09:02 +00004154static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004155_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4156 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004157 PyObject *hostname_obj, PyObject *owner,
4158 PyObject *session)
4159/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004160{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004161 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004162 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004163
4164 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004165 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004166 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004167 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004168 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004169 }
4170
4171 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004172 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004173 incoming, outgoing);
4174
4175 PyMem_Free(hostname);
4176 return res;
4177}
4178
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004179/*[clinic input]
4180_ssl._SSLContext.session_stats
4181[clinic start generated code]*/
4182
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004184_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4185/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004186{
4187 int r;
4188 PyObject *value, *stats = PyDict_New();
4189 if (!stats)
4190 return NULL;
4191
4192#define ADD_STATS(SSL_NAME, KEY_NAME) \
4193 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4194 if (value == NULL) \
4195 goto error; \
4196 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4197 Py_DECREF(value); \
4198 if (r < 0) \
4199 goto error;
4200
4201 ADD_STATS(number, "number");
4202 ADD_STATS(connect, "connect");
4203 ADD_STATS(connect_good, "connect_good");
4204 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4205 ADD_STATS(accept, "accept");
4206 ADD_STATS(accept_good, "accept_good");
4207 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4208 ADD_STATS(accept, "accept");
4209 ADD_STATS(hits, "hits");
4210 ADD_STATS(misses, "misses");
4211 ADD_STATS(timeouts, "timeouts");
4212 ADD_STATS(cache_full, "cache_full");
4213
4214#undef ADD_STATS
4215
4216 return stats;
4217
4218error:
4219 Py_DECREF(stats);
4220 return NULL;
4221}
4222
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004223/*[clinic input]
4224_ssl._SSLContext.set_default_verify_paths
4225[clinic start generated code]*/
4226
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004227static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004228_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4229/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004230{
4231 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4232 _setSSLError(NULL, 0, __FILE__, __LINE__);
4233 return NULL;
4234 }
4235 Py_RETURN_NONE;
4236}
4237
Antoine Pitrou501da612011-12-21 09:27:41 +01004238#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004239/*[clinic input]
4240_ssl._SSLContext.set_ecdh_curve
4241 name: object
4242 /
4243
4244[clinic start generated code]*/
4245
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004246static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004247_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4248/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004249{
4250 PyObject *name_bytes;
4251 int nid;
4252 EC_KEY *key;
4253
4254 if (!PyUnicode_FSConverter(name, &name_bytes))
4255 return NULL;
4256 assert(PyBytes_Check(name_bytes));
4257 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4258 Py_DECREF(name_bytes);
4259 if (nid == 0) {
4260 PyErr_Format(PyExc_ValueError,
4261 "unknown elliptic curve name %R", name);
4262 return NULL;
4263 }
4264 key = EC_KEY_new_by_curve_name(nid);
4265 if (key == NULL) {
4266 _setSSLError(NULL, 0, __FILE__, __LINE__);
4267 return NULL;
4268 }
4269 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4270 EC_KEY_free(key);
4271 Py_RETURN_NONE;
4272}
Antoine Pitrou501da612011-12-21 09:27:41 +01004273#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004274
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004275#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004276static int
4277_servername_callback(SSL *s, int *al, void *args)
4278{
4279 int ret;
4280 PySSLContext *ssl_ctx = (PySSLContext *) args;
4281 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004282 PyObject *result;
4283 /* The high-level ssl.SSLSocket object */
4284 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004285 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004286 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004287
Christian Heimes11a14932018-02-24 02:35:08 +01004288 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004289 /* remove race condition in this the call back while if removing the
4290 * callback is in progress */
4291 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004292 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004293 }
4294
4295 ssl = SSL_get_app_data(s);
4296 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004297
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004298 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004299 * SSL connection and that has a .context attribute that can be changed to
4300 * identify the requested hostname. Since the official API is the Python
4301 * level API we want to pass the callback a Python level object rather than
4302 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4303 * SSLObject) that will be passed. Otherwise if there's a socket then that
4304 * will be passed. If both do not exist only then the C-level object is
4305 * passed. */
4306 if (ssl->owner)
4307 ssl_socket = PyWeakref_GetObject(ssl->owner);
4308 else if (ssl->Socket)
4309 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4310 else
4311 ssl_socket = (PyObject *) ssl;
4312
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004313 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004314 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004315 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004316
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004317 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004318 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004319 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004320 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004321 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004322 PyObject *servername_bytes;
4323 PyObject *servername_str;
4324
4325 servername_bytes = PyBytes_FromString(servername);
4326 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004327 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4328 goto error;
4329 }
Christian Heimes11a14932018-02-24 02:35:08 +01004330 /* server_hostname was encoded to an A-label by our caller; put it
4331 * back into a str object, but still as an A-label (bpo-28414)
4332 */
4333 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4334 Py_DECREF(servername_bytes);
4335 if (servername_str == NULL) {
4336 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004337 goto error;
4338 }
Christian Heimes11a14932018-02-24 02:35:08 +01004339 result = PyObject_CallFunctionObjArgs(
4340 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4341 ssl_ctx, NULL);
4342 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004343 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004344 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004345
4346 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004347 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004348 *al = SSL_AD_HANDSHAKE_FAILURE;
4349 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4350 }
4351 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004352 /* Result may be None, a SSLContext or an integer
4353 * None and SSLContext are OK, integer or other values are an error.
4354 */
4355 if (result == Py_None) {
4356 ret = SSL_TLSEXT_ERR_OK;
4357 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004358 *al = (int) PyLong_AsLong(result);
4359 if (PyErr_Occurred()) {
4360 PyErr_WriteUnraisable(result);
4361 *al = SSL_AD_INTERNAL_ERROR;
4362 }
4363 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4364 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004365 Py_DECREF(result);
4366 }
4367
4368 PyGILState_Release(gstate);
4369 return ret;
4370
4371error:
4372 Py_DECREF(ssl_socket);
4373 *al = SSL_AD_INTERNAL_ERROR;
4374 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4375 PyGILState_Release(gstate);
4376 return ret;
4377}
Antoine Pitroua5963382013-03-30 16:39:00 +01004378#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004379
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004380static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004381get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004382{
Christian Heimes11a14932018-02-24 02:35:08 +01004383 PyObject *cb = self->set_sni_cb;
4384 if (cb == NULL) {
4385 Py_RETURN_NONE;
4386 }
4387 Py_INCREF(cb);
4388 return cb;
4389}
4390
4391static int
4392set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4393{
4394 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4395 PyErr_SetString(PyExc_ValueError,
4396 "sni_callback cannot be set on TLS_CLIENT context");
4397 return -1;
4398 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004399#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004400 Py_CLEAR(self->set_sni_cb);
4401 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004402 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4403 }
4404 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004405 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004406 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4407 PyErr_SetString(PyExc_TypeError,
4408 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004409 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004410 }
Christian Heimes11a14932018-02-24 02:35:08 +01004411 Py_INCREF(arg);
4412 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004413 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4414 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4415 }
Christian Heimes11a14932018-02-24 02:35:08 +01004416 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004417#else
4418 PyErr_SetString(PyExc_NotImplementedError,
4419 "The TLS extension servername callback, "
4420 "SSL_CTX_set_tlsext_servername_callback, "
4421 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004422 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004423#endif
4424}
4425
Christian Heimes11a14932018-02-24 02:35:08 +01004426PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4427"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4428\n\
4429If the argument is None then the callback is disabled. The method is called\n\
4430with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4431See RFC 6066 for details of the SNI extension.");
4432
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004433/*[clinic input]
4434_ssl._SSLContext.cert_store_stats
4435
4436Returns quantities of loaded X.509 certificates.
4437
4438X.509 certificates with a CA extension and certificate revocation lists
4439inside the context's cert store.
4440
4441NOTE: Certificates in a capath directory aren't loaded unless they have
4442been used at least once.
4443[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004444
4445static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004446_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4447/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004448{
4449 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004450 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004451 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004452 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004453
4454 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004455 objs = X509_STORE_get0_objects(store);
4456 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4457 obj = sk_X509_OBJECT_value(objs, i);
4458 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004459 case X509_LU_X509:
4460 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004461 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004462 ca++;
4463 }
4464 break;
4465 case X509_LU_CRL:
4466 crl++;
4467 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004468 default:
4469 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4470 * As far as I can tell they are internal states and never
4471 * stored in a cert store */
4472 break;
4473 }
4474 }
4475 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4476 "x509_ca", ca);
4477}
4478
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004479/*[clinic input]
4480_ssl._SSLContext.get_ca_certs
4481 binary_form: bool = False
4482
4483Returns a list of dicts with information of loaded CA certs.
4484
4485If the optional argument is True, returns a DER-encoded copy of the CA
4486certificate.
4487
4488NOTE: Certificates in a capath directory aren't loaded unless they have
4489been used at least once.
4490[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004491
4492static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004493_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4494/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004495{
4496 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004497 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004498 PyObject *ci = NULL, *rlist = NULL;
4499 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004500
4501 if ((rlist = PyList_New(0)) == NULL) {
4502 return NULL;
4503 }
4504
4505 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004506 objs = X509_STORE_get0_objects(store);
4507 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004508 X509_OBJECT *obj;
4509 X509 *cert;
4510
Christian Heimes598894f2016-09-05 23:19:05 +02004511 obj = sk_X509_OBJECT_value(objs, i);
4512 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004513 /* not a x509 cert */
4514 continue;
4515 }
4516 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004517 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004518 if (!X509_check_ca(cert)) {
4519 continue;
4520 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004521 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004522 ci = _certificate_to_der(cert);
4523 } else {
4524 ci = _decode_certificate(cert);
4525 }
4526 if (ci == NULL) {
4527 goto error;
4528 }
4529 if (PyList_Append(rlist, ci) == -1) {
4530 goto error;
4531 }
4532 Py_CLEAR(ci);
4533 }
4534 return rlist;
4535
4536 error:
4537 Py_XDECREF(ci);
4538 Py_XDECREF(rlist);
4539 return NULL;
4540}
4541
4542
Antoine Pitrou152efa22010-05-16 18:19:27 +00004543static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004544 {"check_hostname", (getter) get_check_hostname,
4545 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004546 {"_host_flags", (getter) get_host_flags,
4547 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004548#if SSL_CTRL_GET_MAX_PROTO_VERSION
4549 {"minimum_version", (getter) get_minimum_version,
4550 (setter) set_minimum_version, NULL},
4551 {"maximum_version", (getter) get_maximum_version,
4552 (setter) set_maximum_version, NULL},
4553#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004554 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004555 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004556 {"options", (getter) get_options,
4557 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004558 {"post_handshake_auth", (getter) get_post_handshake_auth,
4559#ifdef TLS1_3_VERSION
4560 (setter) set_post_handshake_auth,
4561#else
4562 NULL,
4563#endif
4564 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004565 {"protocol", (getter) get_protocol,
4566 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004567 {"verify_flags", (getter) get_verify_flags,
4568 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004569 {"verify_mode", (getter) get_verify_mode,
4570 (setter) set_verify_mode, NULL},
4571 {NULL}, /* sentinel */
4572};
4573
4574static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004575 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4576 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4577 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4578 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4579 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4580 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4581 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4582 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4583 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4584 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4585 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004586 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4587 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004588 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004589 {NULL, NULL} /* sentinel */
4590};
4591
4592static PyTypeObject PySSLContext_Type = {
4593 PyVarObject_HEAD_INIT(NULL, 0)
4594 "_ssl._SSLContext", /*tp_name*/
4595 sizeof(PySSLContext), /*tp_basicsize*/
4596 0, /*tp_itemsize*/
4597 (destructor)context_dealloc, /*tp_dealloc*/
4598 0, /*tp_print*/
4599 0, /*tp_getattr*/
4600 0, /*tp_setattr*/
4601 0, /*tp_reserved*/
4602 0, /*tp_repr*/
4603 0, /*tp_as_number*/
4604 0, /*tp_as_sequence*/
4605 0, /*tp_as_mapping*/
4606 0, /*tp_hash*/
4607 0, /*tp_call*/
4608 0, /*tp_str*/
4609 0, /*tp_getattro*/
4610 0, /*tp_setattro*/
4611 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004612 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004613 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004614 (traverseproc) context_traverse, /*tp_traverse*/
4615 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004616 0, /*tp_richcompare*/
4617 0, /*tp_weaklistoffset*/
4618 0, /*tp_iter*/
4619 0, /*tp_iternext*/
4620 context_methods, /*tp_methods*/
4621 0, /*tp_members*/
4622 context_getsetlist, /*tp_getset*/
4623 0, /*tp_base*/
4624 0, /*tp_dict*/
4625 0, /*tp_descr_get*/
4626 0, /*tp_descr_set*/
4627 0, /*tp_dictoffset*/
4628 0, /*tp_init*/
4629 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004630 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004631};
4632
4633
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004634/*
4635 * MemoryBIO objects
4636 */
4637
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004638/*[clinic input]
4639@classmethod
4640_ssl.MemoryBIO.__new__
4641
4642[clinic start generated code]*/
4643
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004644static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004645_ssl_MemoryBIO_impl(PyTypeObject *type)
4646/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004648 BIO *bio;
4649 PySSLMemoryBIO *self;
4650
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004651 bio = BIO_new(BIO_s_mem());
4652 if (bio == NULL) {
4653 PyErr_SetString(PySSLErrorObject,
4654 "failed to allocate BIO");
4655 return NULL;
4656 }
4657 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4658 * just that no data is currently available. The SSL routines should retry
4659 * the read, which we can achieve by calling BIO_set_retry_read(). */
4660 BIO_set_retry_read(bio);
4661 BIO_set_mem_eof_return(bio, -1);
4662
4663 assert(type != NULL && type->tp_alloc != NULL);
4664 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4665 if (self == NULL) {
4666 BIO_free(bio);
4667 return NULL;
4668 }
4669 self->bio = bio;
4670 self->eof_written = 0;
4671
4672 return (PyObject *) self;
4673}
4674
4675static void
4676memory_bio_dealloc(PySSLMemoryBIO *self)
4677{
4678 BIO_free(self->bio);
4679 Py_TYPE(self)->tp_free(self);
4680}
4681
4682static PyObject *
4683memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4684{
Segev Finer5cff6372017-07-27 01:19:17 +03004685 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004686}
4687
4688PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4689"The number of bytes pending in the memory BIO.");
4690
4691static PyObject *
4692memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4693{
4694 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4695 && self->eof_written);
4696}
4697
4698PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4699"Whether the memory BIO is at EOF.");
4700
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004701/*[clinic input]
4702_ssl.MemoryBIO.read
4703 size as len: int = -1
4704 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004705
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004706Read up to size bytes from the memory BIO.
4707
4708If size is not specified, read the entire buffer.
4709If the return value is an empty bytes instance, this means either
4710EOF or that no data is available. Use the "eof" property to
4711distinguish between the two.
4712[clinic start generated code]*/
4713
4714static PyObject *
4715_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4716/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4717{
4718 int avail, nbytes;
4719 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004720
Segev Finer5cff6372017-07-27 01:19:17 +03004721 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004722 if ((len < 0) || (len > avail))
4723 len = avail;
4724
4725 result = PyBytes_FromStringAndSize(NULL, len);
4726 if ((result == NULL) || (len == 0))
4727 return result;
4728
4729 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004730 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004731 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004732 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004733 return NULL;
4734 }
4735
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004736 /* There should never be any short reads but check anyway. */
4737 if (nbytes < len) {
4738 _PyBytes_Resize(&result, nbytes);
4739 }
4740
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004741 return result;
4742}
4743
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004744/*[clinic input]
4745_ssl.MemoryBIO.write
4746 b: Py_buffer
4747 /
4748
4749Writes the bytes b into the memory BIO.
4750
4751Returns the number of bytes written.
4752[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004753
4754static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004755_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4756/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004757{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004758 int nbytes;
4759
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004760 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004761 PyErr_Format(PyExc_OverflowError,
4762 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004763 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004764 }
4765
4766 if (self->eof_written) {
4767 PyErr_SetString(PySSLErrorObject,
4768 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004769 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004770 }
4771
Segev Finer5cff6372017-07-27 01:19:17 +03004772 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004773 if (nbytes < 0) {
4774 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004775 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004776 }
4777
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004778 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004779}
4780
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004781/*[clinic input]
4782_ssl.MemoryBIO.write_eof
4783
4784Write an EOF marker to the memory BIO.
4785
4786When all data has been read, the "eof" property will be True.
4787[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004788
4789static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004790_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4791/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004792{
4793 self->eof_written = 1;
4794 /* After an EOF is written, a zero return from read() should be a real EOF
4795 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4796 BIO_clear_retry_flags(self->bio);
4797 BIO_set_mem_eof_return(self->bio, 0);
4798
4799 Py_RETURN_NONE;
4800}
4801
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004802static PyGetSetDef memory_bio_getsetlist[] = {
4803 {"pending", (getter) memory_bio_get_pending, NULL,
4804 PySSL_memory_bio_pending_doc},
4805 {"eof", (getter) memory_bio_get_eof, NULL,
4806 PySSL_memory_bio_eof_doc},
4807 {NULL}, /* sentinel */
4808};
4809
4810static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004811 _SSL_MEMORYBIO_READ_METHODDEF
4812 _SSL_MEMORYBIO_WRITE_METHODDEF
4813 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004814 {NULL, NULL} /* sentinel */
4815};
4816
4817static PyTypeObject PySSLMemoryBIO_Type = {
4818 PyVarObject_HEAD_INIT(NULL, 0)
4819 "_ssl.MemoryBIO", /*tp_name*/
4820 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4821 0, /*tp_itemsize*/
4822 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4823 0, /*tp_print*/
4824 0, /*tp_getattr*/
4825 0, /*tp_setattr*/
4826 0, /*tp_reserved*/
4827 0, /*tp_repr*/
4828 0, /*tp_as_number*/
4829 0, /*tp_as_sequence*/
4830 0, /*tp_as_mapping*/
4831 0, /*tp_hash*/
4832 0, /*tp_call*/
4833 0, /*tp_str*/
4834 0, /*tp_getattro*/
4835 0, /*tp_setattro*/
4836 0, /*tp_as_buffer*/
4837 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4838 0, /*tp_doc*/
4839 0, /*tp_traverse*/
4840 0, /*tp_clear*/
4841 0, /*tp_richcompare*/
4842 0, /*tp_weaklistoffset*/
4843 0, /*tp_iter*/
4844 0, /*tp_iternext*/
4845 memory_bio_methods, /*tp_methods*/
4846 0, /*tp_members*/
4847 memory_bio_getsetlist, /*tp_getset*/
4848 0, /*tp_base*/
4849 0, /*tp_dict*/
4850 0, /*tp_descr_get*/
4851 0, /*tp_descr_set*/
4852 0, /*tp_dictoffset*/
4853 0, /*tp_init*/
4854 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004855 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004856};
4857
Antoine Pitrou152efa22010-05-16 18:19:27 +00004858
Christian Heimes99a65702016-09-10 23:44:53 +02004859/*
4860 * SSL Session object
4861 */
4862
4863static void
4864PySSLSession_dealloc(PySSLSession *self)
4865{
INADA Naokia6296d32017-08-24 14:55:17 +09004866 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004867 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004868 Py_XDECREF(self->ctx);
4869 if (self->session != NULL) {
4870 SSL_SESSION_free(self->session);
4871 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004872 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004873}
4874
4875static PyObject *
4876PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4877{
4878 int result;
4879
4880 if (left == NULL || right == NULL) {
4881 PyErr_BadInternalCall();
4882 return NULL;
4883 }
4884
4885 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4886 Py_RETURN_NOTIMPLEMENTED;
4887 }
4888
4889 if (left == right) {
4890 result = 0;
4891 } else {
4892 const unsigned char *left_id, *right_id;
4893 unsigned int left_len, right_len;
4894 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4895 &left_len);
4896 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4897 &right_len);
4898 if (left_len == right_len) {
4899 result = memcmp(left_id, right_id, left_len);
4900 } else {
4901 result = 1;
4902 }
4903 }
4904
4905 switch (op) {
4906 case Py_EQ:
4907 if (result == 0) {
4908 Py_RETURN_TRUE;
4909 } else {
4910 Py_RETURN_FALSE;
4911 }
4912 break;
4913 case Py_NE:
4914 if (result != 0) {
4915 Py_RETURN_TRUE;
4916 } else {
4917 Py_RETURN_FALSE;
4918 }
4919 break;
4920 case Py_LT:
4921 case Py_LE:
4922 case Py_GT:
4923 case Py_GE:
4924 Py_RETURN_NOTIMPLEMENTED;
4925 break;
4926 default:
4927 PyErr_BadArgument();
4928 return NULL;
4929 }
4930}
4931
4932static int
4933PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4934{
4935 Py_VISIT(self->ctx);
4936 return 0;
4937}
4938
4939static int
4940PySSLSession_clear(PySSLSession *self)
4941{
4942 Py_CLEAR(self->ctx);
4943 return 0;
4944}
4945
4946
4947static PyObject *
4948PySSLSession_get_time(PySSLSession *self, void *closure) {
4949 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4950}
4951
4952PyDoc_STRVAR(PySSLSession_get_time_doc,
4953"Session creation time (seconds since epoch).");
4954
4955
4956static PyObject *
4957PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4958 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4959}
4960
4961PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4962"Session timeout (delta in seconds).");
4963
4964
4965static PyObject *
4966PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4967 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4968 return PyLong_FromUnsignedLong(hint);
4969}
4970
4971PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4972"Ticket life time hint.");
4973
4974
4975static PyObject *
4976PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4977 const unsigned char *id;
4978 unsigned int len;
4979 id = SSL_SESSION_get_id(self->session, &len);
4980 return PyBytes_FromStringAndSize((const char *)id, len);
4981}
4982
4983PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4984"Session id");
4985
4986
4987static PyObject *
4988PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4989 if (SSL_SESSION_has_ticket(self->session)) {
4990 Py_RETURN_TRUE;
4991 } else {
4992 Py_RETURN_FALSE;
4993 }
4994}
4995
4996PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4997"Does the session contain a ticket?");
4998
4999
5000static PyGetSetDef PySSLSession_getsetlist[] = {
5001 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5002 PySSLSession_get_has_ticket_doc},
5003 {"id", (getter) PySSLSession_get_session_id, NULL,
5004 PySSLSession_get_session_id_doc},
5005 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5006 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5007 {"time", (getter) PySSLSession_get_time, NULL,
5008 PySSLSession_get_time_doc},
5009 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5010 PySSLSession_get_timeout_doc},
5011 {NULL}, /* sentinel */
5012};
5013
5014static PyTypeObject PySSLSession_Type = {
5015 PyVarObject_HEAD_INIT(NULL, 0)
5016 "_ssl.Session", /*tp_name*/
5017 sizeof(PySSLSession), /*tp_basicsize*/
5018 0, /*tp_itemsize*/
5019 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
5020 0, /*tp_print*/
5021 0, /*tp_getattr*/
5022 0, /*tp_setattr*/
5023 0, /*tp_reserved*/
5024 0, /*tp_repr*/
5025 0, /*tp_as_number*/
5026 0, /*tp_as_sequence*/
5027 0, /*tp_as_mapping*/
5028 0, /*tp_hash*/
5029 0, /*tp_call*/
5030 0, /*tp_str*/
5031 0, /*tp_getattro*/
5032 0, /*tp_setattro*/
5033 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005034 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005035 0, /*tp_doc*/
5036 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5037 (inquiry)PySSLSession_clear, /*tp_clear*/
5038 PySSLSession_richcompare, /*tp_richcompare*/
5039 0, /*tp_weaklistoffset*/
5040 0, /*tp_iter*/
5041 0, /*tp_iternext*/
5042 0, /*tp_methods*/
5043 0, /*tp_members*/
5044 PySSLSession_getsetlist, /*tp_getset*/
5045};
5046
5047
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005048/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005049/*[clinic input]
5050_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005051 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005052 entropy: double
5053 /
5054
5055Mix string into the OpenSSL PRNG state.
5056
5057entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305058string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005059[clinic start generated code]*/
5060
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005061static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005062_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005063/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005064{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005065 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005066 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005067
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005068 buf = (const char *)view->buf;
5069 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005070 do {
5071 written = Py_MIN(len, INT_MAX);
5072 RAND_add(buf, (int)written, entropy);
5073 buf += written;
5074 len -= written;
5075 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005076 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005077}
5078
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005079static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005080PySSL_RAND(int len, int pseudo)
5081{
5082 int ok;
5083 PyObject *bytes;
5084 unsigned long err;
5085 const char *errstr;
5086 PyObject *v;
5087
Victor Stinner1e81a392013-12-19 16:47:04 +01005088 if (len < 0) {
5089 PyErr_SetString(PyExc_ValueError, "num must be positive");
5090 return NULL;
5091 }
5092
Victor Stinner99c8b162011-05-24 12:05:19 +02005093 bytes = PyBytes_FromStringAndSize(NULL, len);
5094 if (bytes == NULL)
5095 return NULL;
5096 if (pseudo) {
5097 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5098 if (ok == 0 || ok == 1)
5099 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5100 }
5101 else {
5102 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5103 if (ok == 1)
5104 return bytes;
5105 }
5106 Py_DECREF(bytes);
5107
5108 err = ERR_get_error();
5109 errstr = ERR_reason_error_string(err);
5110 v = Py_BuildValue("(ks)", err, errstr);
5111 if (v != NULL) {
5112 PyErr_SetObject(PySSLErrorObject, v);
5113 Py_DECREF(v);
5114 }
5115 return NULL;
5116}
5117
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005118/*[clinic input]
5119_ssl.RAND_bytes
5120 n: int
5121 /
5122
5123Generate n cryptographically strong pseudo-random bytes.
5124[clinic start generated code]*/
5125
Victor Stinner99c8b162011-05-24 12:05:19 +02005126static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005127_ssl_RAND_bytes_impl(PyObject *module, int n)
5128/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005129{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005130 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005131}
5132
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005133/*[clinic input]
5134_ssl.RAND_pseudo_bytes
5135 n: int
5136 /
5137
5138Generate n pseudo-random bytes.
5139
5140Return a pair (bytes, is_cryptographic). is_cryptographic is True
5141if the bytes generated are cryptographically strong.
5142[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005143
5144static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005145_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5146/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005147{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005148 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005149}
5150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005151/*[clinic input]
5152_ssl.RAND_status
5153
5154Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5155
5156It is necessary to seed the PRNG with RAND_add() on some platforms before
5157using the ssl() function.
5158[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005159
5160static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005161_ssl_RAND_status_impl(PyObject *module)
5162/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005163{
Christian Heimes217cfd12007-12-02 14:31:20 +00005164 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005165}
5166
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005167#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005168/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005169/*[clinic input]
5170_ssl.RAND_egd
5171 path: object(converter="PyUnicode_FSConverter")
5172 /
5173
5174Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5175
5176Returns number of bytes read. Raises SSLError if connection to EGD
5177fails or if it does not provide enough data to seed PRNG.
5178[clinic start generated code]*/
5179
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005180static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005181_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5182/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005183{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005184 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005185 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005186 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005187 PyErr_SetString(PySSLErrorObject,
5188 "EGD connection failed or EGD did not return "
5189 "enough data to seed the PRNG");
5190 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005191 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005192 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005193}
Christian Heimesa5d07652016-09-24 10:48:05 +02005194/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005195#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005196
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005197
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005198
5199/*[clinic input]
5200_ssl.get_default_verify_paths
5201
5202Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5203
5204The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5205[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005206
5207static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005208_ssl_get_default_verify_paths_impl(PyObject *module)
5209/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005210{
5211 PyObject *ofile_env = NULL;
5212 PyObject *ofile = NULL;
5213 PyObject *odir_env = NULL;
5214 PyObject *odir = NULL;
5215
Benjamin Petersond113c962015-07-18 10:59:13 -07005216#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005217 const char *tmp = (info); \
5218 target = NULL; \
5219 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5220 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5221 target = PyBytes_FromString(tmp); } \
5222 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005223 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005224
Benjamin Petersond113c962015-07-18 10:59:13 -07005225 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5226 CONVERT(X509_get_default_cert_file(), ofile);
5227 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5228 CONVERT(X509_get_default_cert_dir(), odir);
5229#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005230
Christian Heimes200bb1b2013-06-14 15:14:29 +02005231 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005232
5233 error:
5234 Py_XDECREF(ofile_env);
5235 Py_XDECREF(ofile);
5236 Py_XDECREF(odir_env);
5237 Py_XDECREF(odir);
5238 return NULL;
5239}
5240
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005241static PyObject*
5242asn1obj2py(ASN1_OBJECT *obj)
5243{
5244 int nid;
5245 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005246
5247 nid = OBJ_obj2nid(obj);
5248 if (nid == NID_undef) {
5249 PyErr_Format(PyExc_ValueError, "Unknown object");
5250 return NULL;
5251 }
5252 sn = OBJ_nid2sn(nid);
5253 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005254 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005255}
5256
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005257/*[clinic input]
5258_ssl.txt2obj
5259 txt: str
5260 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005261
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005262Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5263
5264By default objects are looked up by OID. With name=True short and
5265long name are also matched.
5266[clinic start generated code]*/
5267
5268static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005269_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5270/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005271{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005272 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005273 ASN1_OBJECT *obj;
5274
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005275 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5276 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005277 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005278 return NULL;
5279 }
5280 result = asn1obj2py(obj);
5281 ASN1_OBJECT_free(obj);
5282 return result;
5283}
5284
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005285/*[clinic input]
5286_ssl.nid2obj
5287 nid: int
5288 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005289
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005290Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5291[clinic start generated code]*/
5292
5293static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005294_ssl_nid2obj_impl(PyObject *module, int nid)
5295/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005296{
5297 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005298 ASN1_OBJECT *obj;
5299
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005300 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005301 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005302 return NULL;
5303 }
5304 obj = OBJ_nid2obj(nid);
5305 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005306 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005307 return NULL;
5308 }
5309 result = asn1obj2py(obj);
5310 ASN1_OBJECT_free(obj);
5311 return result;
5312}
5313
Christian Heimes46bebee2013-06-09 19:03:31 +02005314#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005315
5316static PyObject*
5317certEncodingType(DWORD encodingType)
5318{
5319 static PyObject *x509_asn = NULL;
5320 static PyObject *pkcs_7_asn = NULL;
5321
5322 if (x509_asn == NULL) {
5323 x509_asn = PyUnicode_InternFromString("x509_asn");
5324 if (x509_asn == NULL)
5325 return NULL;
5326 }
5327 if (pkcs_7_asn == NULL) {
5328 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5329 if (pkcs_7_asn == NULL)
5330 return NULL;
5331 }
5332 switch(encodingType) {
5333 case X509_ASN_ENCODING:
5334 Py_INCREF(x509_asn);
5335 return x509_asn;
5336 case PKCS_7_ASN_ENCODING:
5337 Py_INCREF(pkcs_7_asn);
5338 return pkcs_7_asn;
5339 default:
5340 return PyLong_FromLong(encodingType);
5341 }
5342}
5343
5344static PyObject*
5345parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5346{
5347 CERT_ENHKEY_USAGE *usage;
5348 DWORD size, error, i;
5349 PyObject *retval;
5350
5351 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5352 error = GetLastError();
5353 if (error == CRYPT_E_NOT_FOUND) {
5354 Py_RETURN_TRUE;
5355 }
5356 return PyErr_SetFromWindowsErr(error);
5357 }
5358
5359 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5360 if (usage == NULL) {
5361 return PyErr_NoMemory();
5362 }
5363
5364 /* Now get the actual enhanced usage property */
5365 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5366 PyMem_Free(usage);
5367 error = GetLastError();
5368 if (error == CRYPT_E_NOT_FOUND) {
5369 Py_RETURN_TRUE;
5370 }
5371 return PyErr_SetFromWindowsErr(error);
5372 }
5373 retval = PySet_New(NULL);
5374 if (retval == NULL) {
5375 goto error;
5376 }
5377 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5378 if (usage->rgpszUsageIdentifier[i]) {
5379 PyObject *oid;
5380 int err;
5381 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5382 if (oid == NULL) {
5383 Py_CLEAR(retval);
5384 goto error;
5385 }
5386 err = PySet_Add(retval, oid);
5387 Py_DECREF(oid);
5388 if (err == -1) {
5389 Py_CLEAR(retval);
5390 goto error;
5391 }
5392 }
5393 }
5394 error:
5395 PyMem_Free(usage);
5396 return retval;
5397}
5398
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005399/*[clinic input]
5400_ssl.enum_certificates
5401 store_name: str
5402
5403Retrieve certificates from Windows' cert store.
5404
5405store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5406more cert storages, too. The function returns a list of (bytes,
5407encoding_type, trust) tuples. The encoding_type flag can be interpreted
5408with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5409a set of OIDs or the boolean True.
5410[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005411
Christian Heimes46bebee2013-06-09 19:03:31 +02005412static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005413_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5414/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005415{
Christian Heimes46bebee2013-06-09 19:03:31 +02005416 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005417 PCCERT_CONTEXT pCertCtx = NULL;
5418 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005419 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005420
Christian Heimes44109d72013-11-22 01:51:30 +01005421 result = PyList_New(0);
5422 if (result == NULL) {
5423 return NULL;
5424 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005425 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5426 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5427 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005428 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005429 Py_DECREF(result);
5430 return PyErr_SetFromWindowsErr(GetLastError());
5431 }
5432
Christian Heimes44109d72013-11-22 01:51:30 +01005433 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5434 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5435 pCertCtx->cbCertEncoded);
5436 if (!cert) {
5437 Py_CLEAR(result);
5438 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005439 }
Christian Heimes44109d72013-11-22 01:51:30 +01005440 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5441 Py_CLEAR(result);
5442 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005443 }
Christian Heimes44109d72013-11-22 01:51:30 +01005444 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5445 if (keyusage == Py_True) {
5446 Py_DECREF(keyusage);
5447 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005448 }
Christian Heimes44109d72013-11-22 01:51:30 +01005449 if (keyusage == NULL) {
5450 Py_CLEAR(result);
5451 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005452 }
Christian Heimes44109d72013-11-22 01:51:30 +01005453 if ((tup = PyTuple_New(3)) == NULL) {
5454 Py_CLEAR(result);
5455 break;
5456 }
5457 PyTuple_SET_ITEM(tup, 0, cert);
5458 cert = NULL;
5459 PyTuple_SET_ITEM(tup, 1, enc);
5460 enc = NULL;
5461 PyTuple_SET_ITEM(tup, 2, keyusage);
5462 keyusage = NULL;
5463 if (PyList_Append(result, tup) < 0) {
5464 Py_CLEAR(result);
5465 break;
5466 }
5467 Py_CLEAR(tup);
5468 }
5469 if (pCertCtx) {
5470 /* loop ended with an error, need to clean up context manually */
5471 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005472 }
5473
5474 /* In error cases cert, enc and tup may not be NULL */
5475 Py_XDECREF(cert);
5476 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005477 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005478 Py_XDECREF(tup);
5479
5480 if (!CertCloseStore(hStore, 0)) {
5481 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005482 Py_XDECREF(result);
5483 return PyErr_SetFromWindowsErr(GetLastError());
5484 }
5485 return result;
5486}
5487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005488/*[clinic input]
5489_ssl.enum_crls
5490 store_name: str
5491
5492Retrieve CRLs from Windows' cert store.
5493
5494store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5495more cert storages, too. The function returns a list of (bytes,
5496encoding_type) tuples. The encoding_type flag can be interpreted with
5497X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5498[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005499
5500static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005501_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5502/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005503{
Christian Heimes44109d72013-11-22 01:51:30 +01005504 HCERTSTORE hStore = NULL;
5505 PCCRL_CONTEXT pCrlCtx = NULL;
5506 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5507 PyObject *result = NULL;
5508
Christian Heimes44109d72013-11-22 01:51:30 +01005509 result = PyList_New(0);
5510 if (result == NULL) {
5511 return NULL;
5512 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005513 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5514 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5515 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005516 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005517 Py_DECREF(result);
5518 return PyErr_SetFromWindowsErr(GetLastError());
5519 }
Christian Heimes44109d72013-11-22 01:51:30 +01005520
5521 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5522 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5523 pCrlCtx->cbCrlEncoded);
5524 if (!crl) {
5525 Py_CLEAR(result);
5526 break;
5527 }
5528 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5529 Py_CLEAR(result);
5530 break;
5531 }
5532 if ((tup = PyTuple_New(2)) == NULL) {
5533 Py_CLEAR(result);
5534 break;
5535 }
5536 PyTuple_SET_ITEM(tup, 0, crl);
5537 crl = NULL;
5538 PyTuple_SET_ITEM(tup, 1, enc);
5539 enc = NULL;
5540
5541 if (PyList_Append(result, tup) < 0) {
5542 Py_CLEAR(result);
5543 break;
5544 }
5545 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005546 }
Christian Heimes44109d72013-11-22 01:51:30 +01005547 if (pCrlCtx) {
5548 /* loop ended with an error, need to clean up context manually */
5549 CertFreeCRLContext(pCrlCtx);
5550 }
5551
5552 /* In error cases cert, enc and tup may not be NULL */
5553 Py_XDECREF(crl);
5554 Py_XDECREF(enc);
5555 Py_XDECREF(tup);
5556
5557 if (!CertCloseStore(hStore, 0)) {
5558 /* This error case might shadow another exception.*/
5559 Py_XDECREF(result);
5560 return PyErr_SetFromWindowsErr(GetLastError());
5561 }
5562 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005563}
Christian Heimes44109d72013-11-22 01:51:30 +01005564
5565#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005566
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005567/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005568static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005569 _SSL__TEST_DECODE_CERT_METHODDEF
5570 _SSL_RAND_ADD_METHODDEF
5571 _SSL_RAND_BYTES_METHODDEF
5572 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5573 _SSL_RAND_EGD_METHODDEF
5574 _SSL_RAND_STATUS_METHODDEF
5575 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5576 _SSL_ENUM_CERTIFICATES_METHODDEF
5577 _SSL_ENUM_CRLS_METHODDEF
5578 _SSL_TXT2OBJ_METHODDEF
5579 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005580 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005581};
5582
5583
Christian Heimes598894f2016-09-05 23:19:05 +02005584#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005585
5586/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005587 * of the Python C thread library
5588 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5589 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005590
5591static PyThread_type_lock *_ssl_locks = NULL;
5592
Christian Heimes4d98ca92013-08-19 17:36:29 +02005593#if OPENSSL_VERSION_NUMBER >= 0x10000000
5594/* use new CRYPTO_THREADID API. */
5595static void
5596_ssl_threadid_callback(CRYPTO_THREADID *id)
5597{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005598 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005599}
5600#else
5601/* deprecated CRYPTO_set_id_callback() API. */
5602static unsigned long
5603_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005604 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005605}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005606#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005607
Bill Janssen6e027db2007-11-15 22:23:56 +00005608static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005609 (int mode, int n, const char *file, int line) {
5610 /* this function is needed to perform locking on shared data
5611 structures. (Note that OpenSSL uses a number of global data
5612 structures that will be implicitly shared whenever multiple
5613 threads use OpenSSL.) Multi-threaded applications will
5614 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005616 locking_function() must be able to handle up to
5617 CRYPTO_num_locks() different mutex locks. It sets the n-th
5618 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005620 file and line are the file number of the function setting the
5621 lock. They can be useful for debugging.
5622 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005624 if ((_ssl_locks == NULL) ||
5625 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5626 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005628 if (mode & CRYPTO_LOCK) {
5629 PyThread_acquire_lock(_ssl_locks[n], 1);
5630 } else {
5631 PyThread_release_lock(_ssl_locks[n]);
5632 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005633}
5634
5635static int _setup_ssl_threads(void) {
5636
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005637 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005639 if (_ssl_locks == NULL) {
5640 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005641 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5642 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005643 if (_ssl_locks == NULL) {
5644 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005645 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005646 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005647 for (i = 0; i < _ssl_locks_count; i++) {
5648 _ssl_locks[i] = PyThread_allocate_lock();
5649 if (_ssl_locks[i] == NULL) {
5650 unsigned int j;
5651 for (j = 0; j < i; j++) {
5652 PyThread_free_lock(_ssl_locks[j]);
5653 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005654 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005655 return 0;
5656 }
5657 }
5658 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005659#if OPENSSL_VERSION_NUMBER >= 0x10000000
5660 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5661#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005662 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005663#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005664 }
5665 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005666}
5667
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005668#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005669
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005670PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005671"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005672for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005673
Martin v. Löwis1a214512008-06-11 05:26:20 +00005674
5675static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005676 PyModuleDef_HEAD_INIT,
5677 "_ssl",
5678 module_doc,
5679 -1,
5680 PySSL_methods,
5681 NULL,
5682 NULL,
5683 NULL,
5684 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005685};
5686
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005687
5688static void
5689parse_openssl_version(unsigned long libver,
5690 unsigned int *major, unsigned int *minor,
5691 unsigned int *fix, unsigned int *patch,
5692 unsigned int *status)
5693{
5694 *status = libver & 0xF;
5695 libver >>= 4;
5696 *patch = libver & 0xFF;
5697 libver >>= 8;
5698 *fix = libver & 0xFF;
5699 libver >>= 8;
5700 *minor = libver & 0xFF;
5701 libver >>= 8;
5702 *major = libver & 0xFF;
5703}
5704
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005705PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005706PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005707{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005708 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005709 unsigned long libver;
5710 unsigned int major, minor, fix, patch, status;
5711 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005712 struct py_ssl_error_code *errcode;
5713 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005714
Antoine Pitrou152efa22010-05-16 18:19:27 +00005715 if (PyType_Ready(&PySSLContext_Type) < 0)
5716 return NULL;
5717 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005718 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005719 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5720 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005721 if (PyType_Ready(&PySSLSession_Type) < 0)
5722 return NULL;
5723
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005724
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005725 m = PyModule_Create(&_sslmodule);
5726 if (m == NULL)
5727 return NULL;
5728 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005730 /* Load _socket module and its C API */
5731 socket_api = PySocketModule_ImportModuleAndAPI();
5732 if (!socket_api)
5733 return NULL;
5734 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005735
Christian Heimesc941e622017-09-05 15:47:11 +02005736#ifndef OPENSSL_VERSION_1_1
5737 /* Load all algorithms and initialize cpuid */
5738 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005739 /* Init OpenSSL */
5740 SSL_load_error_strings();
5741 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005742#endif
5743
Christian Heimes598894f2016-09-05 23:19:05 +02005744#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005745 /* note that this will start threading if not already started */
5746 if (!_setup_ssl_threads()) {
5747 return NULL;
5748 }
Christian Heimes598894f2016-09-05 23:19:05 +02005749#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5750 /* OpenSSL 1.1.0 builtin thread support is enabled */
5751 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005752#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005754 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005755 sslerror_type_slots[0].pfunc = PyExc_OSError;
5756 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005757 if (PySSLErrorObject == NULL)
5758 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005759
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005760 /* ssl.CertificateError used to be a subclass of ValueError */
5761 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5762 if (bases == NULL)
5763 return NULL;
5764 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5765 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5766 bases, NULL);
5767 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005768 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5769 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5770 PySSLErrorObject, NULL);
5771 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5772 "ssl.SSLWantReadError", SSLWantReadError_doc,
5773 PySSLErrorObject, NULL);
5774 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5775 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5776 PySSLErrorObject, NULL);
5777 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5778 "ssl.SSLSyscallError", SSLSyscallError_doc,
5779 PySSLErrorObject, NULL);
5780 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5781 "ssl.SSLEOFError", SSLEOFError_doc,
5782 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005783 if (PySSLCertVerificationErrorObject == NULL
5784 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005785 || PySSLWantReadErrorObject == NULL
5786 || PySSLWantWriteErrorObject == NULL
5787 || PySSLSyscallErrorObject == NULL
5788 || PySSLEOFErrorObject == NULL)
5789 return NULL;
5790 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005791 || PyDict_SetItemString(d, "SSLCertVerificationError",
5792 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005793 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5794 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5795 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5796 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5797 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005798 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005799 if (PyDict_SetItemString(d, "_SSLContext",
5800 (PyObject *)&PySSLContext_Type) != 0)
5801 return NULL;
5802 if (PyDict_SetItemString(d, "_SSLSocket",
5803 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005804 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005805 if (PyDict_SetItemString(d, "MemoryBIO",
5806 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5807 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005808 if (PyDict_SetItemString(d, "SSLSession",
5809 (PyObject *)&PySSLSession_Type) != 0)
5810 return NULL;
5811
Christian Heimes892d66e2018-01-29 14:10:18 +01005812 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5813 PY_SSL_DEFAULT_CIPHER_STRING);
5814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005815 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5816 PY_SSL_ERROR_ZERO_RETURN);
5817 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5818 PY_SSL_ERROR_WANT_READ);
5819 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5820 PY_SSL_ERROR_WANT_WRITE);
5821 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5822 PY_SSL_ERROR_WANT_X509_LOOKUP);
5823 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5824 PY_SSL_ERROR_SYSCALL);
5825 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5826 PY_SSL_ERROR_SSL);
5827 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5828 PY_SSL_ERROR_WANT_CONNECT);
5829 /* non ssl.h errorcodes */
5830 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5831 PY_SSL_ERROR_EOF);
5832 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5833 PY_SSL_ERROR_INVALID_ERROR_CODE);
5834 /* cert requirements */
5835 PyModule_AddIntConstant(m, "CERT_NONE",
5836 PY_SSL_CERT_NONE);
5837 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5838 PY_SSL_CERT_OPTIONAL);
5839 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5840 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005841 /* CRL verification for verification_flags */
5842 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5843 0);
5844 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5845 X509_V_FLAG_CRL_CHECK);
5846 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5847 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5848 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5849 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005850#ifdef X509_V_FLAG_TRUSTED_FIRST
5851 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5852 X509_V_FLAG_TRUSTED_FIRST);
5853#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005854
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005855 /* Alert Descriptions from ssl.h */
5856 /* note RESERVED constants no longer intended for use have been removed */
5857 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5858
5859#define ADD_AD_CONSTANT(s) \
5860 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5861 SSL_AD_##s)
5862
5863 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5864 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5865 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5866 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5867 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5868 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5869 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5870 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5871 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5872 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5873 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5874 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5875 ADD_AD_CONSTANT(UNKNOWN_CA);
5876 ADD_AD_CONSTANT(ACCESS_DENIED);
5877 ADD_AD_CONSTANT(DECODE_ERROR);
5878 ADD_AD_CONSTANT(DECRYPT_ERROR);
5879 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5880 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5881 ADD_AD_CONSTANT(INTERNAL_ERROR);
5882 ADD_AD_CONSTANT(USER_CANCELLED);
5883 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005884 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005885#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5886 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5887#endif
5888#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5889 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5890#endif
5891#ifdef SSL_AD_UNRECOGNIZED_NAME
5892 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5893#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005894#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5895 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5896#endif
5897#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5898 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5899#endif
5900#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5901 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5902#endif
5903
5904#undef ADD_AD_CONSTANT
5905
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005906 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005907#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005908 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5909 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005910#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005911#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005912 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5913 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005914#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005915 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005916 PY_SSL_VERSION_TLS);
5917 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5918 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005919 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5920 PY_SSL_VERSION_TLS_CLIENT);
5921 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5922 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005923 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5924 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005925#if HAVE_TLSv1_2
5926 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5927 PY_SSL_VERSION_TLS1_1);
5928 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5929 PY_SSL_VERSION_TLS1_2);
5930#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005931
Antoine Pitroub5218772010-05-21 09:56:06 +00005932 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005933 PyModule_AddIntConstant(m, "OP_ALL",
5934 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005935 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5936 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5937 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005938#if HAVE_TLSv1_2
5939 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5940 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5941#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005942#ifdef SSL_OP_NO_TLSv1_3
5943 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5944#else
5945 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5946#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005947 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5948 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005949 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005950 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005951#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005952 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005953#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005954#ifdef SSL_OP_NO_COMPRESSION
5955 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5956 SSL_OP_NO_COMPRESSION);
5957#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005958#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5959 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5960 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5961#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005962#ifdef SSL_OP_NO_RENEGOTIATION
5963 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5964 SSL_OP_NO_RENEGOTIATION);
5965#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005966
Christian Heimes61d478c2018-01-27 15:51:38 +01005967#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5968 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5969 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5970#endif
5971#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5972 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5973 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5974#endif
5975#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5976 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5977 X509_CHECK_FLAG_NO_WILDCARDS);
5978#endif
5979#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5980 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5981 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5982#endif
5983#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5984 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5985 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5986#endif
5987#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5988 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5989 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5990#endif
5991
Christian Heimes698dde12018-02-27 11:54:43 +01005992 /* protocol versions */
5993 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5994 PY_PROTO_MINIMUM_SUPPORTED);
5995 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5996 PY_PROTO_MAXIMUM_SUPPORTED);
5997 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5998 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5999 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6000 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6001 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006002
Victor Stinnerb37672d2018-11-22 03:37:50 +01006003#define addbool(m, key, value) \
6004 do { \
6005 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6006 Py_INCREF(bool_obj); \
6007 PyModule_AddObject((m), (key), bool_obj); \
6008 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006009
6010#if HAVE_SNI
6011 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006012#else
Christian Heimes698dde12018-02-27 11:54:43 +01006013 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006014#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006015
6016 addbool(m, "HAS_TLS_UNIQUE", 1);
6017
6018#ifndef OPENSSL_NO_ECDH
6019 addbool(m, "HAS_ECDH", 1);
6020#else
6021 addbool(m, "HAS_ECDH", 0);
6022#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006023
Christian Heimes29eab552018-02-25 12:31:33 +01006024#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006025 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006026#else
Christian Heimes698dde12018-02-27 11:54:43 +01006027 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006028#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006029
Christian Heimes29eab552018-02-25 12:31:33 +01006030#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006031 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006032#else
Christian Heimes698dde12018-02-27 11:54:43 +01006033 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006034#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006035
6036#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6037 addbool(m, "HAS_SSLv2", 1);
6038#else
6039 addbool(m, "HAS_SSLv2", 0);
6040#endif
6041
6042#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6043 addbool(m, "HAS_SSLv3", 1);
6044#else
6045 addbool(m, "HAS_SSLv3", 0);
6046#endif
6047
6048#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6049 addbool(m, "HAS_TLSv1", 1);
6050#else
6051 addbool(m, "HAS_TLSv1", 0);
6052#endif
6053
6054#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6055 addbool(m, "HAS_TLSv1_1", 1);
6056#else
6057 addbool(m, "HAS_TLSv1_1", 0);
6058#endif
6059
6060#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6061 addbool(m, "HAS_TLSv1_2", 1);
6062#else
6063 addbool(m, "HAS_TLSv1_2", 0);
6064#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006065
Christian Heimescb5b68a2017-09-07 18:07:00 -07006066#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006067 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006068#else
Christian Heimes698dde12018-02-27 11:54:43 +01006069 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006070#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006071
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006072 /* Mappings for error codes */
6073 err_codes_to_names = PyDict_New();
6074 err_names_to_codes = PyDict_New();
6075 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6076 return NULL;
6077 errcode = error_codes;
6078 while (errcode->mnemonic != NULL) {
6079 PyObject *mnemo, *key;
6080 mnemo = PyUnicode_FromString(errcode->mnemonic);
6081 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6082 if (mnemo == NULL || key == NULL)
6083 return NULL;
6084 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6085 return NULL;
6086 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6087 return NULL;
6088 Py_DECREF(key);
6089 Py_DECREF(mnemo);
6090 errcode++;
6091 }
6092 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6093 return NULL;
6094 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6095 return NULL;
6096
6097 lib_codes_to_names = PyDict_New();
6098 if (lib_codes_to_names == NULL)
6099 return NULL;
6100 libcode = library_codes;
6101 while (libcode->library != NULL) {
6102 PyObject *mnemo, *key;
6103 key = PyLong_FromLong(libcode->code);
6104 mnemo = PyUnicode_FromString(libcode->library);
6105 if (key == NULL || mnemo == NULL)
6106 return NULL;
6107 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6108 return NULL;
6109 Py_DECREF(key);
6110 Py_DECREF(mnemo);
6111 libcode++;
6112 }
6113 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6114 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006115
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006116 /* OpenSSL version */
6117 /* SSLeay() gives us the version of the library linked against,
6118 which could be different from the headers version.
6119 */
6120 libver = SSLeay();
6121 r = PyLong_FromUnsignedLong(libver);
6122 if (r == NULL)
6123 return NULL;
6124 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6125 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006126 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006127 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6128 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6129 return NULL;
6130 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6131 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6132 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006133
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006134 libver = OPENSSL_VERSION_NUMBER;
6135 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6136 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6137 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6138 return NULL;
6139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006140 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006141}