blob: a0d34b34baadca94235b5cb6a8dda8707c851cb2 [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
Christian Heimesc7f70692019-05-31 11:44:05 +0200188#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
189#define HAVE_OPENSSL_KEYLOG 1
190#endif
191
Victor Stinner524714e2016-07-22 17:43:59 +0200192#ifndef INVALID_SOCKET /* MS defines this */
193#define INVALID_SOCKET (-1)
194#endif
195
Christian Heimes4ca07392018-03-24 15:41:37 +0100196/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
197#ifndef OPENSSL_VERSION_1_1
198#define HAVE_OPENSSL_CRYPTO_LOCK
199#endif
200
201#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200202#define OPENSSL_NO_SSL2
203#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100204
205#ifndef PY_OPENSSL_1_1_API
206/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200209#define TLS_client_method SSLv23_client_method
210#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200211
212static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
213{
214 return ne->set;
215}
216
217#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200218/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200219static int COMP_get_type(const COMP_METHOD *meth)
220{
221 return meth->type;
222}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200223/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200224#endif
225
226static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
227{
228 return ctx->default_passwd_callback;
229}
230
231static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
232{
233 return ctx->default_passwd_callback_userdata;
234}
235
236static int X509_OBJECT_get_type(X509_OBJECT *x)
237{
238 return x->type;
239}
240
241static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
242{
243 return x->data.x509;
244}
245
246static int BIO_up_ref(BIO *b)
247{
248 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
249 return 1;
250}
251
252static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
253 return store->objs;
254}
255
Christian Heimes99a65702016-09-10 23:44:53 +0200256static int
257SSL_SESSION_has_ticket(const SSL_SESSION *s)
258{
259 return (s->tlsext_ticklen > 0) ? 1 : 0;
260}
261
262static unsigned long
263SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
264{
265 return s->tlsext_tick_lifetime_hint;
266}
267
Christian Heimes4ca07392018-03-24 15:41:37 +0100268#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200269
Christian Heimes892d66e2018-01-29 14:10:18 +0100270/* Default cipher suites */
271#ifndef PY_SSL_DEFAULT_CIPHERS
272#define PY_SSL_DEFAULT_CIPHERS 1
273#endif
274
275#if PY_SSL_DEFAULT_CIPHERS == 0
276 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
277 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
278 #endif
279#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200280/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100281 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
282 * !aNULL:!eNULL: really no NULL ciphers
283 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
284 * !aDSS: no authentication with discrete logarithm DSA algorithm
285 * !SRP:!PSK: no secure remote password or pre-shared key authentication
286 */
287 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
288#elif PY_SSL_DEFAULT_CIPHERS == 2
289/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
290 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
291#else
292 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
293#endif
294
Christian Heimes598894f2016-09-05 23:19:05 +0200295
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000296enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 /* these mirror ssl.h */
298 PY_SSL_ERROR_NONE,
299 PY_SSL_ERROR_SSL,
300 PY_SSL_ERROR_WANT_READ,
301 PY_SSL_ERROR_WANT_WRITE,
302 PY_SSL_ERROR_WANT_X509_LOOKUP,
303 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
304 PY_SSL_ERROR_ZERO_RETURN,
305 PY_SSL_ERROR_WANT_CONNECT,
306 /* start of non ssl.h errorcodes */
307 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
308 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
309 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000310};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311
Thomas Woutersed03b412007-08-28 21:37:11 +0000312enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 PY_SSL_CLIENT,
314 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000315};
316
317enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000318 PY_SSL_CERT_NONE,
319 PY_SSL_CERT_OPTIONAL,
320 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000321};
322
323enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000324 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200325 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#if HAVE_TLSv1_2
328 PY_SSL_VERSION_TLS1,
329 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100331#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200332 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000333#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200334 PY_SSL_VERSION_TLS_CLIENT=0x10,
335 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100336};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200337
Christian Heimes698dde12018-02-27 11:54:43 +0100338enum py_proto_version {
339 PY_PROTO_MINIMUM_SUPPORTED = -2,
340 PY_PROTO_SSLv3 = SSL3_VERSION,
341 PY_PROTO_TLSv1 = TLS1_VERSION,
342 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
343 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
344#ifdef TLS1_3_VERSION
345 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
346#else
347 PY_PROTO_TLSv1_3 = 0x304,
348#endif
349 PY_PROTO_MAXIMUM_SUPPORTED = -1,
350
351/* OpenSSL has no dedicated API to set the minimum version to the maximum
352 * available version, and the other way around. We have to figure out the
353 * minimum and maximum available version on our own and hope for the best.
354 */
355#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
357#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
359#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
361#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
362 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
363#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
364 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
365#else
366 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
367#endif
368
369#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
371#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
373#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
375#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
376 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
377#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
378 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
379#else
380 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
381#endif
382};
383
384
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000385/* serves as a flag to see whether we've initialized the SSL thread support. */
386/* 0 means no, greater than 0 means yes */
387
388static unsigned int _ssl_locks_count = 0;
389
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000390/* SSL socket object */
391
392#define X509_NAME_MAXLEN 256
393
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000394/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
395 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
396 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
397#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000398# define HAVE_SSL_CTX_CLEAR_OPTIONS
399#else
400# undef HAVE_SSL_CTX_CLEAR_OPTIONS
401#endif
402
Antoine Pitroud6494802011-07-21 01:11:30 +0200403/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
404 * older SSL, but let's be safe */
405#define PySSL_CB_MAXLEN 128
406
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100407
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000410 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100411#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100413 int npn_protocols_len;
414#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100415#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500416 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300417 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500418#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100419#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100420 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100421#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100422 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100423 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
424 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
425 */
426 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100427 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200428#ifdef TLS1_3_VERSION
429 int post_handshake_auth;
430#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200431 PyObject *msg_cb;
432#ifdef HAVE_OPENSSL_KEYLOG
433 PyObject *keylog_filename;
434 BIO *keylog_bio;
435#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000436} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700439 int ssl; /* last seen error from SSL */
440 int c; /* last seen error from libc */
441#ifdef MS_WINDOWS
442 int ws; /* last seen error from winsock */
443#endif
444} _PySSLError;
445
446typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447 PyObject_HEAD
448 PyObject *Socket; /* weakref to socket on which we're layered */
449 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100450 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200451 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200452 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200453 PyObject *owner; /* Python level "owner" passed to servername callback */
454 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700455 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200456 /* Some SSL callbacks don't have error reporting. Callback wrappers
457 * store exception information on the socket. The handshake, read, write,
458 * and shutdown methods check for chained exceptions.
459 */
460 PyObject *exc_type;
461 PyObject *exc_value;
462 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000463} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000464
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200465typedef struct {
466 PyObject_HEAD
467 BIO *bio;
468 int eof_written;
469} PySSLMemoryBIO;
470
Christian Heimes99a65702016-09-10 23:44:53 +0200471typedef struct {
472 PyObject_HEAD
473 SSL_SESSION *session;
474 PySSLContext *ctx;
475} PySSLSession;
476
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477static PyTypeObject PySSLContext_Type;
478static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200479static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200480static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700482static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
483{
484 _PySSLError err = { 0 };
485 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700486#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700487 err.ws = WSAGetLastError();
488 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700489#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700490 err.c = errno;
491 err.ssl = SSL_get_error(ssl, retcode);
492 }
493 return err;
494}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300496/*[clinic input]
497module _ssl
498class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
499class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
500class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200501class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300502[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200503/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300504
505#include "clinic/_ssl.c.h"
506
Victor Stinner14690702015-04-06 22:46:13 +0200507static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000508
Christian Heimes141c5e82018-02-24 21:10:57 +0100509static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
510static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000511#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200513#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000514
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000515typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 SOCKET_IS_NONBLOCKING,
517 SOCKET_IS_BLOCKING,
518 SOCKET_HAS_TIMED_OUT,
519 SOCKET_HAS_BEEN_CLOSED,
520 SOCKET_TOO_LARGE_FOR_SELECT,
521 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000522} timeout_state;
523
Thomas Woutersed03b412007-08-28 21:37:11 +0000524/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000525#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200526#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000527
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200528/* Get the socket from a PySSLSocket, if it has one */
529#define GET_SOCKET(obj) ((obj)->Socket ? \
530 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200531
Victor Stinner14690702015-04-06 22:46:13 +0200532/* If sock is NULL, use a timeout of 0 second */
533#define GET_SOCKET_TIMEOUT(sock) \
534 ((sock != NULL) ? (sock)->sock_timeout : 0)
535
Christian Heimesc7f70692019-05-31 11:44:05 +0200536#include "_ssl/debughelpers.c"
537
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200538/*
539 * SSL errors.
540 */
541
542PyDoc_STRVAR(SSLError_doc,
543"An error occurred in the SSL implementation.");
544
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700545PyDoc_STRVAR(SSLCertVerificationError_doc,
546"A certificate could not be verified.");
547
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200548PyDoc_STRVAR(SSLZeroReturnError_doc,
549"SSL/TLS session closed cleanly.");
550
551PyDoc_STRVAR(SSLWantReadError_doc,
552"Non-blocking SSL socket needs to read more data\n"
553"before the requested operation can be completed.");
554
555PyDoc_STRVAR(SSLWantWriteError_doc,
556"Non-blocking SSL socket needs to write more data\n"
557"before the requested operation can be completed.");
558
559PyDoc_STRVAR(SSLSyscallError_doc,
560"System error when attempting SSL operation.");
561
562PyDoc_STRVAR(SSLEOFError_doc,
563"SSL/TLS connection terminated abruptly.");
564
565static PyObject *
566SSLError_str(PyOSErrorObject *self)
567{
568 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
569 Py_INCREF(self->strerror);
570 return self->strerror;
571 }
572 else
573 return PyObject_Str(self->args);
574}
575
576static PyType_Slot sslerror_type_slots[] = {
577 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900578 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 {Py_tp_str, SSLError_str},
580 {0, 0},
581};
582
583static PyType_Spec sslerror_type_spec = {
584 "ssl.SSLError",
585 sizeof(PyOSErrorObject),
586 0,
587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
588 sslerror_type_slots
589};
590
591static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700592fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
593 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594{
595 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700596 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 PyObject *init_value, *msg, *key;
598 _Py_IDENTIFIER(reason);
599 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700600 _Py_IDENTIFIER(verify_message);
601 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200602
603 if (errcode != 0) {
604 int lib, reason;
605
606 lib = ERR_GET_LIB(errcode);
607 reason = ERR_GET_REASON(errcode);
608 key = Py_BuildValue("ii", lib, reason);
609 if (key == NULL)
610 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300611 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300613 if (reason_obj == NULL && PyErr_Occurred()) {
614 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200615 }
616 key = PyLong_FromLong(lib);
617 if (key == NULL)
618 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300619 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200620 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300621 if (lib_obj == NULL && PyErr_Occurred()) {
622 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200623 }
624 if (errstr == NULL)
625 errstr = ERR_reason_error_string(errcode);
626 }
627 if (errstr == NULL)
628 errstr = "unknown error";
629
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700630 /* verify code for cert validation error */
631 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
632 const char *verify_str = NULL;
633 long verify_code;
634
635 verify_code = SSL_get_verify_result(sslsock->ssl);
636 verify_code_obj = PyLong_FromLong(verify_code);
637 if (verify_code_obj == NULL) {
638 goto fail;
639 }
640
641 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700642#ifdef X509_V_ERR_HOSTNAME_MISMATCH
643 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700644 case X509_V_ERR_HOSTNAME_MISMATCH:
645 verify_obj = PyUnicode_FromFormat(
646 "Hostname mismatch, certificate is not valid for '%S'.",
647 sslsock->server_hostname
648 );
649 break;
Christian Heimes09153602017-09-08 14:47:58 -0700650#endif
651#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700652 case X509_V_ERR_IP_ADDRESS_MISMATCH:
653 verify_obj = PyUnicode_FromFormat(
654 "IP address mismatch, certificate is not valid for '%S'.",
655 sslsock->server_hostname
656 );
657 break;
Christian Heimes09153602017-09-08 14:47:58 -0700658#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 default:
660 verify_str = X509_verify_cert_error_string(verify_code);
661 if (verify_str != NULL) {
662 verify_obj = PyUnicode_FromString(verify_str);
663 } else {
664 verify_obj = Py_None;
665 Py_INCREF(verify_obj);
666 }
667 break;
668 }
669 if (verify_obj == NULL) {
670 goto fail;
671 }
672 }
673
674 if (verify_obj && reason_obj && lib_obj)
675 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
676 lib_obj, reason_obj, errstr, verify_obj,
677 lineno);
678 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200679 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
680 lib_obj, reason_obj, errstr, lineno);
681 else if (lib_obj)
682 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
683 lib_obj, errstr, lineno);
684 else
685 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 if (msg == NULL)
687 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100688
Paul Monsonfb7e7502019-05-15 15:38:55 -0700689 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100690 if (init_value == NULL)
691 goto fail;
692
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200693 err_value = PyObject_CallObject(type, init_value);
694 Py_DECREF(init_value);
695 if (err_value == NULL)
696 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100697
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200698 if (reason_obj == NULL)
699 reason_obj = Py_None;
700 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
701 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700702
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200703 if (lib_obj == NULL)
704 lib_obj = Py_None;
705 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
706 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700707
708 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
709 /* Only set verify code / message for SSLCertVerificationError */
710 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
711 verify_code_obj))
712 goto fail;
713 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
714 goto fail;
715 }
716
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200717 PyErr_SetObject(type, err_value);
718fail:
719 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700720 Py_XDECREF(verify_code_obj);
721 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200722}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000723
Christian Heimesc7f70692019-05-31 11:44:05 +0200724static int
725PySSL_ChainExceptions(PySSLSocket *sslsock) {
726 if (sslsock->exc_type == NULL)
727 return 0;
728
729 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
730 sslsock->exc_type = NULL;
731 sslsock->exc_value = NULL;
732 sslsock->exc_tb = NULL;
733 return -1;
734}
735
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700737PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000738{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200739 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200740 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700741 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200743 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200746 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000747
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700748 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700749 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000750
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700751 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200753 errstr = "TLS/SSL connection has been closed (EOF)";
754 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 p = PY_SSL_ERROR_ZERO_RETURN;
756 break;
757 case SSL_ERROR_WANT_READ:
758 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200759 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 p = PY_SSL_ERROR_WANT_READ;
761 break;
762 case SSL_ERROR_WANT_WRITE:
763 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200764 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 errstr = "The operation did not complete (write)";
766 break;
767 case SSL_ERROR_WANT_X509_LOOKUP:
768 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000769 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 break;
771 case SSL_ERROR_WANT_CONNECT:
772 p = PY_SSL_ERROR_WANT_CONNECT;
773 errstr = "The operation did not complete (connect)";
774 break;
775 case SSL_ERROR_SYSCALL:
776 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700778 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000780 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200781 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200783 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000785 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700786#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700787 if (err.ws) {
788 return PyErr_SetFromWindowsErr(err.ws);
789 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700790#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700791 if (err.c) {
792 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700793 return PyErr_SetFromErrno(PyExc_OSError);
794 }
795 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200796 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000797 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200798 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000800 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200801 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000802 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 }
804 } else {
805 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 }
807 break;
808 }
809 case SSL_ERROR_SSL:
810 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700812 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200813 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000814 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700815 }
816 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
817 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
818 type = PySSLCertVerificationErrorObject;
819 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 break;
821 }
822 default:
823 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
824 errstr = "Invalid error code";
825 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700827 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000828 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200829 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000831}
832
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200834_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200836 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200838 else
839 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700840 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000841 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843}
844
Christian Heimes61d478c2018-01-27 15:51:38 +0100845/*
846 * SSL objects
847 */
848
849static int
850_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
851{
852 int retval = -1;
853 ASN1_OCTET_STRING *ip;
854 PyObject *hostname;
855 size_t len;
856
857 assert(server_hostname);
858
859 /* Disable OpenSSL's special mode with leading dot in hostname:
860 * When name starts with a dot (e.g ".example.com"), it will be
861 * matched by a certificate valid for any sub-domain of name.
862 */
863 len = strlen(server_hostname);
864 if (len == 0 || *server_hostname == '.') {
865 PyErr_SetString(
866 PyExc_ValueError,
867 "server_hostname cannot be an empty string or start with a "
868 "leading dot.");
869 return retval;
870 }
871
872 /* inet_pton is not available on all platforms. */
873 ip = a2i_IPADDRESS(server_hostname);
874 if (ip == NULL) {
875 ERR_clear_error();
876 }
877
Christian Heimes11a14932018-02-24 02:35:08 +0100878 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100879 if (hostname == NULL) {
880 goto error;
881 }
882 self->server_hostname = hostname;
883
884 /* Only send SNI extension for non-IP hostnames */
885 if (ip == NULL) {
886 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
887 _setSSLError(NULL, 0, __FILE__, __LINE__);
888 }
889 }
890 if (self->ctx->check_hostname) {
891 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
892 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200893 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
894 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100895 _setSSLError(NULL, 0, __FILE__, __LINE__);
896 goto error;
897 }
898 } else {
899 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
900 ASN1_STRING_length(ip))) {
901 _setSSLError(NULL, 0, __FILE__, __LINE__);
902 goto error;
903 }
904 }
905 }
906 retval = 0;
907 error:
908 if (ip != NULL) {
909 ASN1_OCTET_STRING_free(ip);
910 }
911 return retval;
912}
913
Antoine Pitrou152efa22010-05-16 18:19:27 +0000914static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100915newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000916 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200917 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100918 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000920{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000921 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100922 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700923 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000924
Antoine Pitrou152efa22010-05-16 18:19:27 +0000925 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 if (self == NULL)
927 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100931 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700932 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200933 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200934 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700935 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700936 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200937 self->exc_type = NULL;
938 self->exc_value = NULL;
939 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000945 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700947 if (self->ssl == NULL) {
948 Py_DECREF(self);
949 _setSSLError(NULL, 0, __FILE__, __LINE__);
950 return NULL;
951 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200952 SSL_set_app_data(self->ssl, self);
953 if (sock) {
954 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
955 } else {
956 /* BIOs are reference counted and SSL_set_bio borrows our reference.
957 * To prevent a double free in memory_bio_dealloc() we need to take an
958 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200959 BIO_up_ref(inbio->bio);
960 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200961 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
962 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400963 SSL_set_mode(self->ssl,
964 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000965
Christian Heimesf0f59302019-07-01 08:29:17 +0200966#ifdef TLS1_3_VERSION
967 if (sslctx->post_handshake_auth == 1) {
968 if (socket_type == PY_SSL_SERVER) {
969 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
970 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
971 * only in combination with SSL_VERIFY_PEER flag. */
972 int mode = SSL_get_verify_mode(self->ssl);
973 if (mode & SSL_VERIFY_PEER) {
974 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
975 verify_cb = SSL_get_verify_callback(self->ssl);
976 mode |= SSL_VERIFY_POST_HANDSHAKE;
977 SSL_set_verify(self->ssl, mode, verify_cb);
978 }
979 } else {
980 /* client socket */
981 SSL_set_post_handshake_auth(self->ssl, 1);
982 }
983 }
984#endif
985
Christian Heimes61d478c2018-01-27 15:51:38 +0100986 if (server_hostname != NULL) {
987 if (_ssl_configure_hostname(self, server_hostname) < 0) {
988 Py_DECREF(self);
989 return NULL;
990 }
991 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 /* If the socket is in non-blocking mode or timeout mode, set the BIO
993 * to non-blocking mode (blocking is the default)
994 */
Victor Stinnere2452312015-03-28 03:00:46 +0100995 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
997 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
998 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 PySSL_BEGIN_ALLOW_THREADS
1001 if (socket_type == PY_SSL_CLIENT)
1002 SSL_set_connect_state(self->ssl);
1003 else
1004 SSL_set_accept_state(self->ssl);
1005 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001006
Antoine Pitroud6494802011-07-21 01:11:30 +02001007 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001008 if (sock != NULL) {
1009 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1010 if (self->Socket == NULL) {
1011 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001012 return NULL;
1013 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001014 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001015 if (owner && owner != Py_None) {
1016 if (PySSL_set_owner(self, owner, NULL) == -1) {
1017 Py_DECREF(self);
1018 return NULL;
1019 }
1020 }
1021 if (session && session != Py_None) {
1022 if (PySSL_set_session(self, session, NULL) == -1) {
1023 Py_DECREF(self);
1024 return NULL;
1025 }
1026 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001028}
1029
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001030/* SSL object methods */
1031
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001032/*[clinic input]
1033_ssl._SSLSocket.do_handshake
1034[clinic start generated code]*/
1035
1036static PyObject *
1037_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1038/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001039{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001041 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001043 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001044 _PyTime_t timeout, deadline = 0;
1045 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001046
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001047 if (sock) {
1048 if (((PyObject*)sock) == Py_None) {
1049 _setSSLError("Underlying socket connection gone",
1050 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1051 return NULL;
1052 }
1053 Py_INCREF(sock);
1054
1055 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001056 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001057 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1058 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001060
Victor Stinner14690702015-04-06 22:46:13 +02001061 timeout = GET_SOCKET_TIMEOUT(sock);
1062 has_timeout = (timeout > 0);
1063 if (has_timeout)
1064 deadline = _PyTime_GetMonotonicClock() + timeout;
1065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 /* Actually negotiate SSL connection */
1067 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001069 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001071 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001073 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001074
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001075 if (PyErr_CheckSignals())
1076 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001077
Victor Stinner14690702015-04-06 22:46:13 +02001078 if (has_timeout)
1079 timeout = deadline - _PyTime_GetMonotonicClock();
1080
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001081 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001082 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001083 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001084 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 } else {
1086 sockstate = SOCKET_OPERATION_OK;
1087 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001090 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001091 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001092 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1094 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001095 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001096 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1098 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001099 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001100 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1102 break;
1103 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001104 } while (err.ssl == SSL_ERROR_WANT_READ ||
1105 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001106 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 if (ret < 1)
1108 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001109 if (PySSL_ChainExceptions(self) < 0)
1110 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001111 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001112error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001113 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001114 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001115 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001116}
1117
Thomas Woutersed03b412007-08-28 21:37:11 +00001118static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001119_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1120{
1121 char buf[X509_NAME_MAXLEN];
1122 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001124 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001125
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001126 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 if (buflen < 0) {
1128 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001129 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001131 /* initial buffer is too small for oid + terminating null byte */
1132 if (buflen > X509_NAME_MAXLEN - 1) {
1133 /* make OBJ_obj2txt() calculate the required buflen */
1134 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1135 /* allocate len + 1 for terminating NULL byte */
1136 namebuf = PyMem_Malloc(buflen + 1);
1137 if (namebuf == NULL) {
1138 PyErr_NoMemory();
1139 return NULL;
1140 }
1141 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1142 if (buflen < 0) {
1143 _setSSLError(NULL, 0, __FILE__, __LINE__);
1144 goto done;
1145 }
1146 }
1147 if (!buflen && no_name) {
1148 Py_INCREF(Py_None);
1149 name_obj = Py_None;
1150 }
1151 else {
1152 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1153 }
1154
1155 done:
1156 if (buf != namebuf) {
1157 PyMem_Free(namebuf);
1158 }
1159 return name_obj;
1160}
1161
1162static PyObject *
1163_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1164{
1165 Py_ssize_t buflen;
1166 unsigned char *valuebuf = NULL;
1167 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1170 if (buflen < 0) {
1171 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001172 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001174 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001177}
1178
1179static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001181{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1183 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1184 PyObject *rdnt;
1185 PyObject *attr = NULL; /* tuple to hold an attribute */
1186 int entry_count = X509_NAME_entry_count(xname);
1187 X509_NAME_ENTRY *entry;
1188 ASN1_OBJECT *name;
1189 ASN1_STRING *value;
1190 int index_counter;
1191 int rdn_level = -1;
1192 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 dn = PyList_New(0);
1195 if (dn == NULL)
1196 return NULL;
1197 /* now create another tuple to hold the top-level RDN */
1198 rdn = PyList_New(0);
1199 if (rdn == NULL)
1200 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 for (index_counter = 0;
1203 index_counter < entry_count;
1204 index_counter++)
1205 {
1206 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 /* check to see if we've gotten to a new RDN */
1209 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001210 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 /* yes, new RDN */
1212 /* add old RDN to DN */
1213 rdnt = PyList_AsTuple(rdn);
1214 Py_DECREF(rdn);
1215 if (rdnt == NULL)
1216 goto fail0;
1217 retcode = PyList_Append(dn, rdnt);
1218 Py_DECREF(rdnt);
1219 if (retcode < 0)
1220 goto fail0;
1221 /* create new RDN */
1222 rdn = PyList_New(0);
1223 if (rdn == NULL)
1224 goto fail0;
1225 }
1226 }
Christian Heimes598894f2016-09-05 23:19:05 +02001227 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 /* now add this attribute to the current RDN */
1230 name = X509_NAME_ENTRY_get_object(entry);
1231 value = X509_NAME_ENTRY_get_data(entry);
1232 attr = _create_tuple_for_attribute(name, value);
1233 /*
1234 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1235 entry->set,
1236 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1237 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1238 */
1239 if (attr == NULL)
1240 goto fail1;
1241 retcode = PyList_Append(rdn, attr);
1242 Py_DECREF(attr);
1243 if (retcode < 0)
1244 goto fail1;
1245 }
1246 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001247 if (rdn != NULL) {
1248 if (PyList_GET_SIZE(rdn) > 0) {
1249 rdnt = PyList_AsTuple(rdn);
1250 Py_DECREF(rdn);
1251 if (rdnt == NULL)
1252 goto fail0;
1253 retcode = PyList_Append(dn, rdnt);
1254 Py_DECREF(rdnt);
1255 if (retcode < 0)
1256 goto fail0;
1257 }
1258 else {
1259 Py_DECREF(rdn);
1260 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 /* convert list to tuple */
1264 rdnt = PyList_AsTuple(dn);
1265 Py_DECREF(dn);
1266 if (rdnt == NULL)
1267 return NULL;
1268 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001269
1270 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272
1273 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 Py_XDECREF(dn);
1275 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276}
1277
1278static PyObject *
1279_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 /* this code follows the procedure outlined in
1282 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1283 function to extract the STACK_OF(GENERAL_NAME),
1284 then iterates through the stack to add the
1285 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001287 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001289 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 GENERAL_NAMES *names = NULL;
1291 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 BIO *biobuf = NULL;
1293 char buf[2048];
1294 char *vptr;
1295 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 if (certificate == NULL)
1298 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 /* get a memory buffer */
1301 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001302 if (biobuf == NULL) {
1303 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1304 return NULL;
1305 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001307 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1308 certificate, NID_subject_alt_name, NULL, NULL);
1309 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 if (peer_alt_names == Py_None) {
1311 peer_alt_names = PyList_New(0);
1312 if (peer_alt_names == NULL)
1313 goto fail;
1314 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001318 int gntype;
1319 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001322 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001323 switch (gntype) {
1324 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 /* we special-case DirName as a tuple of
1326 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 t = PyTuple_New(2);
1329 if (t == NULL) {
1330 goto fail;
1331 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 v = PyUnicode_FromString("DirName");
1334 if (v == NULL) {
1335 Py_DECREF(t);
1336 goto fail;
1337 }
1338 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 v = _create_tuple_for_X509_NAME (name->d.dirn);
1341 if (v == NULL) {
1342 Py_DECREF(t);
1343 goto fail;
1344 }
1345 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001346 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001347
Christian Heimes824f7f32013-08-17 00:54:47 +02001348 case GEN_EMAIL:
1349 case GEN_DNS:
1350 case GEN_URI:
1351 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1352 correctly, CVE-2013-4238 */
1353 t = PyTuple_New(2);
1354 if (t == NULL)
1355 goto fail;
1356 switch (gntype) {
1357 case GEN_EMAIL:
1358 v = PyUnicode_FromString("email");
1359 as = name->d.rfc822Name;
1360 break;
1361 case GEN_DNS:
1362 v = PyUnicode_FromString("DNS");
1363 as = name->d.dNSName;
1364 break;
1365 case GEN_URI:
1366 v = PyUnicode_FromString("URI");
1367 as = name->d.uniformResourceIdentifier;
1368 break;
1369 }
1370 if (v == NULL) {
1371 Py_DECREF(t);
1372 goto fail;
1373 }
1374 PyTuple_SET_ITEM(t, 0, v);
1375 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1376 ASN1_STRING_length(as));
1377 if (v == NULL) {
1378 Py_DECREF(t);
1379 goto fail;
1380 }
1381 PyTuple_SET_ITEM(t, 1, v);
1382 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383
Christian Heimes1c03abd2016-09-06 23:25:35 +02001384 case GEN_RID:
1385 t = PyTuple_New(2);
1386 if (t == NULL)
1387 goto fail;
1388
1389 v = PyUnicode_FromString("Registered ID");
1390 if (v == NULL) {
1391 Py_DECREF(t);
1392 goto fail;
1393 }
1394 PyTuple_SET_ITEM(t, 0, v);
1395
1396 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1397 if (len < 0) {
1398 Py_DECREF(t);
1399 _setSSLError(NULL, 0, __FILE__, __LINE__);
1400 goto fail;
1401 } else if (len >= (int)sizeof(buf)) {
1402 v = PyUnicode_FromString("<INVALID>");
1403 } else {
1404 v = PyUnicode_FromStringAndSize(buf, len);
1405 }
1406 if (v == NULL) {
1407 Py_DECREF(t);
1408 goto fail;
1409 }
1410 PyTuple_SET_ITEM(t, 1, v);
1411 break;
1412
Christian Heimes2b7de662019-12-07 17:59:36 +01001413 case GEN_IPADD:
1414 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1415 * the trailing newline. Remove it in all versions
1416 */
1417 t = PyTuple_New(2);
1418 if (t == NULL)
1419 goto fail;
1420
1421 v = PyUnicode_FromString("IP Address");
1422 if (v == NULL) {
1423 Py_DECREF(t);
1424 goto fail;
1425 }
1426 PyTuple_SET_ITEM(t, 0, v);
1427
1428 if (name->d.ip->length == 4) {
1429 unsigned char *p = name->d.ip->data;
1430 v = PyUnicode_FromFormat(
1431 "%d.%d.%d.%d",
1432 p[0], p[1], p[2], p[3]
1433 );
1434 } else if (name->d.ip->length == 16) {
1435 /* PyUnicode_FromFormat() does not support %X */
1436 unsigned char *p = name->d.ip->data;
1437 len = sprintf(
1438 buf,
1439 "%X:%X:%X:%X:%X:%X:%X:%X",
1440 p[0] << 8 | p[1],
1441 p[2] << 8 | p[3],
1442 p[4] << 8 | p[5],
1443 p[6] << 8 | p[7],
1444 p[8] << 8 | p[9],
1445 p[10] << 8 | p[11],
1446 p[12] << 8 | p[13],
1447 p[14] << 8 | p[15]
1448 );
1449 v = PyUnicode_FromStringAndSize(buf, len);
1450 } else {
1451 v = PyUnicode_FromString("<invalid>");
1452 }
1453
1454 if (v == NULL) {
1455 Py_DECREF(t);
1456 goto fail;
1457 }
1458 PyTuple_SET_ITEM(t, 1, v);
1459 break;
1460
Christian Heimes824f7f32013-08-17 00:54:47 +02001461 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001463 switch (gntype) {
1464 /* check for new general name type */
1465 case GEN_OTHERNAME:
1466 case GEN_X400:
1467 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001468 case GEN_RID:
1469 break;
1470 default:
1471 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1472 "Unknown general name type %d",
1473 gntype) == -1) {
1474 goto fail;
1475 }
1476 break;
1477 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 (void) BIO_reset(biobuf);
1479 GENERAL_NAME_print(biobuf, name);
1480 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1481 if (len < 0) {
1482 _setSSLError(NULL, 0, __FILE__, __LINE__);
1483 goto fail;
1484 }
1485 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001486 if (vptr == NULL) {
1487 PyErr_Format(PyExc_ValueError,
1488 "Invalid value %.200s",
1489 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001491 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 t = PyTuple_New(2);
1493 if (t == NULL)
1494 goto fail;
1495 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1496 if (v == NULL) {
1497 Py_DECREF(t);
1498 goto fail;
1499 }
1500 PyTuple_SET_ITEM(t, 0, v);
1501 v = PyUnicode_FromStringAndSize((vptr + 1),
1502 (len - (vptr - buf + 1)));
1503 if (v == NULL) {
1504 Py_DECREF(t);
1505 goto fail;
1506 }
1507 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001508 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 if (PyList_Append(peer_alt_names, t) < 0) {
1514 Py_DECREF(t);
1515 goto fail;
1516 }
1517 Py_DECREF(t);
1518 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001519 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 }
1521 BIO_free(biobuf);
1522 if (peer_alt_names != Py_None) {
1523 v = PyList_AsTuple(peer_alt_names);
1524 Py_DECREF(peer_alt_names);
1525 return v;
1526 } else {
1527 return peer_alt_names;
1528 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001529
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001530
1531 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 if (biobuf != NULL)
1533 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001534
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 if (peer_alt_names != Py_None) {
1536 Py_XDECREF(peer_alt_names);
1537 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540}
1541
1542static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001543_get_aia_uri(X509 *certificate, int nid) {
1544 PyObject *lst = NULL, *ostr = NULL;
1545 int i, result;
1546 AUTHORITY_INFO_ACCESS *info;
1547
1548 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001549 if (info == NULL)
1550 return Py_None;
1551 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1552 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001553 return Py_None;
1554 }
1555
1556 if ((lst = PyList_New(0)) == NULL) {
1557 goto fail;
1558 }
1559
1560 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1561 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1562 ASN1_IA5STRING *uri;
1563
1564 if ((OBJ_obj2nid(ad->method) != nid) ||
1565 (ad->location->type != GEN_URI)) {
1566 continue;
1567 }
1568 uri = ad->location->d.uniformResourceIdentifier;
1569 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1570 uri->length);
1571 if (ostr == NULL) {
1572 goto fail;
1573 }
1574 result = PyList_Append(lst, ostr);
1575 Py_DECREF(ostr);
1576 if (result < 0) {
1577 goto fail;
1578 }
1579 }
1580 AUTHORITY_INFO_ACCESS_free(info);
1581
1582 /* convert to tuple or None */
1583 if (PyList_Size(lst) == 0) {
1584 Py_DECREF(lst);
1585 return Py_None;
1586 } else {
1587 PyObject *tup;
1588 tup = PyList_AsTuple(lst);
1589 Py_DECREF(lst);
1590 return tup;
1591 }
1592
1593 fail:
1594 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001595 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001596 return NULL;
1597}
1598
1599static PyObject *
1600_get_crl_dp(X509 *certificate) {
1601 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001602 int i, j;
1603 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001604
Christian Heimes598894f2016-09-05 23:19:05 +02001605 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001606
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001607 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001608 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001609
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001610 lst = PyList_New(0);
1611 if (lst == NULL)
1612 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001613
1614 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1615 DIST_POINT *dp;
1616 STACK_OF(GENERAL_NAME) *gns;
1617
1618 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001619 if (dp->distpoint == NULL) {
1620 /* Ignore empty DP value, CVE-2019-5010 */
1621 continue;
1622 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001623 gns = dp->distpoint->name.fullname;
1624
1625 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1626 GENERAL_NAME *gn;
1627 ASN1_IA5STRING *uri;
1628 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001629 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001630
1631 gn = sk_GENERAL_NAME_value(gns, j);
1632 if (gn->type != GEN_URI) {
1633 continue;
1634 }
1635 uri = gn->d.uniformResourceIdentifier;
1636 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1637 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001638 if (ouri == NULL)
1639 goto done;
1640
1641 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001642 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001643 if (err < 0)
1644 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001645 }
1646 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001647
1648 /* Convert to tuple. */
1649 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1650
1651 done:
1652 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001653 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001654 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001655}
1656
1657static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001658_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001659
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001660 PyObject *retval = NULL;
1661 BIO *biobuf = NULL;
1662 PyObject *peer;
1663 PyObject *peer_alt_names = NULL;
1664 PyObject *issuer;
1665 PyObject *version;
1666 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001667 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001668 ASN1_INTEGER *serialNumber;
1669 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001670 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001671 ASN1_TIME *notBefore, *notAfter;
1672 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 retval = PyDict_New();
1675 if (retval == NULL)
1676 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 peer = _create_tuple_for_X509_NAME(
1679 X509_get_subject_name(certificate));
1680 if (peer == NULL)
1681 goto fail0;
1682 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1683 Py_DECREF(peer);
1684 goto fail0;
1685 }
1686 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001687
Antoine Pitroufb046912010-11-09 20:21:19 +00001688 issuer = _create_tuple_for_X509_NAME(
1689 X509_get_issuer_name(certificate));
1690 if (issuer == NULL)
1691 goto fail0;
1692 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001694 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001696 Py_DECREF(issuer);
1697
1698 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001699 if (version == NULL)
1700 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001701 if (PyDict_SetItemString(retval, "version", version) < 0) {
1702 Py_DECREF(version);
1703 goto fail0;
1704 }
1705 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001706
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001707 /* get a memory buffer */
1708 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001709 if (biobuf == NULL) {
1710 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1711 goto fail0;
1712 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001713
Antoine Pitroufb046912010-11-09 20:21:19 +00001714 (void) BIO_reset(biobuf);
1715 serialNumber = X509_get_serialNumber(certificate);
1716 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1717 i2a_ASN1_INTEGER(biobuf, serialNumber);
1718 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1719 if (len < 0) {
1720 _setSSLError(NULL, 0, __FILE__, __LINE__);
1721 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001723 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1724 if (sn_obj == NULL)
1725 goto fail1;
1726 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1727 Py_DECREF(sn_obj);
1728 goto fail1;
1729 }
1730 Py_DECREF(sn_obj);
1731
1732 (void) BIO_reset(biobuf);
1733 notBefore = X509_get_notBefore(certificate);
1734 ASN1_TIME_print(biobuf, notBefore);
1735 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1736 if (len < 0) {
1737 _setSSLError(NULL, 0, __FILE__, __LINE__);
1738 goto fail1;
1739 }
1740 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1741 if (pnotBefore == NULL)
1742 goto fail1;
1743 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1744 Py_DECREF(pnotBefore);
1745 goto fail1;
1746 }
1747 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 (void) BIO_reset(biobuf);
1750 notAfter = X509_get_notAfter(certificate);
1751 ASN1_TIME_print(biobuf, notAfter);
1752 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1753 if (len < 0) {
1754 _setSSLError(NULL, 0, __FILE__, __LINE__);
1755 goto fail1;
1756 }
1757 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1758 if (pnotAfter == NULL)
1759 goto fail1;
1760 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1761 Py_DECREF(pnotAfter);
1762 goto fail1;
1763 }
1764 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 peer_alt_names = _get_peer_alt_names(certificate);
1769 if (peer_alt_names == NULL)
1770 goto fail1;
1771 else if (peer_alt_names != Py_None) {
1772 if (PyDict_SetItemString(retval, "subjectAltName",
1773 peer_alt_names) < 0) {
1774 Py_DECREF(peer_alt_names);
1775 goto fail1;
1776 }
1777 Py_DECREF(peer_alt_names);
1778 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001779
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001780 /* Authority Information Access: OCSP URIs */
1781 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1782 if (obj == NULL) {
1783 goto fail1;
1784 } else if (obj != Py_None) {
1785 result = PyDict_SetItemString(retval, "OCSP", obj);
1786 Py_DECREF(obj);
1787 if (result < 0) {
1788 goto fail1;
1789 }
1790 }
1791
1792 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1793 if (obj == NULL) {
1794 goto fail1;
1795 } else if (obj != Py_None) {
1796 result = PyDict_SetItemString(retval, "caIssuers", obj);
1797 Py_DECREF(obj);
1798 if (result < 0) {
1799 goto fail1;
1800 }
1801 }
1802
1803 /* CDP (CRL distribution points) */
1804 obj = _get_crl_dp(certificate);
1805 if (obj == NULL) {
1806 goto fail1;
1807 } else if (obj != Py_None) {
1808 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1809 Py_DECREF(obj);
1810 if (result < 0) {
1811 goto fail1;
1812 }
1813 }
1814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 BIO_free(biobuf);
1816 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001817
1818 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 if (biobuf != NULL)
1820 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001821 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 Py_XDECREF(retval);
1823 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001824}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001825
Christian Heimes9a5395a2013-06-17 15:44:12 +02001826static PyObject *
1827_certificate_to_der(X509 *certificate)
1828{
1829 unsigned char *bytes_buf = NULL;
1830 int len;
1831 PyObject *retval;
1832
1833 bytes_buf = NULL;
1834 len = i2d_X509(certificate, &bytes_buf);
1835 if (len < 0) {
1836 _setSSLError(NULL, 0, __FILE__, __LINE__);
1837 return NULL;
1838 }
1839 /* this is actually an immutable bytes sequence */
1840 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1841 OPENSSL_free(bytes_buf);
1842 return retval;
1843}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001844
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001845/*[clinic input]
1846_ssl._test_decode_cert
1847 path: object(converter="PyUnicode_FSConverter")
1848 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001849
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001850[clinic start generated code]*/
1851
1852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001853_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1854/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001855{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001857 X509 *x=NULL;
1858 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001859
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1861 PyErr_SetString(PySSLErrorObject,
1862 "Can't malloc memory to read file");
1863 goto fail0;
1864 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001865
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001866 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 PyErr_SetString(PySSLErrorObject,
1868 "Can't open file");
1869 goto fail0;
1870 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001871
Alex Gaynor40dad952019-08-15 08:31:28 -04001872 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 if (x == NULL) {
1874 PyErr_SetString(PySSLErrorObject,
1875 "Error decoding PEM-encoded file");
1876 goto fail0;
1877 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001878
Antoine Pitroufb046912010-11-09 20:21:19 +00001879 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001880 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001881
1882 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001883 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 if (cert != NULL) BIO_free(cert);
1885 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001886}
1887
1888
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001889/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001890_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001891 der as binary_mode: bool = False
1892 /
1893
1894Returns the certificate for the peer.
1895
1896If no certificate was provided, returns None. If a certificate was
1897provided, but not validated, returns an empty dictionary. Otherwise
1898returns a dict containing information about the peer certificate.
1899
1900If the optional argument is True, returns a DER-encoded copy of the
1901peer certificate, or None if no certificate was provided. This will
1902return the certificate even if it wasn't validated.
1903[clinic start generated code]*/
1904
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001905static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001906_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1907/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001908{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001910 X509 *peer_cert;
1911 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912
Christian Heimes66dc33b2017-05-23 16:02:02 -07001913 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001914 PyErr_SetString(PyExc_ValueError,
1915 "handshake not done yet");
1916 return NULL;
1917 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001918 peer_cert = SSL_get_peer_certificate(self->ssl);
1919 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001921
Antoine Pitrou721738f2012-08-15 23:20:39 +02001922 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001924 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001926 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001928 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001930 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001932 X509_free(peer_cert);
1933 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001934}
1935
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001936static PyObject *
1937cipher_to_tuple(const SSL_CIPHER *cipher)
1938{
1939 const char *cipher_name, *cipher_protocol;
1940 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 if (retval == NULL)
1942 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001943
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001944 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001946 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 PyTuple_SET_ITEM(retval, 0, Py_None);
1948 } else {
1949 v = PyUnicode_FromString(cipher_name);
1950 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001951 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 PyTuple_SET_ITEM(retval, 0, v);
1953 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001954
1955 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001957 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 PyTuple_SET_ITEM(retval, 1, Py_None);
1959 } else {
1960 v = PyUnicode_FromString(cipher_protocol);
1961 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001962 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 PyTuple_SET_ITEM(retval, 1, v);
1964 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001965
1966 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001968 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001972
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001973 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974 Py_DECREF(retval);
1975 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001976}
1977
Christian Heimes25bfcd52016-09-06 00:04:45 +02001978#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1979static PyObject *
1980cipher_to_dict(const SSL_CIPHER *cipher)
1981{
1982 const char *cipher_name, *cipher_protocol;
1983
1984 unsigned long cipher_id;
1985 int alg_bits, strength_bits, len;
1986 char buf[512] = {0};
1987#if OPENSSL_VERSION_1_1
1988 int aead, nid;
1989 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1990#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001991
1992 /* can be NULL */
1993 cipher_name = SSL_CIPHER_get_name(cipher);
1994 cipher_protocol = SSL_CIPHER_get_version(cipher);
1995 cipher_id = SSL_CIPHER_get_id(cipher);
1996 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001997 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1998 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001999 if (len > 1 && buf[len-1] == '\n')
2000 buf[len-1] = '\0';
2001 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2002
2003#if OPENSSL_VERSION_1_1
2004 aead = SSL_CIPHER_is_aead(cipher);
2005 nid = SSL_CIPHER_get_cipher_nid(cipher);
2006 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2007 nid = SSL_CIPHER_get_digest_nid(cipher);
2008 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2009 nid = SSL_CIPHER_get_kx_nid(cipher);
2010 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2011 nid = SSL_CIPHER_get_auth_nid(cipher);
2012 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2013#endif
2014
Victor Stinner410b9882016-09-12 12:00:23 +02002015 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002016 "{sksssssssisi"
2017#if OPENSSL_VERSION_1_1
2018 "sOssssssss"
2019#endif
2020 "}",
2021 "id", cipher_id,
2022 "name", cipher_name,
2023 "protocol", cipher_protocol,
2024 "description", buf,
2025 "strength_bits", strength_bits,
2026 "alg_bits", alg_bits
2027#if OPENSSL_VERSION_1_1
2028 ,"aead", aead ? Py_True : Py_False,
2029 "symmetric", skcipher,
2030 "digest", digest,
2031 "kea", kx,
2032 "auth", auth
2033#endif
2034 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002035}
2036#endif
2037
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002038/*[clinic input]
2039_ssl._SSLSocket.shared_ciphers
2040[clinic start generated code]*/
2041
2042static PyObject *
2043_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2044/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002045{
2046 STACK_OF(SSL_CIPHER) *ciphers;
2047 int i;
2048 PyObject *res;
2049
Christian Heimes598894f2016-09-05 23:19:05 +02002050 ciphers = SSL_get_ciphers(self->ssl);
2051 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002052 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002053 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2054 if (!res)
2055 return NULL;
2056 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2057 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2058 if (!tup) {
2059 Py_DECREF(res);
2060 return NULL;
2061 }
2062 PyList_SET_ITEM(res, i, tup);
2063 }
2064 return res;
2065}
2066
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002067/*[clinic input]
2068_ssl._SSLSocket.cipher
2069[clinic start generated code]*/
2070
2071static PyObject *
2072_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2073/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002074{
2075 const SSL_CIPHER *current;
2076
2077 if (self->ssl == NULL)
2078 Py_RETURN_NONE;
2079 current = SSL_get_current_cipher(self->ssl);
2080 if (current == NULL)
2081 Py_RETURN_NONE;
2082 return cipher_to_tuple(current);
2083}
2084
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002085/*[clinic input]
2086_ssl._SSLSocket.version
2087[clinic start generated code]*/
2088
2089static PyObject *
2090_ssl__SSLSocket_version_impl(PySSLSocket *self)
2091/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002092{
2093 const char *version;
2094
2095 if (self->ssl == NULL)
2096 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002097 if (!SSL_is_init_finished(self->ssl)) {
2098 /* handshake not finished */
2099 Py_RETURN_NONE;
2100 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002101 version = SSL_get_version(self->ssl);
2102 if (!strcmp(version, "unknown"))
2103 Py_RETURN_NONE;
2104 return PyUnicode_FromString(version);
2105}
2106
Christian Heimes29eab552018-02-25 12:31:33 +01002107#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002108/*[clinic input]
2109_ssl._SSLSocket.selected_npn_protocol
2110[clinic start generated code]*/
2111
2112static PyObject *
2113_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2114/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2115{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002116 const unsigned char *out;
2117 unsigned int outlen;
2118
Victor Stinner4569cd52013-06-23 14:58:43 +02002119 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002120 &out, &outlen);
2121
2122 if (out == NULL)
2123 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002124 return PyUnicode_FromStringAndSize((char *)out, outlen);
2125}
2126#endif
2127
Christian Heimes29eab552018-02-25 12:31:33 +01002128#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002129/*[clinic input]
2130_ssl._SSLSocket.selected_alpn_protocol
2131[clinic start generated code]*/
2132
2133static PyObject *
2134_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2135/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2136{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002137 const unsigned char *out;
2138 unsigned int outlen;
2139
2140 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2141
2142 if (out == NULL)
2143 Py_RETURN_NONE;
2144 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002145}
2146#endif
2147
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002148/*[clinic input]
2149_ssl._SSLSocket.compression
2150[clinic start generated code]*/
2151
2152static PyObject *
2153_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2154/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2155{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002156#ifdef OPENSSL_NO_COMP
2157 Py_RETURN_NONE;
2158#else
2159 const COMP_METHOD *comp_method;
2160 const char *short_name;
2161
2162 if (self->ssl == NULL)
2163 Py_RETURN_NONE;
2164 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002165 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002166 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002167 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002168 if (short_name == NULL)
2169 Py_RETURN_NONE;
2170 return PyUnicode_DecodeFSDefault(short_name);
2171#endif
2172}
2173
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002174static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2175 Py_INCREF(self->ctx);
2176 return self->ctx;
2177}
2178
2179static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2180 void *closure) {
2181
2182 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002183#if !HAVE_SNI
2184 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2185 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002186 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002187#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002188 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002189 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002190 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002191#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002192 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002193 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002194 return -1;
2195 }
2196
2197 return 0;
2198}
2199
2200PyDoc_STRVAR(PySSL_set_context_doc,
2201"_setter_context(ctx)\n\
2202\
2203This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002204used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002205on the SSLContext to change the certificate information associated with the\n\
2206SSLSocket before the cryptographic exchange handshake messages\n");
2207
2208
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002209static PyObject *
2210PySSL_get_server_side(PySSLSocket *self, void *c)
2211{
2212 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2213}
2214
2215PyDoc_STRVAR(PySSL_get_server_side_doc,
2216"Whether this is a server-side socket.");
2217
2218static PyObject *
2219PySSL_get_server_hostname(PySSLSocket *self, void *c)
2220{
2221 if (self->server_hostname == NULL)
2222 Py_RETURN_NONE;
2223 Py_INCREF(self->server_hostname);
2224 return self->server_hostname;
2225}
2226
2227PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2228"The currently set server hostname (for SNI).");
2229
2230static PyObject *
2231PySSL_get_owner(PySSLSocket *self, void *c)
2232{
2233 PyObject *owner;
2234
2235 if (self->owner == NULL)
2236 Py_RETURN_NONE;
2237
2238 owner = PyWeakref_GetObject(self->owner);
2239 Py_INCREF(owner);
2240 return owner;
2241}
2242
2243static int
2244PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2245{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002246 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002247 if (self->owner == NULL)
2248 return -1;
2249 return 0;
2250}
2251
2252PyDoc_STRVAR(PySSL_get_owner_doc,
2253"The Python-level owner of this object.\
2254Passed as \"self\" in servername callback.");
2255
Christian Heimesc7f70692019-05-31 11:44:05 +02002256static int
2257PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2258{
2259 Py_VISIT(self->exc_type);
2260 Py_VISIT(self->exc_value);
2261 Py_VISIT(self->exc_tb);
2262 return 0;
2263}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002264
Christian Heimesc7f70692019-05-31 11:44:05 +02002265static int
2266PySSL_clear(PySSLSocket *self)
2267{
2268 Py_CLEAR(self->exc_type);
2269 Py_CLEAR(self->exc_value);
2270 Py_CLEAR(self->exc_tb);
2271 return 0;
2272}
2273
2274static void
2275PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002276{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 if (self->ssl)
2278 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002280 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002281 Py_XDECREF(self->server_hostname);
2282 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002284}
2285
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002286/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002287 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002288 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002289 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002290
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002291static int
Victor Stinner14690702015-04-06 22:46:13 +02002292PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002293{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002294 int rc;
2295#ifdef HAVE_POLL
2296 struct pollfd pollfd;
2297 _PyTime_t ms;
2298#else
2299 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 fd_set fds;
2301 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002302#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002305 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002307 else if (timeout < 0) {
2308 if (s->sock_timeout > 0)
2309 return SOCKET_HAS_TIMED_OUT;
2310 else
2311 return SOCKET_IS_BLOCKING;
2312 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002315 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002316 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 /* Prefer poll, if available, since you can poll() any fd
2319 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002320#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002321 pollfd.fd = s->sock_fd;
2322 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002323
Victor Stinner14690702015-04-06 22:46:13 +02002324 /* timeout is in seconds, poll() uses milliseconds */
2325 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002326 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002327
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002328 PySSL_BEGIN_ALLOW_THREADS
2329 rc = poll(&pollfd, 1, (int)ms);
2330 PySSL_END_ALLOW_THREADS
2331#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002333 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002335
Victor Stinner14690702015-04-06 22:46:13 +02002336 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 FD_ZERO(&fds);
2339 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002340
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002341 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002344 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002345 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002347 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002349#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002350
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2352 (when we are able to write or when there's something to read) */
2353 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002354}
2355
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002356/*[clinic input]
2357_ssl._SSLSocket.write
2358 b: Py_buffer
2359 /
2360
2361Writes the bytes-like object b into the SSL object.
2362
2363Returns the number of bytes written.
2364[clinic start generated code]*/
2365
2366static PyObject *
2367_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2368/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002369{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 int len;
2371 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002372 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002374 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002375 _PyTime_t timeout, deadline = 0;
2376 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002377
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002378 if (sock != NULL) {
2379 if (((PyObject*)sock) == Py_None) {
2380 _setSSLError("Underlying socket connection gone",
2381 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2382 return NULL;
2383 }
2384 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 }
2386
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002387 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002388 PyErr_Format(PyExc_OverflowError,
2389 "string longer than %d bytes", INT_MAX);
2390 goto error;
2391 }
2392
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002393 if (sock != NULL) {
2394 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002395 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002396 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2397 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2398 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002399
Victor Stinner14690702015-04-06 22:46:13 +02002400 timeout = GET_SOCKET_TIMEOUT(sock);
2401 has_timeout = (timeout > 0);
2402 if (has_timeout)
2403 deadline = _PyTime_GetMonotonicClock() + timeout;
2404
2405 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002406 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002407 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002408 "The write operation timed out");
2409 goto error;
2410 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2411 PyErr_SetString(PySSLErrorObject,
2412 "Underlying socket has been closed.");
2413 goto error;
2414 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2415 PyErr_SetString(PySSLErrorObject,
2416 "Underlying socket too large for select().");
2417 goto error;
2418 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002419
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002422 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002423 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002425 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002426
2427 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002429
Victor Stinner14690702015-04-06 22:46:13 +02002430 if (has_timeout)
2431 timeout = deadline - _PyTime_GetMonotonicClock();
2432
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002433 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002434 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002435 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002436 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 } else {
2438 sockstate = SOCKET_OPERATION_OK;
2439 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002440
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002442 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 "The write operation timed out");
2444 goto error;
2445 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2446 PyErr_SetString(PySSLErrorObject,
2447 "Underlying socket has been closed.");
2448 goto error;
2449 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2450 break;
2451 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002452 } while (err.ssl == SSL_ERROR_WANT_READ ||
2453 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002454
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002455 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002456 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002457 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002458 if (PySSL_ChainExceptions(self) < 0)
2459 return NULL;
2460 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002461error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002462 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002463 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002464 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002465}
2466
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002467/*[clinic input]
2468_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002469
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002470Returns the number of already decrypted bytes available for read, pending on the connection.
2471[clinic start generated code]*/
2472
2473static PyObject *
2474_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2475/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002476{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002478 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002479
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480 PySSL_BEGIN_ALLOW_THREADS
2481 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002482 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002483 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002484 self->err = err;
2485
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486 if (count < 0)
2487 return PySSL_SetError(self, count, __FILE__, __LINE__);
2488 else
2489 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002490}
2491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492/*[clinic input]
2493_ssl._SSLSocket.read
2494 size as len: int
2495 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002496 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002497 ]
2498 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002499
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002500Read up to size bytes from the SSL socket.
2501[clinic start generated code]*/
2502
2503static PyObject *
2504_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2505 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002506/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002507{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002510 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002512 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002514 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002515 _PyTime_t timeout, deadline = 0;
2516 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002517
Martin Panter5503d472016-03-27 05:35:19 +00002518 if (!group_right_1 && len < 0) {
2519 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2520 return NULL;
2521 }
2522
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002523 if (sock != NULL) {
2524 if (((PyObject*)sock) == Py_None) {
2525 _setSSLError("Underlying socket connection gone",
2526 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2527 return NULL;
2528 }
2529 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002530 }
2531
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002532 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002533 dest = PyBytes_FromStringAndSize(NULL, len);
2534 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002535 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002536 if (len == 0) {
2537 Py_XDECREF(sock);
2538 return dest;
2539 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002540 mem = PyBytes_AS_STRING(dest);
2541 }
2542 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002543 mem = buffer->buf;
2544 if (len <= 0 || len > buffer->len) {
2545 len = (int) buffer->len;
2546 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002547 PyErr_SetString(PyExc_OverflowError,
2548 "maximum length can't fit in a C 'int'");
2549 goto error;
2550 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002551 if (len == 0) {
2552 count = 0;
2553 goto done;
2554 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002555 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002556 }
2557
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002558 if (sock != NULL) {
2559 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002560 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002561 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2562 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2563 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002564
Victor Stinner14690702015-04-06 22:46:13 +02002565 timeout = GET_SOCKET_TIMEOUT(sock);
2566 has_timeout = (timeout > 0);
2567 if (has_timeout)
2568 deadline = _PyTime_GetMonotonicClock() + timeout;
2569
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002570 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 PySSL_BEGIN_ALLOW_THREADS
2572 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002573 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002574 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002575 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002576
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002577 if (PyErr_CheckSignals())
2578 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002579
Victor Stinner14690702015-04-06 22:46:13 +02002580 if (has_timeout)
2581 timeout = deadline - _PyTime_GetMonotonicClock();
2582
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002583 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002584 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002585 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002586 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002587 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002588 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002589 {
2590 count = 0;
2591 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002592 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002593 else
2594 sockstate = SOCKET_OPERATION_OK;
2595
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002597 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 "The read operation timed out");
2599 goto error;
2600 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2601 break;
2602 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002603 } while (err.ssl == SSL_ERROR_WANT_READ ||
2604 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002606 if (count <= 0) {
2607 PySSL_SetError(self, count, __FILE__, __LINE__);
2608 goto error;
2609 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002610 if (self->exc_type != NULL)
2611 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002612
2613done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002614 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002615 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002616 _PyBytes_Resize(&dest, count);
2617 return dest;
2618 }
2619 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 return PyLong_FromLong(count);
2621 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002622
2623error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002624 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002625 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002626 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002627 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002628 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002629}
2630
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002631/*[clinic input]
2632_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002633
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002634Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002635[clinic start generated code]*/
2636
2637static PyObject *
2638_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002639/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002640{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002641 _PySSLError err;
2642 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002643 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002644 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002645 _PyTime_t timeout, deadline = 0;
2646 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002647
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002648 if (sock != NULL) {
2649 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002650 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002651 _setSSLError("Underlying socket connection gone",
2652 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2653 return NULL;
2654 }
2655 Py_INCREF(sock);
2656
2657 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002658 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002659 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2660 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002661 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002662
Victor Stinner14690702015-04-06 22:46:13 +02002663 timeout = GET_SOCKET_TIMEOUT(sock);
2664 has_timeout = (timeout > 0);
2665 if (has_timeout)
2666 deadline = _PyTime_GetMonotonicClock() + timeout;
2667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002668 while (1) {
2669 PySSL_BEGIN_ALLOW_THREADS
2670 /* Disable read-ahead so that unwrap can work correctly.
2671 * Otherwise OpenSSL might read in too much data,
2672 * eating clear text data that happens to be
2673 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002674 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002675 * function is used and the shutdown_seen_zero != 0
2676 * condition is met.
2677 */
2678 if (self->shutdown_seen_zero)
2679 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002680 ret = SSL_shutdown(self->ssl);
2681 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002682 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002683 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002685 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002686 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002687 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002688 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 /* Don't loop endlessly; instead preserve legacy
2690 behaviour of trying SSL_shutdown() only twice.
2691 This looks necessary for OpenSSL < 0.9.8m */
2692 if (++zeros > 1)
2693 break;
2694 /* Shutdown was sent, now try receiving */
2695 self->shutdown_seen_zero = 1;
2696 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002697 }
2698
Victor Stinner14690702015-04-06 22:46:13 +02002699 if (has_timeout)
2700 timeout = deadline - _PyTime_GetMonotonicClock();
2701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002702 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002703 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002704 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002705 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002706 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002707 else
2708 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002710 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002711 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002712 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002713 "The read operation timed out");
2714 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002715 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002716 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002717 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002718 }
2719 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2720 PyErr_SetString(PySSLErrorObject,
2721 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002722 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002723 }
2724 else if (sockstate != SOCKET_OPERATION_OK)
2725 /* Retain the SSL error code */
2726 break;
2727 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002728 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002729 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002730 PySSL_SetError(self, ret, __FILE__, __LINE__);
2731 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002732 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002733 if (self->exc_type != NULL)
2734 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002735 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002736 /* It's already INCREF'ed */
2737 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002738 else
2739 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002740
2741error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002742 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002743 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002744 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002745}
2746
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002747/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002748_ssl._SSLSocket.get_channel_binding
2749 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002750
Christian Heimes141c5e82018-02-24 21:10:57 +01002751Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002752
Christian Heimes141c5e82018-02-24 21:10:57 +01002753Raise ValueError if the requested `cb_type` is not supported. Return bytes
2754of the data or None if the data is not available (e.g. before the handshake).
2755Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002756[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002757
Antoine Pitroud6494802011-07-21 01:11:30 +02002758static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002759_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2760 const char *cb_type)
2761/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002762{
Antoine Pitroud6494802011-07-21 01:11:30 +02002763 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002764 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002765
Christian Heimes141c5e82018-02-24 21:10:57 +01002766 if (strcmp(cb_type, "tls-unique") == 0) {
2767 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2768 /* if session is resumed XOR we are the client */
2769 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2770 }
2771 else {
2772 /* if a new session XOR we are the server */
2773 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2774 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002775 }
2776 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002777 PyErr_Format(
2778 PyExc_ValueError,
2779 "'%s' channel binding type not implemented",
2780 cb_type
2781 );
2782 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002783 }
2784
2785 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002786 if (len == 0)
2787 Py_RETURN_NONE;
2788
Christian Heimes141c5e82018-02-24 21:10:57 +01002789 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002790}
2791
Christian Heimes9fb051f2018-09-23 08:32:31 +02002792/*[clinic input]
2793_ssl._SSLSocket.verify_client_post_handshake
2794
2795Initiate TLS 1.3 post-handshake authentication
2796[clinic start generated code]*/
2797
2798static PyObject *
2799_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2800/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2801{
2802#ifdef TLS1_3_VERSION
2803 int err = SSL_verify_client_post_handshake(self->ssl);
2804 if (err == 0)
2805 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2806 else
2807 Py_RETURN_NONE;
2808#else
2809 PyErr_SetString(PyExc_NotImplementedError,
2810 "Post-handshake auth is not supported by your "
2811 "OpenSSL version.");
2812 return NULL;
2813#endif
2814}
2815
Christian Heimes99a65702016-09-10 23:44:53 +02002816#ifdef OPENSSL_VERSION_1_1
2817
2818static SSL_SESSION*
2819_ssl_session_dup(SSL_SESSION *session) {
2820 SSL_SESSION *newsession = NULL;
2821 int slen;
2822 unsigned char *senc = NULL, *p;
2823 const unsigned char *const_p;
2824
2825 if (session == NULL) {
2826 PyErr_SetString(PyExc_ValueError, "Invalid session");
2827 goto error;
2828 }
2829
2830 /* get length */
2831 slen = i2d_SSL_SESSION(session, NULL);
2832 if (slen == 0 || slen > 0xFF00) {
2833 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2834 goto error;
2835 }
2836 if ((senc = PyMem_Malloc(slen)) == NULL) {
2837 PyErr_NoMemory();
2838 goto error;
2839 }
2840 p = senc;
2841 if (!i2d_SSL_SESSION(session, &p)) {
2842 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2843 goto error;
2844 }
2845 const_p = senc;
2846 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2847 if (session == NULL) {
2848 goto error;
2849 }
2850 PyMem_Free(senc);
2851 return newsession;
2852 error:
2853 if (senc != NULL) {
2854 PyMem_Free(senc);
2855 }
2856 return NULL;
2857}
2858#endif
2859
2860static PyObject *
2861PySSL_get_session(PySSLSocket *self, void *closure) {
2862 /* get_session can return sessions from a server-side connection,
2863 * it does not check for handshake done or client socket. */
2864 PySSLSession *pysess;
2865 SSL_SESSION *session;
2866
2867#ifdef OPENSSL_VERSION_1_1
2868 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2869 * https://github.com/openssl/openssl/issues/1550 */
2870 session = SSL_get0_session(self->ssl); /* borrowed reference */
2871 if (session == NULL) {
2872 Py_RETURN_NONE;
2873 }
2874 if ((session = _ssl_session_dup(session)) == NULL) {
2875 return NULL;
2876 }
2877#else
2878 session = SSL_get1_session(self->ssl);
2879 if (session == NULL) {
2880 Py_RETURN_NONE;
2881 }
2882#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002883 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002884 if (pysess == NULL) {
2885 SSL_SESSION_free(session);
2886 return NULL;
2887 }
2888
2889 assert(self->ctx);
2890 pysess->ctx = self->ctx;
2891 Py_INCREF(pysess->ctx);
2892 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002893 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002894 return (PyObject *)pysess;
2895}
2896
2897static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2898 void *closure)
2899 {
2900 PySSLSession *pysess;
2901#ifdef OPENSSL_VERSION_1_1
2902 SSL_SESSION *session;
2903#endif
2904 int result;
2905
2906 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002907 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002908 return -1;
2909 }
2910 pysess = (PySSLSession *)value;
2911
2912 if (self->ctx->ctx != pysess->ctx->ctx) {
2913 PyErr_SetString(PyExc_ValueError,
2914 "Session refers to a different SSLContext.");
2915 return -1;
2916 }
2917 if (self->socket_type != PY_SSL_CLIENT) {
2918 PyErr_SetString(PyExc_ValueError,
2919 "Cannot set session for server-side SSLSocket.");
2920 return -1;
2921 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002922 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002923 PyErr_SetString(PyExc_ValueError,
2924 "Cannot set session after handshake.");
2925 return -1;
2926 }
2927#ifdef OPENSSL_VERSION_1_1
2928 /* duplicate session */
2929 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2930 return -1;
2931 }
2932 result = SSL_set_session(self->ssl, session);
2933 /* free duplicate, SSL_set_session() bumps ref count */
2934 SSL_SESSION_free(session);
2935#else
2936 result = SSL_set_session(self->ssl, pysess->session);
2937#endif
2938 if (result == 0) {
2939 _setSSLError(NULL, 0, __FILE__, __LINE__);
2940 return -1;
2941 }
2942 return 0;
2943}
2944
2945PyDoc_STRVAR(PySSL_set_session_doc,
2946"_setter_session(session)\n\
2947\
2948Get / set SSLSession.");
2949
2950static PyObject *
2951PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2952 if (SSL_session_reused(self->ssl)) {
2953 Py_RETURN_TRUE;
2954 } else {
2955 Py_RETURN_FALSE;
2956 }
2957}
2958
2959PyDoc_STRVAR(PySSL_get_session_reused_doc,
2960"Was the client session reused during handshake?");
2961
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002962static PyGetSetDef ssl_getsetlist[] = {
2963 {"context", (getter) PySSL_get_context,
2964 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002965 {"server_side", (getter) PySSL_get_server_side, NULL,
2966 PySSL_get_server_side_doc},
2967 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2968 PySSL_get_server_hostname_doc},
2969 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2970 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002971 {"session", (getter) PySSL_get_session,
2972 (setter) PySSL_set_session, PySSL_set_session_doc},
2973 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2974 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002975 {NULL}, /* sentinel */
2976};
2977
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002978static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002979 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2980 _SSL__SSLSOCKET_WRITE_METHODDEF
2981 _SSL__SSLSOCKET_READ_METHODDEF
2982 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002983 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2984 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002985 _SSL__SSLSOCKET_CIPHER_METHODDEF
2986 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2987 _SSL__SSLSOCKET_VERSION_METHODDEF
2988 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2989 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2990 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2991 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002992 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002993 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002994};
2995
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002997 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002998 "_ssl._SSLSocket", /*tp_name*/
2999 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003000 0, /*tp_itemsize*/
3001 /* methods */
3002 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003003 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003004 0, /*tp_getattr*/
3005 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003006 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003007 0, /*tp_repr*/
3008 0, /*tp_as_number*/
3009 0, /*tp_as_sequence*/
3010 0, /*tp_as_mapping*/
3011 0, /*tp_hash*/
3012 0, /*tp_call*/
3013 0, /*tp_str*/
3014 0, /*tp_getattro*/
3015 0, /*tp_setattro*/
3016 0, /*tp_as_buffer*/
3017 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3018 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003019 (traverseproc) PySSL_traverse, /*tp_traverse*/
3020 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003021 0, /*tp_richcompare*/
3022 0, /*tp_weaklistoffset*/
3023 0, /*tp_iter*/
3024 0, /*tp_iternext*/
3025 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003026 0, /*tp_members*/
3027 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003028};
3029
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030
3031/*
3032 * _SSLContext objects
3033 */
3034
Christian Heimes5fe668c2016-09-12 00:01:11 +02003035static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003036_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003037{
3038 int mode;
3039 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3040
3041 switch(n) {
3042 case PY_SSL_CERT_NONE:
3043 mode = SSL_VERIFY_NONE;
3044 break;
3045 case PY_SSL_CERT_OPTIONAL:
3046 mode = SSL_VERIFY_PEER;
3047 break;
3048 case PY_SSL_CERT_REQUIRED:
3049 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3050 break;
3051 default:
3052 PyErr_SetString(PyExc_ValueError,
3053 "invalid value for verify_mode");
3054 return -1;
3055 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003056
3057 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3058 * server sockets and SSL_set_post_handshake_auth() for client. */
3059
Christian Heimes5fe668c2016-09-12 00:01:11 +02003060 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003061 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3062 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003063 return 0;
3064}
3065
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003066/*[clinic input]
3067@classmethod
3068_ssl._SSLContext.__new__
3069 protocol as proto_version: int
3070 /
3071[clinic start generated code]*/
3072
Antoine Pitrou152efa22010-05-16 18:19:27 +00003073static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003074_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3075/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003076{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003077 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003078 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003079 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003080 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003081 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003082#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003083 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003084#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085
Antoine Pitrou152efa22010-05-16 18:19:27 +00003086 PySSL_BEGIN_ALLOW_THREADS
3087 if (proto_version == PY_SSL_VERSION_TLS1)
3088 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003089#if HAVE_TLSv1_2
3090 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3091 ctx = SSL_CTX_new(TLSv1_1_method());
3092 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3093 ctx = SSL_CTX_new(TLSv1_2_method());
3094#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003095#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003096 else if (proto_version == PY_SSL_VERSION_SSL3)
3097 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003098#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003099#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100 else if (proto_version == PY_SSL_VERSION_SSL2)
3101 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003102#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003103 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003104 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003105 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3106 ctx = SSL_CTX_new(TLS_client_method());
3107 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3108 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003109 else
3110 proto_version = -1;
3111 PySSL_END_ALLOW_THREADS
3112
3113 if (proto_version == -1) {
3114 PyErr_SetString(PyExc_ValueError,
3115 "invalid protocol version");
3116 return NULL;
3117 }
3118 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003119 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003120 return NULL;
3121 }
3122
3123 assert(type != NULL && type->tp_alloc != NULL);
3124 self = (PySSLContext *) type->tp_alloc(type, 0);
3125 if (self == NULL) {
3126 SSL_CTX_free(ctx);
3127 return NULL;
3128 }
3129 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003130 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003131 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003132 self->msg_cb = NULL;
3133#ifdef HAVE_OPENSSL_KEYLOG
3134 self->keylog_filename = NULL;
3135 self->keylog_bio = NULL;
3136#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003137#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003138 self->npn_protocols = NULL;
3139#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003140#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003141 self->alpn_protocols = NULL;
3142#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003143#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003144 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003145#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003146 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003147 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3148 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003149 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003150 Py_DECREF(self);
3151 return NULL;
3152 }
3153 } else {
3154 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003155 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003156 Py_DECREF(self);
3157 return NULL;
3158 }
3159 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003160 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003161 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3162 if (proto_version != PY_SSL_VERSION_SSL2)
3163 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003164 if (proto_version != PY_SSL_VERSION_SSL3)
3165 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003166 /* Minimal security flags for server and client side context.
3167 * Client sockets ignore server-side parameters. */
3168#ifdef SSL_OP_NO_COMPRESSION
3169 options |= SSL_OP_NO_COMPRESSION;
3170#endif
3171#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3172 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3173#endif
3174#ifdef SSL_OP_SINGLE_DH_USE
3175 options |= SSL_OP_SINGLE_DH_USE;
3176#endif
3177#ifdef SSL_OP_SINGLE_ECDH_USE
3178 options |= SSL_OP_SINGLE_ECDH_USE;
3179#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003180 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003181
Semen Zhydenko1295e112017-10-15 21:28:31 +02003182 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003183 * It's far from perfect but gives users a better head start. */
3184 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003185#if PY_SSL_DEFAULT_CIPHERS == 2
3186 /* stick to OpenSSL's default settings */
3187 result = 1;
3188#else
3189 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3190#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003191 } else {
3192 /* SSLv2 needs MD5 */
3193 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3194 }
3195 if (result == 0) {
3196 Py_DECREF(self);
3197 ERR_clear_error();
3198 PyErr_SetString(PySSLErrorObject,
3199 "No cipher can be selected.");
3200 return NULL;
3201 }
3202
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003203#if defined(SSL_MODE_RELEASE_BUFFERS)
3204 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3205 usage for no cost at all. However, don't do this for OpenSSL versions
3206 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3207 2014-0198. I can't find exactly which beta fixed this CVE, so be
3208 conservative and assume it wasn't fixed until release. We do this check
3209 at runtime to avoid problems from the dynamic linker.
3210 See #25672 for more on this. */
3211 libver = SSLeay();
3212 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3213 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3214 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3215 }
3216#endif
3217
3218
Donald Stufft8ae264c2017-03-02 11:45:29 -05003219#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003220 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3221 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003222 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3223 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003224#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003225 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3226#else
3227 {
3228 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3229 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3230 EC_KEY_free(key);
3231 }
3232#endif
3233#endif
3234
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003235#define SID_CTX "Python"
3236 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3237 sizeof(SID_CTX));
3238#undef SID_CTX
3239
Christian Heimes61d478c2018-01-27 15:51:38 +01003240 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003241#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003242 /* Improve trust chain building when cross-signed intermediate
3243 certificates are present. See https://bugs.python.org/issue23476. */
3244 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003245#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003246 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003247
Christian Heimes9fb051f2018-09-23 08:32:31 +02003248#ifdef TLS1_3_VERSION
3249 self->post_handshake_auth = 0;
3250 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3251#endif
3252
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 return (PyObject *)self;
3254}
3255
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003256static int
3257context_traverse(PySSLContext *self, visitproc visit, void *arg)
3258{
3259#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003260 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003261#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003262 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003263 return 0;
3264}
3265
3266static int
3267context_clear(PySSLContext *self)
3268{
3269#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003270 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003271#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003272 Py_CLEAR(self->msg_cb);
3273#ifdef HAVE_OPENSSL_KEYLOG
3274 Py_CLEAR(self->keylog_filename);
3275 if (self->keylog_bio != NULL) {
3276 PySSL_BEGIN_ALLOW_THREADS
3277 BIO_free_all(self->keylog_bio);
3278 PySSL_END_ALLOW_THREADS
3279 self->keylog_bio = NULL;
3280 }
3281#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003282 return 0;
3283}
3284
Antoine Pitrou152efa22010-05-16 18:19:27 +00003285static void
3286context_dealloc(PySSLContext *self)
3287{
INADA Naokia6296d32017-08-24 14:55:17 +09003288 /* bpo-31095: UnTrack is needed before calling any callbacks */
3289 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003290 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003291 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003292#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003293 PyMem_FREE(self->npn_protocols);
3294#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003295#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003296 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003297#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003298 Py_TYPE(self)->tp_free(self);
3299}
3300
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003301/*[clinic input]
3302_ssl._SSLContext.set_ciphers
3303 cipherlist: str
3304 /
3305[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003307static PyObject *
3308_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3309/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3310{
3311 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003313 /* Clearing the error queue is necessary on some OpenSSL versions,
3314 otherwise the error will be reported again when another SSL call
3315 is done. */
3316 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 PyErr_SetString(PySSLErrorObject,
3318 "No cipher can be selected.");
3319 return NULL;
3320 }
3321 Py_RETURN_NONE;
3322}
3323
Christian Heimes25bfcd52016-09-06 00:04:45 +02003324#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3325/*[clinic input]
3326_ssl._SSLContext.get_ciphers
3327[clinic start generated code]*/
3328
3329static PyObject *
3330_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3331/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3332{
3333 SSL *ssl = NULL;
3334 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003335 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003336 int i=0;
3337 PyObject *result = NULL, *dct;
3338
3339 ssl = SSL_new(self->ctx);
3340 if (ssl == NULL) {
3341 _setSSLError(NULL, 0, __FILE__, __LINE__);
3342 goto exit;
3343 }
3344 sk = SSL_get_ciphers(ssl);
3345
3346 result = PyList_New(sk_SSL_CIPHER_num(sk));
3347 if (result == NULL) {
3348 goto exit;
3349 }
3350
3351 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3352 cipher = sk_SSL_CIPHER_value(sk, i);
3353 dct = cipher_to_dict(cipher);
3354 if (dct == NULL) {
3355 Py_CLEAR(result);
3356 goto exit;
3357 }
3358 PyList_SET_ITEM(result, i, dct);
3359 }
3360
3361 exit:
3362 if (ssl != NULL)
3363 SSL_free(ssl);
3364 return result;
3365
3366}
3367#endif
3368
3369
Christian Heimes29eab552018-02-25 12:31:33 +01003370#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003371static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003372do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3373 const unsigned char *server_protocols, unsigned int server_protocols_len,
3374 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003375{
Benjamin Peterson88615022015-01-23 17:30:26 -05003376 int ret;
3377 if (client_protocols == NULL) {
3378 client_protocols = (unsigned char *)"";
3379 client_protocols_len = 0;
3380 }
3381 if (server_protocols == NULL) {
3382 server_protocols = (unsigned char *)"";
3383 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003384 }
3385
Benjamin Peterson88615022015-01-23 17:30:26 -05003386 ret = SSL_select_next_proto(out, outlen,
3387 server_protocols, server_protocols_len,
3388 client_protocols, client_protocols_len);
3389 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3390 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003391
3392 return SSL_TLSEXT_ERR_OK;
3393}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003394#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003395
Christian Heimes29eab552018-02-25 12:31:33 +01003396#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003397/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3398static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003399_advertiseNPN_cb(SSL *s,
3400 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003401 void *args)
3402{
3403 PySSLContext *ssl_ctx = (PySSLContext *) args;
3404
3405 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003406 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003407 *len = 0;
3408 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003409 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003410 *len = ssl_ctx->npn_protocols_len;
3411 }
3412
3413 return SSL_TLSEXT_ERR_OK;
3414}
3415/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3416static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003417_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003418 unsigned char **out, unsigned char *outlen,
3419 const unsigned char *server, unsigned int server_len,
3420 void *args)
3421{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003422 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003423 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003424 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003425}
3426#endif
3427
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003428/*[clinic input]
3429_ssl._SSLContext._set_npn_protocols
3430 protos: Py_buffer
3431 /
3432[clinic start generated code]*/
3433
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003434static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003435_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3436 Py_buffer *protos)
3437/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003438{
Christian Heimes29eab552018-02-25 12:31:33 +01003439#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003440 PyMem_Free(self->npn_protocols);
3441 self->npn_protocols = PyMem_Malloc(protos->len);
3442 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003443 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003444 memcpy(self->npn_protocols, protos->buf, protos->len);
3445 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003446
3447 /* set both server and client callbacks, because the context can
3448 * be used to create both types of sockets */
3449 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3450 _advertiseNPN_cb,
3451 self);
3452 SSL_CTX_set_next_proto_select_cb(self->ctx,
3453 _selectNPN_cb,
3454 self);
3455
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003456 Py_RETURN_NONE;
3457#else
3458 PyErr_SetString(PyExc_NotImplementedError,
3459 "The NPN extension requires OpenSSL 1.0.1 or later.");
3460 return NULL;
3461#endif
3462}
3463
Christian Heimes29eab552018-02-25 12:31:33 +01003464#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003465static int
3466_selectALPN_cb(SSL *s,
3467 const unsigned char **out, unsigned char *outlen,
3468 const unsigned char *client_protocols, unsigned int client_protocols_len,
3469 void *args)
3470{
3471 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003472 return do_protocol_selection(1, (unsigned char **)out, outlen,
3473 ctx->alpn_protocols, ctx->alpn_protocols_len,
3474 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003475}
3476#endif
3477
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003478/*[clinic input]
3479_ssl._SSLContext._set_alpn_protocols
3480 protos: Py_buffer
3481 /
3482[clinic start generated code]*/
3483
Benjamin Petersoncca27322015-01-23 16:35:37 -05003484static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003485_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3486 Py_buffer *protos)
3487/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003488{
Christian Heimes29eab552018-02-25 12:31:33 +01003489#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003490 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003491 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003492 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003493 return NULL;
3494 }
3495
Benjamin Petersoncca27322015-01-23 16:35:37 -05003496 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003497 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003498 if (!self->alpn_protocols)
3499 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003500 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003501 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003502
3503 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3504 return PyErr_NoMemory();
3505 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3506
Benjamin Petersoncca27322015-01-23 16:35:37 -05003507 Py_RETURN_NONE;
3508#else
3509 PyErr_SetString(PyExc_NotImplementedError,
3510 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3511 return NULL;
3512#endif
3513}
3514
Antoine Pitrou152efa22010-05-16 18:19:27 +00003515static PyObject *
3516get_verify_mode(PySSLContext *self, void *c)
3517{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003518 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3519 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3520 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3521 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003522 case SSL_VERIFY_NONE:
3523 return PyLong_FromLong(PY_SSL_CERT_NONE);
3524 case SSL_VERIFY_PEER:
3525 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3526 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3527 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3528 }
3529 PyErr_SetString(PySSLErrorObject,
3530 "invalid return value from SSL_CTX_get_verify_mode");
3531 return NULL;
3532}
3533
3534static int
3535set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3536{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003537 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003538 if (!PyArg_Parse(arg, "i", &n))
3539 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003540 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003541 PyErr_SetString(PyExc_ValueError,
3542 "Cannot set verify_mode to CERT_NONE when "
3543 "check_hostname is enabled.");
3544 return -1;
3545 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003546 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003547}
3548
3549static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003550get_verify_flags(PySSLContext *self, void *c)
3551{
Christian Heimes598894f2016-09-05 23:19:05 +02003552 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003553 unsigned long flags;
3554
Christian Heimes61d478c2018-01-27 15:51:38 +01003555 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003556 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003557 return PyLong_FromUnsignedLong(flags);
3558}
3559
3560static int
3561set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3562{
Christian Heimes598894f2016-09-05 23:19:05 +02003563 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003564 unsigned long new_flags, flags, set, clear;
3565
3566 if (!PyArg_Parse(arg, "k", &new_flags))
3567 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003568 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003569 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003570 clear = flags & ~new_flags;
3571 set = ~flags & new_flags;
3572 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003573 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003574 _setSSLError(NULL, 0, __FILE__, __LINE__);
3575 return -1;
3576 }
3577 }
3578 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003579 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003580 _setSSLError(NULL, 0, __FILE__, __LINE__);
3581 return -1;
3582 }
3583 }
3584 return 0;
3585}
3586
Christian Heimes698dde12018-02-27 11:54:43 +01003587/* Getter and setter for protocol version */
3588#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3589
3590
3591static int
3592set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3593{
3594 long v;
3595 int result;
3596
3597 if (!PyArg_Parse(arg, "l", &v))
3598 return -1;
3599 if (v > INT_MAX) {
3600 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3601 return -1;
3602 }
3603
3604 switch(self->protocol) {
3605 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3606 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3607 case PY_SSL_VERSION_TLS:
3608 break;
3609 default:
3610 PyErr_SetString(
3611 PyExc_ValueError,
3612 "The context's protocol doesn't support modification of "
3613 "highest and lowest version."
3614 );
3615 return -1;
3616 }
3617
3618 if (what == 0) {
3619 switch(v) {
3620 case PY_PROTO_MINIMUM_SUPPORTED:
3621 v = 0;
3622 break;
3623 case PY_PROTO_MAXIMUM_SUPPORTED:
3624 /* Emulate max for set_min_proto_version */
3625 v = PY_PROTO_MAXIMUM_AVAILABLE;
3626 break;
3627 default:
3628 break;
3629 }
3630 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3631 }
3632 else {
3633 switch(v) {
3634 case PY_PROTO_MAXIMUM_SUPPORTED:
3635 v = 0;
3636 break;
3637 case PY_PROTO_MINIMUM_SUPPORTED:
3638 /* Emulate max for set_min_proto_version */
3639 v = PY_PROTO_MINIMUM_AVAILABLE;
3640 break;
3641 default:
3642 break;
3643 }
3644 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3645 }
3646 if (result == 0) {
3647 PyErr_Format(PyExc_ValueError,
3648 "Unsupported protocol version 0x%x", v);
3649 return -1;
3650 }
3651 return 0;
3652}
3653
3654static PyObject *
3655get_minimum_version(PySSLContext *self, void *c)
3656{
3657 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3658 if (v == 0) {
3659 v = PY_PROTO_MINIMUM_SUPPORTED;
3660 }
3661 return PyLong_FromLong(v);
3662}
3663
3664static int
3665set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3666{
3667 return set_min_max_proto_version(self, arg, 0);
3668}
3669
3670static PyObject *
3671get_maximum_version(PySSLContext *self, void *c)
3672{
3673 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3674 if (v == 0) {
3675 v = PY_PROTO_MAXIMUM_SUPPORTED;
3676 }
3677 return PyLong_FromLong(v);
3678}
3679
3680static int
3681set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3682{
3683 return set_min_max_proto_version(self, arg, 1);
3684}
3685#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3686
Christian Heimes78c7d522019-06-03 21:00:10 +02003687#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3688static PyObject *
3689get_num_tickets(PySSLContext *self, void *c)
3690{
Victor Stinner76611c72019-07-09 13:30:52 +02003691 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003692}
3693
3694static int
3695set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3696{
3697 long num;
3698 if (!PyArg_Parse(arg, "l", &num))
3699 return -1;
3700 if (num < 0) {
3701 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3702 return -1;
3703 }
3704 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3705 PyErr_SetString(PyExc_ValueError,
3706 "SSLContext is not a server context.");
3707 return -1;
3708 }
3709 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3710 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3711 return -1;
3712 }
3713 return 0;
3714}
3715
3716PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3717"Control the number of TLSv1.3 session tickets");
3718#endif /* OpenSSL 1.1.1 */
3719
Christian Heimes22587792013-11-21 23:56:13 +01003720static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003721get_options(PySSLContext *self, void *c)
3722{
3723 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3724}
3725
3726static int
3727set_options(PySSLContext *self, PyObject *arg, void *c)
3728{
3729 long new_opts, opts, set, clear;
3730 if (!PyArg_Parse(arg, "l", &new_opts))
3731 return -1;
3732 opts = SSL_CTX_get_options(self->ctx);
3733 clear = opts & ~new_opts;
3734 set = ~opts & new_opts;
3735 if (clear) {
3736#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3737 SSL_CTX_clear_options(self->ctx, clear);
3738#else
3739 PyErr_SetString(PyExc_ValueError,
3740 "can't clear options before OpenSSL 0.9.8m");
3741 return -1;
3742#endif
3743 }
3744 if (set)
3745 SSL_CTX_set_options(self->ctx, set);
3746 return 0;
3747}
3748
Christian Heimes1aa9a752013-12-02 02:41:19 +01003749static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003750get_host_flags(PySSLContext *self, void *c)
3751{
3752 return PyLong_FromUnsignedLong(self->hostflags);
3753}
3754
3755static int
3756set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3757{
3758 X509_VERIFY_PARAM *param;
3759 unsigned int new_flags = 0;
3760
3761 if (!PyArg_Parse(arg, "I", &new_flags))
3762 return -1;
3763
3764 param = SSL_CTX_get0_param(self->ctx);
3765 self->hostflags = new_flags;
3766 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3767 return 0;
3768}
3769
3770static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003771get_check_hostname(PySSLContext *self, void *c)
3772{
3773 return PyBool_FromLong(self->check_hostname);
3774}
3775
3776static int
3777set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3778{
3779 int check_hostname;
3780 if (!PyArg_Parse(arg, "p", &check_hostname))
3781 return -1;
3782 if (check_hostname &&
3783 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003784 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003785 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003786 return -1;
3787 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003788 }
3789 self->check_hostname = check_hostname;
3790 return 0;
3791}
3792
Christian Heimes11a14932018-02-24 02:35:08 +01003793static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003794get_post_handshake_auth(PySSLContext *self, void *c) {
3795#if TLS1_3_VERSION
3796 return PyBool_FromLong(self->post_handshake_auth);
3797#else
3798 Py_RETURN_NONE;
3799#endif
3800}
3801
3802#if TLS1_3_VERSION
3803static int
3804set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003805 if (arg == NULL) {
3806 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3807 return -1;
3808 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003809 int pha = PyObject_IsTrue(arg);
3810
3811 if (pha == -1) {
3812 return -1;
3813 }
3814 self->post_handshake_auth = pha;
3815
Christian Heimesf0f59302019-07-01 08:29:17 +02003816 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3817 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003818
3819 return 0;
3820}
3821#endif
3822
3823static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003824get_protocol(PySSLContext *self, void *c) {
3825 return PyLong_FromLong(self->protocol);
3826}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003827
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003828typedef struct {
3829 PyThreadState *thread_state;
3830 PyObject *callable;
3831 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003832 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003833 int error;
3834} _PySSLPasswordInfo;
3835
3836static int
3837_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3838 const char *bad_type_error)
3839{
3840 /* Set the password and size fields of a _PySSLPasswordInfo struct
3841 from a unicode, bytes, or byte array object.
3842 The password field will be dynamically allocated and must be freed
3843 by the caller */
3844 PyObject *password_bytes = NULL;
3845 const char *data = NULL;
3846 Py_ssize_t size;
3847
3848 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003849 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003850 if (!password_bytes) {
3851 goto error;
3852 }
3853 data = PyBytes_AS_STRING(password_bytes);
3854 size = PyBytes_GET_SIZE(password_bytes);
3855 } else if (PyBytes_Check(password)) {
3856 data = PyBytes_AS_STRING(password);
3857 size = PyBytes_GET_SIZE(password);
3858 } else if (PyByteArray_Check(password)) {
3859 data = PyByteArray_AS_STRING(password);
3860 size = PyByteArray_GET_SIZE(password);
3861 } else {
3862 PyErr_SetString(PyExc_TypeError, bad_type_error);
3863 goto error;
3864 }
3865
Victor Stinner9ee02032013-06-23 15:08:23 +02003866 if (size > (Py_ssize_t)INT_MAX) {
3867 PyErr_Format(PyExc_ValueError,
3868 "password cannot be longer than %d bytes", INT_MAX);
3869 goto error;
3870 }
3871
Victor Stinner11ebff22013-07-07 17:07:52 +02003872 PyMem_Free(pw_info->password);
3873 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003874 if (!pw_info->password) {
3875 PyErr_SetString(PyExc_MemoryError,
3876 "unable to allocate password buffer");
3877 goto error;
3878 }
3879 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003880 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003881
3882 Py_XDECREF(password_bytes);
3883 return 1;
3884
3885error:
3886 Py_XDECREF(password_bytes);
3887 return 0;
3888}
3889
3890static int
3891_password_callback(char *buf, int size, int rwflag, void *userdata)
3892{
3893 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3894 PyObject *fn_ret = NULL;
3895
3896 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3897
3898 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003899 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003900 if (!fn_ret) {
3901 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3902 core python API, so we could use it to add a frame here */
3903 goto error;
3904 }
3905
3906 if (!_pwinfo_set(pw_info, fn_ret,
3907 "password callback must return a string")) {
3908 goto error;
3909 }
3910 Py_CLEAR(fn_ret);
3911 }
3912
3913 if (pw_info->size > size) {
3914 PyErr_Format(PyExc_ValueError,
3915 "password cannot be longer than %d bytes", size);
3916 goto error;
3917 }
3918
3919 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3920 memcpy(buf, pw_info->password, pw_info->size);
3921 return pw_info->size;
3922
3923error:
3924 Py_XDECREF(fn_ret);
3925 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3926 pw_info->error = 1;
3927 return -1;
3928}
3929
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003930/*[clinic input]
3931_ssl._SSLContext.load_cert_chain
3932 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003933 keyfile: object = None
3934 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935
3936[clinic start generated code]*/
3937
Antoine Pitroub5218772010-05-21 09:56:06 +00003938static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003939_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3940 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003941/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003942{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003943 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003944 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3945 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003946 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003947 int r;
3948
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003949 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003950 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003951 if (keyfile == Py_None)
3952 keyfile = NULL;
3953 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003954 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3955 PyErr_SetString(PyExc_TypeError,
3956 "certfile should be a valid filesystem path");
3957 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003958 return NULL;
3959 }
3960 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003961 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3962 PyErr_SetString(PyExc_TypeError,
3963 "keyfile should be a valid filesystem path");
3964 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003965 goto error;
3966 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003967 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003968 if (PyCallable_Check(password)) {
3969 pw_info.callable = password;
3970 } else if (!_pwinfo_set(&pw_info, password,
3971 "password should be a string or callable")) {
3972 goto error;
3973 }
3974 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3975 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3976 }
3977 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003978 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3979 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003980 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003981 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003982 if (pw_info.error) {
3983 ERR_clear_error();
3984 /* the password callback has already set the error information */
3985 }
3986 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003987 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003988 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003989 }
3990 else {
3991 _setSSLError(NULL, 0, __FILE__, __LINE__);
3992 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003993 goto error;
3994 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003995 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003996 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3998 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003999 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4000 Py_CLEAR(keyfile_bytes);
4001 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004002 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004003 if (pw_info.error) {
4004 ERR_clear_error();
4005 /* the password callback has already set the error information */
4006 }
4007 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004008 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004009 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004010 }
4011 else {
4012 _setSSLError(NULL, 0, __FILE__, __LINE__);
4013 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004014 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004015 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004016 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004017 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004018 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004019 if (r != 1) {
4020 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004021 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004022 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004023 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4024 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004025 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004026 Py_RETURN_NONE;
4027
4028error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004029 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4030 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004031 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004032 Py_XDECREF(keyfile_bytes);
4033 Py_XDECREF(certfile_bytes);
4034 return NULL;
4035}
4036
Christian Heimesefff7062013-11-21 03:35:02 +01004037/* internal helper function, returns -1 on error
4038 */
4039static int
4040_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
4041 int filetype)
4042{
4043 BIO *biobuf = NULL;
4044 X509_STORE *store;
4045 int retval = 0, err, loaded = 0;
4046
4047 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4048
4049 if (len <= 0) {
4050 PyErr_SetString(PyExc_ValueError,
4051 "Empty certificate data");
4052 return -1;
4053 } else if (len > INT_MAX) {
4054 PyErr_SetString(PyExc_OverflowError,
4055 "Certificate data is too long.");
4056 return -1;
4057 }
4058
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004059 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004060 if (biobuf == NULL) {
4061 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4062 return -1;
4063 }
4064
4065 store = SSL_CTX_get_cert_store(self->ctx);
4066 assert(store != NULL);
4067
4068 while (1) {
4069 X509 *cert = NULL;
4070 int r;
4071
4072 if (filetype == SSL_FILETYPE_ASN1) {
4073 cert = d2i_X509_bio(biobuf, NULL);
4074 } else {
4075 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004076 SSL_CTX_get_default_passwd_cb(self->ctx),
4077 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4078 );
Christian Heimesefff7062013-11-21 03:35:02 +01004079 }
4080 if (cert == NULL) {
4081 break;
4082 }
4083 r = X509_STORE_add_cert(store, cert);
4084 X509_free(cert);
4085 if (!r) {
4086 err = ERR_peek_last_error();
4087 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4088 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4089 /* cert already in hash table, not an error */
4090 ERR_clear_error();
4091 } else {
4092 break;
4093 }
4094 }
4095 loaded++;
4096 }
4097
4098 err = ERR_peek_last_error();
4099 if ((filetype == SSL_FILETYPE_ASN1) &&
4100 (loaded > 0) &&
4101 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4102 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4103 /* EOF ASN1 file, not an error */
4104 ERR_clear_error();
4105 retval = 0;
4106 } else if ((filetype == SSL_FILETYPE_PEM) &&
4107 (loaded > 0) &&
4108 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4109 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4110 /* EOF PEM file, not an error */
4111 ERR_clear_error();
4112 retval = 0;
4113 } else {
4114 _setSSLError(NULL, 0, __FILE__, __LINE__);
4115 retval = -1;
4116 }
4117
4118 BIO_free(biobuf);
4119 return retval;
4120}
4121
4122
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004123/*[clinic input]
4124_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004125 cafile: object = None
4126 capath: object = None
4127 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004128
4129[clinic start generated code]*/
4130
Antoine Pitrou152efa22010-05-16 18:19:27 +00004131static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004132_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4133 PyObject *cafile,
4134 PyObject *capath,
4135 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004136/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004137{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004138 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4139 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004140 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004141
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004142 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004143 if (cafile == Py_None)
4144 cafile = NULL;
4145 if (capath == Py_None)
4146 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004147 if (cadata == Py_None)
4148 cadata = NULL;
4149
4150 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004151 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004152 "cafile, capath and cadata cannot be all omitted");
4153 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004154 }
4155 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004156 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4157 PyErr_SetString(PyExc_TypeError,
4158 "cafile should be a valid filesystem path");
4159 }
Christian Heimesefff7062013-11-21 03:35:02 +01004160 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004161 }
4162 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004163 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4164 PyErr_SetString(PyExc_TypeError,
4165 "capath should be a valid filesystem path");
4166 }
Christian Heimesefff7062013-11-21 03:35:02 +01004167 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004168 }
Christian Heimesefff7062013-11-21 03:35:02 +01004169
4170 /* validata cadata type and load cadata */
4171 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004172 if (PyUnicode_Check(cadata)) {
4173 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4174 if (cadata_ascii == NULL) {
4175 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4176 goto invalid_cadata;
4177 }
4178 goto error;
4179 }
4180 r = _add_ca_certs(self,
4181 PyBytes_AS_STRING(cadata_ascii),
4182 PyBytes_GET_SIZE(cadata_ascii),
4183 SSL_FILETYPE_PEM);
4184 Py_DECREF(cadata_ascii);
4185 if (r == -1) {
4186 goto error;
4187 }
4188 }
4189 else if (PyObject_CheckBuffer(cadata)) {
4190 Py_buffer buf;
4191 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4192 goto error;
4193 }
Christian Heimesefff7062013-11-21 03:35:02 +01004194 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4195 PyBuffer_Release(&buf);
4196 PyErr_SetString(PyExc_TypeError,
4197 "cadata should be a contiguous buffer with "
4198 "a single dimension");
4199 goto error;
4200 }
4201 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4202 PyBuffer_Release(&buf);
4203 if (r == -1) {
4204 goto error;
4205 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004206 }
4207 else {
4208 invalid_cadata:
4209 PyErr_SetString(PyExc_TypeError,
4210 "cadata should be an ASCII string or a "
4211 "bytes-like object");
4212 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004213 }
4214 }
4215
4216 /* load cafile or capath */
4217 if (cafile || capath) {
4218 if (cafile)
4219 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4220 if (capath)
4221 capath_buf = PyBytes_AS_STRING(capath_bytes);
4222 PySSL_BEGIN_ALLOW_THREADS
4223 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4224 PySSL_END_ALLOW_THREADS
4225 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004226 if (errno != 0) {
4227 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004228 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004229 }
4230 else {
4231 _setSSLError(NULL, 0, __FILE__, __LINE__);
4232 }
4233 goto error;
4234 }
4235 }
4236 goto end;
4237
4238 error:
4239 ok = 0;
4240 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004241 Py_XDECREF(cafile_bytes);
4242 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004243 if (ok) {
4244 Py_RETURN_NONE;
4245 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004246 return NULL;
4247 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004248}
4249
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004250/*[clinic input]
4251_ssl._SSLContext.load_dh_params
4252 path as filepath: object
4253 /
4254
4255[clinic start generated code]*/
4256
Antoine Pitrou152efa22010-05-16 18:19:27 +00004257static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004258_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4259/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004260{
4261 FILE *f;
4262 DH *dh;
4263
Victor Stinnerdaf45552013-08-28 00:53:59 +02004264 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004265 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004266 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004267
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004268 errno = 0;
4269 PySSL_BEGIN_ALLOW_THREADS
4270 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004271 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004272 PySSL_END_ALLOW_THREADS
4273 if (dh == NULL) {
4274 if (errno != 0) {
4275 ERR_clear_error();
4276 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4277 }
4278 else {
4279 _setSSLError(NULL, 0, __FILE__, __LINE__);
4280 }
4281 return NULL;
4282 }
4283 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4284 _setSSLError(NULL, 0, __FILE__, __LINE__);
4285 DH_free(dh);
4286 Py_RETURN_NONE;
4287}
4288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004289/*[clinic input]
4290_ssl._SSLContext._wrap_socket
4291 sock: object(subclass_of="PySocketModule.Sock_Type")
4292 server_side: int
4293 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004294 *
4295 owner: object = None
4296 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004297
4298[clinic start generated code]*/
4299
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004300static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004301_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004302 int server_side, PyObject *hostname_obj,
4303 PyObject *owner, PyObject *session)
4304/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004305{
Antoine Pitroud5323212010-10-22 18:19:07 +00004306 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004307 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004308
Antoine Pitroud5323212010-10-22 18:19:07 +00004309 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004310 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004311 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004312 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004313 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004314 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004315
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004316 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4317 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004318 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004319 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004320 if (hostname != NULL)
4321 PyMem_Free(hostname);
4322 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004323}
4324
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004325/*[clinic input]
4326_ssl._SSLContext._wrap_bio
4327 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4328 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4329 server_side: int
4330 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004331 *
4332 owner: object = None
4333 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004334
4335[clinic start generated code]*/
4336
Antoine Pitroub0182c82010-10-12 20:09:02 +00004337static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004338_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4339 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004340 PyObject *hostname_obj, PyObject *owner,
4341 PyObject *session)
4342/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004343{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004344 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004345 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004346
4347 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004348 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004349 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004350 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004351 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004352 }
4353
4354 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004355 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004356 incoming, outgoing);
4357
4358 PyMem_Free(hostname);
4359 return res;
4360}
4361
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004362/*[clinic input]
4363_ssl._SSLContext.session_stats
4364[clinic start generated code]*/
4365
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004366static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004367_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4368/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004369{
4370 int r;
4371 PyObject *value, *stats = PyDict_New();
4372 if (!stats)
4373 return NULL;
4374
4375#define ADD_STATS(SSL_NAME, KEY_NAME) \
4376 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4377 if (value == NULL) \
4378 goto error; \
4379 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4380 Py_DECREF(value); \
4381 if (r < 0) \
4382 goto error;
4383
4384 ADD_STATS(number, "number");
4385 ADD_STATS(connect, "connect");
4386 ADD_STATS(connect_good, "connect_good");
4387 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4388 ADD_STATS(accept, "accept");
4389 ADD_STATS(accept_good, "accept_good");
4390 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4391 ADD_STATS(accept, "accept");
4392 ADD_STATS(hits, "hits");
4393 ADD_STATS(misses, "misses");
4394 ADD_STATS(timeouts, "timeouts");
4395 ADD_STATS(cache_full, "cache_full");
4396
4397#undef ADD_STATS
4398
4399 return stats;
4400
4401error:
4402 Py_DECREF(stats);
4403 return NULL;
4404}
4405
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004406/*[clinic input]
4407_ssl._SSLContext.set_default_verify_paths
4408[clinic start generated code]*/
4409
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004410static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004411_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4412/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004413{
4414 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4415 _setSSLError(NULL, 0, __FILE__, __LINE__);
4416 return NULL;
4417 }
4418 Py_RETURN_NONE;
4419}
4420
Antoine Pitrou501da612011-12-21 09:27:41 +01004421#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004422/*[clinic input]
4423_ssl._SSLContext.set_ecdh_curve
4424 name: object
4425 /
4426
4427[clinic start generated code]*/
4428
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004429static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004430_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4431/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004432{
4433 PyObject *name_bytes;
4434 int nid;
4435 EC_KEY *key;
4436
4437 if (!PyUnicode_FSConverter(name, &name_bytes))
4438 return NULL;
4439 assert(PyBytes_Check(name_bytes));
4440 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4441 Py_DECREF(name_bytes);
4442 if (nid == 0) {
4443 PyErr_Format(PyExc_ValueError,
4444 "unknown elliptic curve name %R", name);
4445 return NULL;
4446 }
4447 key = EC_KEY_new_by_curve_name(nid);
4448 if (key == NULL) {
4449 _setSSLError(NULL, 0, __FILE__, __LINE__);
4450 return NULL;
4451 }
4452 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4453 EC_KEY_free(key);
4454 Py_RETURN_NONE;
4455}
Antoine Pitrou501da612011-12-21 09:27:41 +01004456#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004457
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004458#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004459static int
4460_servername_callback(SSL *s, int *al, void *args)
4461{
4462 int ret;
4463 PySSLContext *ssl_ctx = (PySSLContext *) args;
4464 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004465 PyObject *result;
4466 /* The high-level ssl.SSLSocket object */
4467 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004468 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004469 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004470
Christian Heimes11a14932018-02-24 02:35:08 +01004471 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004472 /* remove race condition in this the call back while if removing the
4473 * callback is in progress */
4474 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004475 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004476 }
4477
4478 ssl = SSL_get_app_data(s);
4479 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004480
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004481 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004482 * SSL connection and that has a .context attribute that can be changed to
4483 * identify the requested hostname. Since the official API is the Python
4484 * level API we want to pass the callback a Python level object rather than
4485 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4486 * SSLObject) that will be passed. Otherwise if there's a socket then that
4487 * will be passed. If both do not exist only then the C-level object is
4488 * passed. */
4489 if (ssl->owner)
4490 ssl_socket = PyWeakref_GetObject(ssl->owner);
4491 else if (ssl->Socket)
4492 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4493 else
4494 ssl_socket = (PyObject *) ssl;
4495
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004496 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004497 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004498 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004499
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004500 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004501 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004502 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004503 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004504 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004505 PyObject *servername_bytes;
4506 PyObject *servername_str;
4507
4508 servername_bytes = PyBytes_FromString(servername);
4509 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004510 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4511 goto error;
4512 }
Christian Heimes11a14932018-02-24 02:35:08 +01004513 /* server_hostname was encoded to an A-label by our caller; put it
4514 * back into a str object, but still as an A-label (bpo-28414)
4515 */
4516 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4517 Py_DECREF(servername_bytes);
4518 if (servername_str == NULL) {
4519 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004520 goto error;
4521 }
Christian Heimes11a14932018-02-24 02:35:08 +01004522 result = PyObject_CallFunctionObjArgs(
4523 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4524 ssl_ctx, NULL);
4525 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004526 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004527 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004528
4529 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004530 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004531 *al = SSL_AD_HANDSHAKE_FAILURE;
4532 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4533 }
4534 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004535 /* Result may be None, a SSLContext or an integer
4536 * None and SSLContext are OK, integer or other values are an error.
4537 */
4538 if (result == Py_None) {
4539 ret = SSL_TLSEXT_ERR_OK;
4540 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004541 *al = (int) PyLong_AsLong(result);
4542 if (PyErr_Occurred()) {
4543 PyErr_WriteUnraisable(result);
4544 *al = SSL_AD_INTERNAL_ERROR;
4545 }
4546 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4547 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004548 Py_DECREF(result);
4549 }
4550
4551 PyGILState_Release(gstate);
4552 return ret;
4553
4554error:
4555 Py_DECREF(ssl_socket);
4556 *al = SSL_AD_INTERNAL_ERROR;
4557 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4558 PyGILState_Release(gstate);
4559 return ret;
4560}
Antoine Pitroua5963382013-03-30 16:39:00 +01004561#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004562
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004563static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004564get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004565{
Christian Heimes11a14932018-02-24 02:35:08 +01004566 PyObject *cb = self->set_sni_cb;
4567 if (cb == NULL) {
4568 Py_RETURN_NONE;
4569 }
4570 Py_INCREF(cb);
4571 return cb;
4572}
4573
4574static int
4575set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4576{
4577 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4578 PyErr_SetString(PyExc_ValueError,
4579 "sni_callback cannot be set on TLS_CLIENT context");
4580 return -1;
4581 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004582#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004583 Py_CLEAR(self->set_sni_cb);
4584 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004585 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4586 }
4587 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004588 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004589 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4590 PyErr_SetString(PyExc_TypeError,
4591 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004592 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004593 }
Christian Heimes11a14932018-02-24 02:35:08 +01004594 Py_INCREF(arg);
4595 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004596 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4597 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4598 }
Christian Heimes11a14932018-02-24 02:35:08 +01004599 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004600#else
4601 PyErr_SetString(PyExc_NotImplementedError,
4602 "The TLS extension servername callback, "
4603 "SSL_CTX_set_tlsext_servername_callback, "
4604 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004605 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004606#endif
4607}
4608
Christian Heimes11a14932018-02-24 02:35:08 +01004609PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4610"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4611\n\
4612If the argument is None then the callback is disabled. The method is called\n\
4613with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4614See RFC 6066 for details of the SNI extension.");
4615
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004616/*[clinic input]
4617_ssl._SSLContext.cert_store_stats
4618
4619Returns quantities of loaded X.509 certificates.
4620
4621X.509 certificates with a CA extension and certificate revocation lists
4622inside the context's cert store.
4623
4624NOTE: Certificates in a capath directory aren't loaded unless they have
4625been used at least once.
4626[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004627
4628static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004629_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4630/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004631{
4632 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004633 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004634 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004635 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004636
4637 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004638 objs = X509_STORE_get0_objects(store);
4639 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4640 obj = sk_X509_OBJECT_value(objs, i);
4641 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004642 case X509_LU_X509:
4643 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004644 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004645 ca++;
4646 }
4647 break;
4648 case X509_LU_CRL:
4649 crl++;
4650 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004651 default:
4652 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4653 * As far as I can tell they are internal states and never
4654 * stored in a cert store */
4655 break;
4656 }
4657 }
4658 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4659 "x509_ca", ca);
4660}
4661
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004662/*[clinic input]
4663_ssl._SSLContext.get_ca_certs
4664 binary_form: bool = False
4665
4666Returns a list of dicts with information of loaded CA certs.
4667
4668If the optional argument is True, returns a DER-encoded copy of the CA
4669certificate.
4670
4671NOTE: Certificates in a capath directory aren't loaded unless they have
4672been used at least once.
4673[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004674
4675static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004676_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4677/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004678{
4679 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004680 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004681 PyObject *ci = NULL, *rlist = NULL;
4682 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683
4684 if ((rlist = PyList_New(0)) == NULL) {
4685 return NULL;
4686 }
4687
4688 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004689 objs = X509_STORE_get0_objects(store);
4690 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004691 X509_OBJECT *obj;
4692 X509 *cert;
4693
Christian Heimes598894f2016-09-05 23:19:05 +02004694 obj = sk_X509_OBJECT_value(objs, i);
4695 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004696 /* not a x509 cert */
4697 continue;
4698 }
4699 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004700 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004701 if (!X509_check_ca(cert)) {
4702 continue;
4703 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004704 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004705 ci = _certificate_to_der(cert);
4706 } else {
4707 ci = _decode_certificate(cert);
4708 }
4709 if (ci == NULL) {
4710 goto error;
4711 }
4712 if (PyList_Append(rlist, ci) == -1) {
4713 goto error;
4714 }
4715 Py_CLEAR(ci);
4716 }
4717 return rlist;
4718
4719 error:
4720 Py_XDECREF(ci);
4721 Py_XDECREF(rlist);
4722 return NULL;
4723}
4724
4725
Antoine Pitrou152efa22010-05-16 18:19:27 +00004726static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004727 {"check_hostname", (getter) get_check_hostname,
4728 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004729 {"_host_flags", (getter) get_host_flags,
4730 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004731#if SSL_CTRL_GET_MAX_PROTO_VERSION
4732 {"minimum_version", (getter) get_minimum_version,
4733 (setter) set_minimum_version, NULL},
4734 {"maximum_version", (getter) get_maximum_version,
4735 (setter) set_maximum_version, NULL},
4736#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004737#ifdef HAVE_OPENSSL_KEYLOG
4738 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4739 (setter) _PySSLContext_set_keylog_filename, NULL},
4740#endif
4741 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4742 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004743 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004744 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004745#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4746 {"num_tickets", (getter) get_num_tickets,
4747 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4748#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004749 {"options", (getter) get_options,
4750 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004751 {"post_handshake_auth", (getter) get_post_handshake_auth,
4752#ifdef TLS1_3_VERSION
4753 (setter) set_post_handshake_auth,
4754#else
4755 NULL,
4756#endif
4757 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004758 {"protocol", (getter) get_protocol,
4759 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004760 {"verify_flags", (getter) get_verify_flags,
4761 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004762 {"verify_mode", (getter) get_verify_mode,
4763 (setter) set_verify_mode, NULL},
4764 {NULL}, /* sentinel */
4765};
4766
4767static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004768 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4769 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4770 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4771 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4772 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4773 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4774 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4775 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4776 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4777 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4778 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004779 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4780 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004781 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004782 {NULL, NULL} /* sentinel */
4783};
4784
4785static PyTypeObject PySSLContext_Type = {
4786 PyVarObject_HEAD_INIT(NULL, 0)
4787 "_ssl._SSLContext", /*tp_name*/
4788 sizeof(PySSLContext), /*tp_basicsize*/
4789 0, /*tp_itemsize*/
4790 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004791 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004792 0, /*tp_getattr*/
4793 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004794 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004795 0, /*tp_repr*/
4796 0, /*tp_as_number*/
4797 0, /*tp_as_sequence*/
4798 0, /*tp_as_mapping*/
4799 0, /*tp_hash*/
4800 0, /*tp_call*/
4801 0, /*tp_str*/
4802 0, /*tp_getattro*/
4803 0, /*tp_setattro*/
4804 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004805 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004806 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004807 (traverseproc) context_traverse, /*tp_traverse*/
4808 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004809 0, /*tp_richcompare*/
4810 0, /*tp_weaklistoffset*/
4811 0, /*tp_iter*/
4812 0, /*tp_iternext*/
4813 context_methods, /*tp_methods*/
4814 0, /*tp_members*/
4815 context_getsetlist, /*tp_getset*/
4816 0, /*tp_base*/
4817 0, /*tp_dict*/
4818 0, /*tp_descr_get*/
4819 0, /*tp_descr_set*/
4820 0, /*tp_dictoffset*/
4821 0, /*tp_init*/
4822 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004823 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004824};
4825
4826
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004827/*
4828 * MemoryBIO objects
4829 */
4830
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004831/*[clinic input]
4832@classmethod
4833_ssl.MemoryBIO.__new__
4834
4835[clinic start generated code]*/
4836
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004837static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004838_ssl_MemoryBIO_impl(PyTypeObject *type)
4839/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004840{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004841 BIO *bio;
4842 PySSLMemoryBIO *self;
4843
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004844 bio = BIO_new(BIO_s_mem());
4845 if (bio == NULL) {
4846 PyErr_SetString(PySSLErrorObject,
4847 "failed to allocate BIO");
4848 return NULL;
4849 }
4850 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4851 * just that no data is currently available. The SSL routines should retry
4852 * the read, which we can achieve by calling BIO_set_retry_read(). */
4853 BIO_set_retry_read(bio);
4854 BIO_set_mem_eof_return(bio, -1);
4855
4856 assert(type != NULL && type->tp_alloc != NULL);
4857 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4858 if (self == NULL) {
4859 BIO_free(bio);
4860 return NULL;
4861 }
4862 self->bio = bio;
4863 self->eof_written = 0;
4864
4865 return (PyObject *) self;
4866}
4867
4868static void
4869memory_bio_dealloc(PySSLMemoryBIO *self)
4870{
4871 BIO_free(self->bio);
4872 Py_TYPE(self)->tp_free(self);
4873}
4874
4875static PyObject *
4876memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4877{
Segev Finer5cff6372017-07-27 01:19:17 +03004878 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004879}
4880
4881PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4882"The number of bytes pending in the memory BIO.");
4883
4884static PyObject *
4885memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4886{
4887 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4888 && self->eof_written);
4889}
4890
4891PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4892"Whether the memory BIO is at EOF.");
4893
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004894/*[clinic input]
4895_ssl.MemoryBIO.read
4896 size as len: int = -1
4897 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004898
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004899Read up to size bytes from the memory BIO.
4900
4901If size is not specified, read the entire buffer.
4902If the return value is an empty bytes instance, this means either
4903EOF or that no data is available. Use the "eof" property to
4904distinguish between the two.
4905[clinic start generated code]*/
4906
4907static PyObject *
4908_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4909/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4910{
4911 int avail, nbytes;
4912 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004913
Segev Finer5cff6372017-07-27 01:19:17 +03004914 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004915 if ((len < 0) || (len > avail))
4916 len = avail;
4917
4918 result = PyBytes_FromStringAndSize(NULL, len);
4919 if ((result == NULL) || (len == 0))
4920 return result;
4921
4922 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004923 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004924 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004925 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004926 return NULL;
4927 }
4928
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004929 /* There should never be any short reads but check anyway. */
4930 if (nbytes < len) {
4931 _PyBytes_Resize(&result, nbytes);
4932 }
4933
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004934 return result;
4935}
4936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004937/*[clinic input]
4938_ssl.MemoryBIO.write
4939 b: Py_buffer
4940 /
4941
4942Writes the bytes b into the memory BIO.
4943
4944Returns the number of bytes written.
4945[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004946
4947static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004948_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4949/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004950{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004951 int nbytes;
4952
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004953 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004954 PyErr_Format(PyExc_OverflowError,
4955 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004956 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004957 }
4958
4959 if (self->eof_written) {
4960 PyErr_SetString(PySSLErrorObject,
4961 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004962 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004963 }
4964
Segev Finer5cff6372017-07-27 01:19:17 +03004965 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004966 if (nbytes < 0) {
4967 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004968 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004969 }
4970
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004972}
4973
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004974/*[clinic input]
4975_ssl.MemoryBIO.write_eof
4976
4977Write an EOF marker to the memory BIO.
4978
4979When all data has been read, the "eof" property will be True.
4980[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004981
4982static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004983_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4984/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004985{
4986 self->eof_written = 1;
4987 /* After an EOF is written, a zero return from read() should be a real EOF
4988 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4989 BIO_clear_retry_flags(self->bio);
4990 BIO_set_mem_eof_return(self->bio, 0);
4991
4992 Py_RETURN_NONE;
4993}
4994
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004995static PyGetSetDef memory_bio_getsetlist[] = {
4996 {"pending", (getter) memory_bio_get_pending, NULL,
4997 PySSL_memory_bio_pending_doc},
4998 {"eof", (getter) memory_bio_get_eof, NULL,
4999 PySSL_memory_bio_eof_doc},
5000 {NULL}, /* sentinel */
5001};
5002
5003static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005004 _SSL_MEMORYBIO_READ_METHODDEF
5005 _SSL_MEMORYBIO_WRITE_METHODDEF
5006 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005007 {NULL, NULL} /* sentinel */
5008};
5009
5010static PyTypeObject PySSLMemoryBIO_Type = {
5011 PyVarObject_HEAD_INIT(NULL, 0)
5012 "_ssl.MemoryBIO", /*tp_name*/
5013 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5014 0, /*tp_itemsize*/
5015 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005016 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005017 0, /*tp_getattr*/
5018 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005019 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005020 0, /*tp_repr*/
5021 0, /*tp_as_number*/
5022 0, /*tp_as_sequence*/
5023 0, /*tp_as_mapping*/
5024 0, /*tp_hash*/
5025 0, /*tp_call*/
5026 0, /*tp_str*/
5027 0, /*tp_getattro*/
5028 0, /*tp_setattro*/
5029 0, /*tp_as_buffer*/
5030 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5031 0, /*tp_doc*/
5032 0, /*tp_traverse*/
5033 0, /*tp_clear*/
5034 0, /*tp_richcompare*/
5035 0, /*tp_weaklistoffset*/
5036 0, /*tp_iter*/
5037 0, /*tp_iternext*/
5038 memory_bio_methods, /*tp_methods*/
5039 0, /*tp_members*/
5040 memory_bio_getsetlist, /*tp_getset*/
5041 0, /*tp_base*/
5042 0, /*tp_dict*/
5043 0, /*tp_descr_get*/
5044 0, /*tp_descr_set*/
5045 0, /*tp_dictoffset*/
5046 0, /*tp_init*/
5047 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005048 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005049};
5050
Antoine Pitrou152efa22010-05-16 18:19:27 +00005051
Christian Heimes99a65702016-09-10 23:44:53 +02005052/*
5053 * SSL Session object
5054 */
5055
5056static void
5057PySSLSession_dealloc(PySSLSession *self)
5058{
INADA Naokia6296d32017-08-24 14:55:17 +09005059 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005060 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005061 Py_XDECREF(self->ctx);
5062 if (self->session != NULL) {
5063 SSL_SESSION_free(self->session);
5064 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005065 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005066}
5067
5068static PyObject *
5069PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5070{
5071 int result;
5072
5073 if (left == NULL || right == NULL) {
5074 PyErr_BadInternalCall();
5075 return NULL;
5076 }
5077
5078 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5079 Py_RETURN_NOTIMPLEMENTED;
5080 }
5081
5082 if (left == right) {
5083 result = 0;
5084 } else {
5085 const unsigned char *left_id, *right_id;
5086 unsigned int left_len, right_len;
5087 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5088 &left_len);
5089 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5090 &right_len);
5091 if (left_len == right_len) {
5092 result = memcmp(left_id, right_id, left_len);
5093 } else {
5094 result = 1;
5095 }
5096 }
5097
5098 switch (op) {
5099 case Py_EQ:
5100 if (result == 0) {
5101 Py_RETURN_TRUE;
5102 } else {
5103 Py_RETURN_FALSE;
5104 }
5105 break;
5106 case Py_NE:
5107 if (result != 0) {
5108 Py_RETURN_TRUE;
5109 } else {
5110 Py_RETURN_FALSE;
5111 }
5112 break;
5113 case Py_LT:
5114 case Py_LE:
5115 case Py_GT:
5116 case Py_GE:
5117 Py_RETURN_NOTIMPLEMENTED;
5118 break;
5119 default:
5120 PyErr_BadArgument();
5121 return NULL;
5122 }
5123}
5124
5125static int
5126PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5127{
5128 Py_VISIT(self->ctx);
5129 return 0;
5130}
5131
5132static int
5133PySSLSession_clear(PySSLSession *self)
5134{
5135 Py_CLEAR(self->ctx);
5136 return 0;
5137}
5138
5139
5140static PyObject *
5141PySSLSession_get_time(PySSLSession *self, void *closure) {
5142 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5143}
5144
5145PyDoc_STRVAR(PySSLSession_get_time_doc,
5146"Session creation time (seconds since epoch).");
5147
5148
5149static PyObject *
5150PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5151 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5152}
5153
5154PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5155"Session timeout (delta in seconds).");
5156
5157
5158static PyObject *
5159PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5160 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5161 return PyLong_FromUnsignedLong(hint);
5162}
5163
5164PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5165"Ticket life time hint.");
5166
5167
5168static PyObject *
5169PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5170 const unsigned char *id;
5171 unsigned int len;
5172 id = SSL_SESSION_get_id(self->session, &len);
5173 return PyBytes_FromStringAndSize((const char *)id, len);
5174}
5175
5176PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5177"Session id");
5178
5179
5180static PyObject *
5181PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5182 if (SSL_SESSION_has_ticket(self->session)) {
5183 Py_RETURN_TRUE;
5184 } else {
5185 Py_RETURN_FALSE;
5186 }
5187}
5188
5189PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5190"Does the session contain a ticket?");
5191
5192
5193static PyGetSetDef PySSLSession_getsetlist[] = {
5194 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5195 PySSLSession_get_has_ticket_doc},
5196 {"id", (getter) PySSLSession_get_session_id, NULL,
5197 PySSLSession_get_session_id_doc},
5198 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5199 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5200 {"time", (getter) PySSLSession_get_time, NULL,
5201 PySSLSession_get_time_doc},
5202 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5203 PySSLSession_get_timeout_doc},
5204 {NULL}, /* sentinel */
5205};
5206
5207static PyTypeObject PySSLSession_Type = {
5208 PyVarObject_HEAD_INIT(NULL, 0)
5209 "_ssl.Session", /*tp_name*/
5210 sizeof(PySSLSession), /*tp_basicsize*/
5211 0, /*tp_itemsize*/
5212 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005213 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005214 0, /*tp_getattr*/
5215 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005216 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005217 0, /*tp_repr*/
5218 0, /*tp_as_number*/
5219 0, /*tp_as_sequence*/
5220 0, /*tp_as_mapping*/
5221 0, /*tp_hash*/
5222 0, /*tp_call*/
5223 0, /*tp_str*/
5224 0, /*tp_getattro*/
5225 0, /*tp_setattro*/
5226 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005227 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005228 0, /*tp_doc*/
5229 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5230 (inquiry)PySSLSession_clear, /*tp_clear*/
5231 PySSLSession_richcompare, /*tp_richcompare*/
5232 0, /*tp_weaklistoffset*/
5233 0, /*tp_iter*/
5234 0, /*tp_iternext*/
5235 0, /*tp_methods*/
5236 0, /*tp_members*/
5237 PySSLSession_getsetlist, /*tp_getset*/
5238};
5239
5240
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005241/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005242/*[clinic input]
5243_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005244 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005245 entropy: double
5246 /
5247
5248Mix string into the OpenSSL PRNG state.
5249
5250entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305251string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005252[clinic start generated code]*/
5253
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005254static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005255_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005256/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005257{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005258 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005259 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005260
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005261 buf = (const char *)view->buf;
5262 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005263 do {
5264 written = Py_MIN(len, INT_MAX);
5265 RAND_add(buf, (int)written, entropy);
5266 buf += written;
5267 len -= written;
5268 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005269 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005270}
5271
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005272static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005273PySSL_RAND(int len, int pseudo)
5274{
5275 int ok;
5276 PyObject *bytes;
5277 unsigned long err;
5278 const char *errstr;
5279 PyObject *v;
5280
Victor Stinner1e81a392013-12-19 16:47:04 +01005281 if (len < 0) {
5282 PyErr_SetString(PyExc_ValueError, "num must be positive");
5283 return NULL;
5284 }
5285
Victor Stinner99c8b162011-05-24 12:05:19 +02005286 bytes = PyBytes_FromStringAndSize(NULL, len);
5287 if (bytes == NULL)
5288 return NULL;
5289 if (pseudo) {
5290 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5291 if (ok == 0 || ok == 1)
5292 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5293 }
5294 else {
5295 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5296 if (ok == 1)
5297 return bytes;
5298 }
5299 Py_DECREF(bytes);
5300
5301 err = ERR_get_error();
5302 errstr = ERR_reason_error_string(err);
5303 v = Py_BuildValue("(ks)", err, errstr);
5304 if (v != NULL) {
5305 PyErr_SetObject(PySSLErrorObject, v);
5306 Py_DECREF(v);
5307 }
5308 return NULL;
5309}
5310
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005311/*[clinic input]
5312_ssl.RAND_bytes
5313 n: int
5314 /
5315
5316Generate n cryptographically strong pseudo-random bytes.
5317[clinic start generated code]*/
5318
Victor Stinner99c8b162011-05-24 12:05:19 +02005319static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005320_ssl_RAND_bytes_impl(PyObject *module, int n)
5321/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005322{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005323 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005324}
5325
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005326/*[clinic input]
5327_ssl.RAND_pseudo_bytes
5328 n: int
5329 /
5330
5331Generate n pseudo-random bytes.
5332
5333Return a pair (bytes, is_cryptographic). is_cryptographic is True
5334if the bytes generated are cryptographically strong.
5335[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005336
5337static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005338_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5339/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005340{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005341 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005342}
5343
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005344/*[clinic input]
5345_ssl.RAND_status
5346
5347Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5348
5349It is necessary to seed the PRNG with RAND_add() on some platforms before
5350using the ssl() function.
5351[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005352
5353static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005354_ssl_RAND_status_impl(PyObject *module)
5355/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005356{
Christian Heimes217cfd12007-12-02 14:31:20 +00005357 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005358}
5359
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005360#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005361/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005362/*[clinic input]
5363_ssl.RAND_egd
5364 path: object(converter="PyUnicode_FSConverter")
5365 /
5366
5367Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5368
5369Returns number of bytes read. Raises SSLError if connection to EGD
5370fails or if it does not provide enough data to seed PRNG.
5371[clinic start generated code]*/
5372
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005373static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005374_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5375/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005376{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005377 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005378 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005379 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005380 PyErr_SetString(PySSLErrorObject,
5381 "EGD connection failed or EGD did not return "
5382 "enough data to seed the PRNG");
5383 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005384 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005385 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005386}
Christian Heimesa5d07652016-09-24 10:48:05 +02005387/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005388#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005389
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005390
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005391
5392/*[clinic input]
5393_ssl.get_default_verify_paths
5394
5395Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5396
5397The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5398[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005399
5400static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005401_ssl_get_default_verify_paths_impl(PyObject *module)
5402/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005403{
5404 PyObject *ofile_env = NULL;
5405 PyObject *ofile = NULL;
5406 PyObject *odir_env = NULL;
5407 PyObject *odir = NULL;
5408
Benjamin Petersond113c962015-07-18 10:59:13 -07005409#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005410 const char *tmp = (info); \
5411 target = NULL; \
5412 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5413 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5414 target = PyBytes_FromString(tmp); } \
5415 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005416 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005417
Benjamin Petersond113c962015-07-18 10:59:13 -07005418 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5419 CONVERT(X509_get_default_cert_file(), ofile);
5420 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5421 CONVERT(X509_get_default_cert_dir(), odir);
5422#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005423
Christian Heimes200bb1b2013-06-14 15:14:29 +02005424 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005425
5426 error:
5427 Py_XDECREF(ofile_env);
5428 Py_XDECREF(ofile);
5429 Py_XDECREF(odir_env);
5430 Py_XDECREF(odir);
5431 return NULL;
5432}
5433
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005434static PyObject*
5435asn1obj2py(ASN1_OBJECT *obj)
5436{
5437 int nid;
5438 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005439
5440 nid = OBJ_obj2nid(obj);
5441 if (nid == NID_undef) {
5442 PyErr_Format(PyExc_ValueError, "Unknown object");
5443 return NULL;
5444 }
5445 sn = OBJ_nid2sn(nid);
5446 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005447 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005448}
5449
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005450/*[clinic input]
5451_ssl.txt2obj
5452 txt: str
5453 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005455Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5456
5457By default objects are looked up by OID. With name=True short and
5458long name are also matched.
5459[clinic start generated code]*/
5460
5461static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005462_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5463/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005464{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005465 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005466 ASN1_OBJECT *obj;
5467
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005468 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5469 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005470 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005471 return NULL;
5472 }
5473 result = asn1obj2py(obj);
5474 ASN1_OBJECT_free(obj);
5475 return result;
5476}
5477
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005478/*[clinic input]
5479_ssl.nid2obj
5480 nid: int
5481 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005483Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5484[clinic start generated code]*/
5485
5486static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005487_ssl_nid2obj_impl(PyObject *module, int nid)
5488/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005489{
5490 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005491 ASN1_OBJECT *obj;
5492
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005493 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005494 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005495 return NULL;
5496 }
5497 obj = OBJ_nid2obj(nid);
5498 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005499 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005500 return NULL;
5501 }
5502 result = asn1obj2py(obj);
5503 ASN1_OBJECT_free(obj);
5504 return result;
5505}
5506
Christian Heimes46bebee2013-06-09 19:03:31 +02005507#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005508
5509static PyObject*
5510certEncodingType(DWORD encodingType)
5511{
5512 static PyObject *x509_asn = NULL;
5513 static PyObject *pkcs_7_asn = NULL;
5514
5515 if (x509_asn == NULL) {
5516 x509_asn = PyUnicode_InternFromString("x509_asn");
5517 if (x509_asn == NULL)
5518 return NULL;
5519 }
5520 if (pkcs_7_asn == NULL) {
5521 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5522 if (pkcs_7_asn == NULL)
5523 return NULL;
5524 }
5525 switch(encodingType) {
5526 case X509_ASN_ENCODING:
5527 Py_INCREF(x509_asn);
5528 return x509_asn;
5529 case PKCS_7_ASN_ENCODING:
5530 Py_INCREF(pkcs_7_asn);
5531 return pkcs_7_asn;
5532 default:
5533 return PyLong_FromLong(encodingType);
5534 }
5535}
5536
5537static PyObject*
5538parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5539{
5540 CERT_ENHKEY_USAGE *usage;
5541 DWORD size, error, i;
5542 PyObject *retval;
5543
5544 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5545 error = GetLastError();
5546 if (error == CRYPT_E_NOT_FOUND) {
5547 Py_RETURN_TRUE;
5548 }
5549 return PyErr_SetFromWindowsErr(error);
5550 }
5551
5552 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5553 if (usage == NULL) {
5554 return PyErr_NoMemory();
5555 }
5556
5557 /* Now get the actual enhanced usage property */
5558 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5559 PyMem_Free(usage);
5560 error = GetLastError();
5561 if (error == CRYPT_E_NOT_FOUND) {
5562 Py_RETURN_TRUE;
5563 }
5564 return PyErr_SetFromWindowsErr(error);
5565 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005566 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005567 if (retval == NULL) {
5568 goto error;
5569 }
5570 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5571 if (usage->rgpszUsageIdentifier[i]) {
5572 PyObject *oid;
5573 int err;
5574 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5575 if (oid == NULL) {
5576 Py_CLEAR(retval);
5577 goto error;
5578 }
5579 err = PySet_Add(retval, oid);
5580 Py_DECREF(oid);
5581 if (err == -1) {
5582 Py_CLEAR(retval);
5583 goto error;
5584 }
5585 }
5586 }
5587 error:
5588 PyMem_Free(usage);
5589 return retval;
5590}
5591
kctherookied93fbbf2019-03-29 00:59:06 +07005592static HCERTSTORE
5593ssl_collect_certificates(const char *store_name)
5594{
5595/* this function collects the system certificate stores listed in
5596 * system_stores into a collection certificate store for being
5597 * enumerated. The store must be readable to be added to the
5598 * store collection.
5599 */
5600
5601 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5602 static DWORD system_stores[] = {
5603 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5604 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5605 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5606 CERT_SYSTEM_STORE_CURRENT_USER,
5607 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5608 CERT_SYSTEM_STORE_SERVICES,
5609 CERT_SYSTEM_STORE_USERS};
5610 size_t i, storesAdded;
5611 BOOL result;
5612
5613 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5614 (HCRYPTPROV)NULL, 0, NULL);
5615 if (!hCollectionStore) {
5616 return NULL;
5617 }
5618 storesAdded = 0;
5619 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5620 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5621 (HCRYPTPROV)NULL,
5622 CERT_STORE_READONLY_FLAG |
5623 system_stores[i], store_name);
5624 if (hSystemStore) {
5625 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5626 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5627 if (result) {
5628 ++storesAdded;
5629 }
neoneneed701292019-09-09 21:33:43 +09005630 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005631 }
5632 }
5633 if (storesAdded == 0) {
5634 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5635 return NULL;
5636 }
5637
5638 return hCollectionStore;
5639}
5640
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005641/*[clinic input]
5642_ssl.enum_certificates
5643 store_name: str
5644
5645Retrieve certificates from Windows' cert store.
5646
5647store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5648more cert storages, too. The function returns a list of (bytes,
5649encoding_type, trust) tuples. The encoding_type flag can be interpreted
5650with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5651a set of OIDs or the boolean True.
5652[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005653
Christian Heimes46bebee2013-06-09 19:03:31 +02005654static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005655_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5656/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005657{
kctherookied93fbbf2019-03-29 00:59:06 +07005658 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005659 PCCERT_CONTEXT pCertCtx = NULL;
5660 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005661 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005662
Christian Heimes915cd3f2019-09-09 18:06:55 +02005663 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005664 if (result == NULL) {
5665 return NULL;
5666 }
kctherookied93fbbf2019-03-29 00:59:06 +07005667 hCollectionStore = ssl_collect_certificates(store_name);
5668 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005669 Py_DECREF(result);
5670 return PyErr_SetFromWindowsErr(GetLastError());
5671 }
5672
kctherookied93fbbf2019-03-29 00:59:06 +07005673 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005674 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5675 pCertCtx->cbCertEncoded);
5676 if (!cert) {
5677 Py_CLEAR(result);
5678 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005679 }
Christian Heimes44109d72013-11-22 01:51:30 +01005680 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5681 Py_CLEAR(result);
5682 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005683 }
Christian Heimes44109d72013-11-22 01:51:30 +01005684 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5685 if (keyusage == Py_True) {
5686 Py_DECREF(keyusage);
5687 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005688 }
Christian Heimes44109d72013-11-22 01:51:30 +01005689 if (keyusage == NULL) {
5690 Py_CLEAR(result);
5691 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005692 }
Christian Heimes44109d72013-11-22 01:51:30 +01005693 if ((tup = PyTuple_New(3)) == NULL) {
5694 Py_CLEAR(result);
5695 break;
5696 }
5697 PyTuple_SET_ITEM(tup, 0, cert);
5698 cert = NULL;
5699 PyTuple_SET_ITEM(tup, 1, enc);
5700 enc = NULL;
5701 PyTuple_SET_ITEM(tup, 2, keyusage);
5702 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005703 if (PySet_Add(result, tup) == -1) {
5704 Py_CLEAR(result);
5705 Py_CLEAR(tup);
5706 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005707 }
5708 Py_CLEAR(tup);
5709 }
5710 if (pCertCtx) {
5711 /* loop ended with an error, need to clean up context manually */
5712 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005713 }
5714
5715 /* In error cases cert, enc and tup may not be NULL */
5716 Py_XDECREF(cert);
5717 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005718 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005719 Py_XDECREF(tup);
5720
kctherookied93fbbf2019-03-29 00:59:06 +07005721 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5722 associated with the store, in this case our collection store and the
5723 associated system stores. */
5724 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005725 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005726 Py_XDECREF(result);
5727 return PyErr_SetFromWindowsErr(GetLastError());
5728 }
kctherookied93fbbf2019-03-29 00:59:06 +07005729
Christian Heimes915cd3f2019-09-09 18:06:55 +02005730 /* convert set to list */
5731 if (result == NULL) {
5732 return NULL;
5733 } else {
5734 PyObject *lst = PySequence_List(result);
5735 Py_DECREF(result);
5736 return lst;
5737 }
Christian Heimes44109d72013-11-22 01:51:30 +01005738}
5739
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005740/*[clinic input]
5741_ssl.enum_crls
5742 store_name: str
5743
5744Retrieve CRLs from Windows' cert store.
5745
5746store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5747more cert storages, too. The function returns a list of (bytes,
5748encoding_type) tuples. The encoding_type flag can be interpreted with
5749X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5750[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005751
5752static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005753_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5754/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005755{
kctherookied93fbbf2019-03-29 00:59:06 +07005756 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005757 PCCRL_CONTEXT pCrlCtx = NULL;
5758 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5759 PyObject *result = NULL;
5760
Christian Heimes915cd3f2019-09-09 18:06:55 +02005761 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005762 if (result == NULL) {
5763 return NULL;
5764 }
kctherookied93fbbf2019-03-29 00:59:06 +07005765 hCollectionStore = ssl_collect_certificates(store_name);
5766 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005767 Py_DECREF(result);
5768 return PyErr_SetFromWindowsErr(GetLastError());
5769 }
Christian Heimes44109d72013-11-22 01:51:30 +01005770
kctherookied93fbbf2019-03-29 00:59:06 +07005771 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005772 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5773 pCrlCtx->cbCrlEncoded);
5774 if (!crl) {
5775 Py_CLEAR(result);
5776 break;
5777 }
5778 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5779 Py_CLEAR(result);
5780 break;
5781 }
5782 if ((tup = PyTuple_New(2)) == NULL) {
5783 Py_CLEAR(result);
5784 break;
5785 }
5786 PyTuple_SET_ITEM(tup, 0, crl);
5787 crl = NULL;
5788 PyTuple_SET_ITEM(tup, 1, enc);
5789 enc = NULL;
5790
Christian Heimes915cd3f2019-09-09 18:06:55 +02005791 if (PySet_Add(result, tup) == -1) {
5792 Py_CLEAR(result);
5793 Py_CLEAR(tup);
5794 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005795 }
5796 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005797 }
Christian Heimes44109d72013-11-22 01:51:30 +01005798 if (pCrlCtx) {
5799 /* loop ended with an error, need to clean up context manually */
5800 CertFreeCRLContext(pCrlCtx);
5801 }
5802
5803 /* In error cases cert, enc and tup may not be NULL */
5804 Py_XDECREF(crl);
5805 Py_XDECREF(enc);
5806 Py_XDECREF(tup);
5807
kctherookied93fbbf2019-03-29 00:59:06 +07005808 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5809 associated with the store, in this case our collection store and the
5810 associated system stores. */
5811 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005812 /* This error case might shadow another exception.*/
5813 Py_XDECREF(result);
5814 return PyErr_SetFromWindowsErr(GetLastError());
5815 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005816 /* convert set to list */
5817 if (result == NULL) {
5818 return NULL;
5819 } else {
5820 PyObject *lst = PySequence_List(result);
5821 Py_DECREF(result);
5822 return lst;
5823 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005824}
Christian Heimes44109d72013-11-22 01:51:30 +01005825
5826#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005827
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005828/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005829static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005830 _SSL__TEST_DECODE_CERT_METHODDEF
5831 _SSL_RAND_ADD_METHODDEF
5832 _SSL_RAND_BYTES_METHODDEF
5833 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5834 _SSL_RAND_EGD_METHODDEF
5835 _SSL_RAND_STATUS_METHODDEF
5836 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5837 _SSL_ENUM_CERTIFICATES_METHODDEF
5838 _SSL_ENUM_CRLS_METHODDEF
5839 _SSL_TXT2OBJ_METHODDEF
5840 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005841 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005842};
5843
5844
Christian Heimes598894f2016-09-05 23:19:05 +02005845#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005846
5847/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005848 * of the Python C thread library
5849 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5850 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005851
5852static PyThread_type_lock *_ssl_locks = NULL;
5853
Christian Heimes4d98ca92013-08-19 17:36:29 +02005854#if OPENSSL_VERSION_NUMBER >= 0x10000000
5855/* use new CRYPTO_THREADID API. */
5856static void
5857_ssl_threadid_callback(CRYPTO_THREADID *id)
5858{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005859 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005860}
5861#else
5862/* deprecated CRYPTO_set_id_callback() API. */
5863static unsigned long
5864_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005865 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005866}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005867#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005868
Bill Janssen6e027db2007-11-15 22:23:56 +00005869static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005870 (int mode, int n, const char *file, int line) {
5871 /* this function is needed to perform locking on shared data
5872 structures. (Note that OpenSSL uses a number of global data
5873 structures that will be implicitly shared whenever multiple
5874 threads use OpenSSL.) Multi-threaded applications will
5875 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005876
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005877 locking_function() must be able to handle up to
5878 CRYPTO_num_locks() different mutex locks. It sets the n-th
5879 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005880
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005881 file and line are the file number of the function setting the
5882 lock. They can be useful for debugging.
5883 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005885 if ((_ssl_locks == NULL) ||
5886 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5887 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005889 if (mode & CRYPTO_LOCK) {
5890 PyThread_acquire_lock(_ssl_locks[n], 1);
5891 } else {
5892 PyThread_release_lock(_ssl_locks[n]);
5893 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005894}
5895
5896static int _setup_ssl_threads(void) {
5897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005898 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005900 if (_ssl_locks == NULL) {
5901 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005902 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5903 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005904 if (_ssl_locks == NULL) {
5905 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005906 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005907 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005908 for (i = 0; i < _ssl_locks_count; i++) {
5909 _ssl_locks[i] = PyThread_allocate_lock();
5910 if (_ssl_locks[i] == NULL) {
5911 unsigned int j;
5912 for (j = 0; j < i; j++) {
5913 PyThread_free_lock(_ssl_locks[j]);
5914 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005915 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005916 return 0;
5917 }
5918 }
5919 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005920#if OPENSSL_VERSION_NUMBER >= 0x10000000
5921 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5922#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005923 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005924#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005925 }
5926 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005927}
5928
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005929#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005930
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005931PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005932"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005933for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005934
Martin v. Löwis1a214512008-06-11 05:26:20 +00005935
5936static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005937 PyModuleDef_HEAD_INIT,
5938 "_ssl",
5939 module_doc,
5940 -1,
5941 PySSL_methods,
5942 NULL,
5943 NULL,
5944 NULL,
5945 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005946};
5947
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005948
5949static void
5950parse_openssl_version(unsigned long libver,
5951 unsigned int *major, unsigned int *minor,
5952 unsigned int *fix, unsigned int *patch,
5953 unsigned int *status)
5954{
5955 *status = libver & 0xF;
5956 libver >>= 4;
5957 *patch = libver & 0xFF;
5958 libver >>= 8;
5959 *fix = libver & 0xFF;
5960 libver >>= 8;
5961 *minor = libver & 0xFF;
5962 libver >>= 8;
5963 *major = libver & 0xFF;
5964}
5965
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005966PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005967PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005968{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005969 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005970 unsigned long libver;
5971 unsigned int major, minor, fix, patch, status;
5972 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005973 struct py_ssl_error_code *errcode;
5974 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005975
Antoine Pitrou152efa22010-05-16 18:19:27 +00005976 if (PyType_Ready(&PySSLContext_Type) < 0)
5977 return NULL;
5978 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005979 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005980 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5981 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005982 if (PyType_Ready(&PySSLSession_Type) < 0)
5983 return NULL;
5984
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005985
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005986 m = PyModule_Create(&_sslmodule);
5987 if (m == NULL)
5988 return NULL;
5989 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005991 /* Load _socket module and its C API */
5992 socket_api = PySocketModule_ImportModuleAndAPI();
5993 if (!socket_api)
5994 return NULL;
5995 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005996
Christian Heimesc941e622017-09-05 15:47:11 +02005997#ifndef OPENSSL_VERSION_1_1
5998 /* Load all algorithms and initialize cpuid */
5999 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006000 /* Init OpenSSL */
6001 SSL_load_error_strings();
6002 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006003#endif
6004
Christian Heimes598894f2016-09-05 23:19:05 +02006005#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006006 /* note that this will start threading if not already started */
6007 if (!_setup_ssl_threads()) {
6008 return NULL;
6009 }
Christian Heimes598894f2016-09-05 23:19:05 +02006010#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
6011 /* OpenSSL 1.1.0 builtin thread support is enabled */
6012 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006013#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006015 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006016 sslerror_type_slots[0].pfunc = PyExc_OSError;
6017 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006018 if (PySSLErrorObject == NULL)
6019 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006020
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006021 /* ssl.CertificateError used to be a subclass of ValueError */
6022 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6023 if (bases == NULL)
6024 return NULL;
6025 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6026 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6027 bases, NULL);
6028 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006029 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6030 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6031 PySSLErrorObject, NULL);
6032 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6033 "ssl.SSLWantReadError", SSLWantReadError_doc,
6034 PySSLErrorObject, NULL);
6035 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6036 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6037 PySSLErrorObject, NULL);
6038 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6039 "ssl.SSLSyscallError", SSLSyscallError_doc,
6040 PySSLErrorObject, NULL);
6041 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6042 "ssl.SSLEOFError", SSLEOFError_doc,
6043 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006044 if (PySSLCertVerificationErrorObject == NULL
6045 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006046 || PySSLWantReadErrorObject == NULL
6047 || PySSLWantWriteErrorObject == NULL
6048 || PySSLSyscallErrorObject == NULL
6049 || PySSLEOFErrorObject == NULL)
6050 return NULL;
6051 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006052 || PyDict_SetItemString(d, "SSLCertVerificationError",
6053 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006054 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6055 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6056 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6057 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6058 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006059 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006060 if (PyDict_SetItemString(d, "_SSLContext",
6061 (PyObject *)&PySSLContext_Type) != 0)
6062 return NULL;
6063 if (PyDict_SetItemString(d, "_SSLSocket",
6064 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006065 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006066 if (PyDict_SetItemString(d, "MemoryBIO",
6067 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6068 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006069 if (PyDict_SetItemString(d, "SSLSession",
6070 (PyObject *)&PySSLSession_Type) != 0)
6071 return NULL;
6072
Christian Heimes892d66e2018-01-29 14:10:18 +01006073 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6074 PY_SSL_DEFAULT_CIPHER_STRING);
6075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006076 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6077 PY_SSL_ERROR_ZERO_RETURN);
6078 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6079 PY_SSL_ERROR_WANT_READ);
6080 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6081 PY_SSL_ERROR_WANT_WRITE);
6082 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6083 PY_SSL_ERROR_WANT_X509_LOOKUP);
6084 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6085 PY_SSL_ERROR_SYSCALL);
6086 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6087 PY_SSL_ERROR_SSL);
6088 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6089 PY_SSL_ERROR_WANT_CONNECT);
6090 /* non ssl.h errorcodes */
6091 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6092 PY_SSL_ERROR_EOF);
6093 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6094 PY_SSL_ERROR_INVALID_ERROR_CODE);
6095 /* cert requirements */
6096 PyModule_AddIntConstant(m, "CERT_NONE",
6097 PY_SSL_CERT_NONE);
6098 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6099 PY_SSL_CERT_OPTIONAL);
6100 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6101 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006102 /* CRL verification for verification_flags */
6103 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6104 0);
6105 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6106 X509_V_FLAG_CRL_CHECK);
6107 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6108 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6109 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6110 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006111#ifdef X509_V_FLAG_TRUSTED_FIRST
6112 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6113 X509_V_FLAG_TRUSTED_FIRST);
6114#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006115
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006116 /* Alert Descriptions from ssl.h */
6117 /* note RESERVED constants no longer intended for use have been removed */
6118 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6119
6120#define ADD_AD_CONSTANT(s) \
6121 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6122 SSL_AD_##s)
6123
6124 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6125 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6126 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6127 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6128 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6129 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6130 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6131 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6132 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6133 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6134 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6135 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6136 ADD_AD_CONSTANT(UNKNOWN_CA);
6137 ADD_AD_CONSTANT(ACCESS_DENIED);
6138 ADD_AD_CONSTANT(DECODE_ERROR);
6139 ADD_AD_CONSTANT(DECRYPT_ERROR);
6140 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6141 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6142 ADD_AD_CONSTANT(INTERNAL_ERROR);
6143 ADD_AD_CONSTANT(USER_CANCELLED);
6144 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006145 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006146#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6147 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6148#endif
6149#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6150 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6151#endif
6152#ifdef SSL_AD_UNRECOGNIZED_NAME
6153 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6154#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006155#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6156 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6157#endif
6158#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6159 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6160#endif
6161#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6162 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6163#endif
6164
6165#undef ADD_AD_CONSTANT
6166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006167 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006168#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006169 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6170 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006171#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006172#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006173 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6174 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006175#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006176 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006177 PY_SSL_VERSION_TLS);
6178 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6179 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006180 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6181 PY_SSL_VERSION_TLS_CLIENT);
6182 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6183 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006184 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6185 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006186#if HAVE_TLSv1_2
6187 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6188 PY_SSL_VERSION_TLS1_1);
6189 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6190 PY_SSL_VERSION_TLS1_2);
6191#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006192
Antoine Pitroub5218772010-05-21 09:56:06 +00006193 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006194 PyModule_AddIntConstant(m, "OP_ALL",
6195 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006196 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6197 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6198 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006199#if HAVE_TLSv1_2
6200 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6201 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6202#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006203#ifdef SSL_OP_NO_TLSv1_3
6204 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6205#else
6206 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6207#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006208 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6209 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006210 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006211 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006212#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006213 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006214#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006215#ifdef SSL_OP_NO_COMPRESSION
6216 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6217 SSL_OP_NO_COMPRESSION);
6218#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006219#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6220 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6221 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6222#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006223#ifdef SSL_OP_NO_RENEGOTIATION
6224 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6225 SSL_OP_NO_RENEGOTIATION);
6226#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006227
Christian Heimes61d478c2018-01-27 15:51:38 +01006228#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6229 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6230 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6231#endif
6232#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6233 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6234 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6235#endif
6236#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6237 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6238 X509_CHECK_FLAG_NO_WILDCARDS);
6239#endif
6240#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6241 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6242 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6243#endif
6244#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6245 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6246 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6247#endif
6248#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6249 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6250 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6251#endif
6252
Christian Heimes698dde12018-02-27 11:54:43 +01006253 /* protocol versions */
6254 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6255 PY_PROTO_MINIMUM_SUPPORTED);
6256 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6257 PY_PROTO_MAXIMUM_SUPPORTED);
6258 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6259 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6260 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6261 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6262 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006263
Victor Stinnerb37672d2018-11-22 03:37:50 +01006264#define addbool(m, key, value) \
6265 do { \
6266 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6267 Py_INCREF(bool_obj); \
6268 PyModule_AddObject((m), (key), bool_obj); \
6269 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006270
6271#if HAVE_SNI
6272 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006273#else
Christian Heimes698dde12018-02-27 11:54:43 +01006274 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006275#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006276
6277 addbool(m, "HAS_TLS_UNIQUE", 1);
6278
6279#ifndef OPENSSL_NO_ECDH
6280 addbool(m, "HAS_ECDH", 1);
6281#else
6282 addbool(m, "HAS_ECDH", 0);
6283#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006284
Christian Heimes29eab552018-02-25 12:31:33 +01006285#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006286 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006287#else
Christian Heimes698dde12018-02-27 11:54:43 +01006288 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006289#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006290
Christian Heimes29eab552018-02-25 12:31:33 +01006291#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006292 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006293#else
Christian Heimes698dde12018-02-27 11:54:43 +01006294 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006295#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006296
6297#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6298 addbool(m, "HAS_SSLv2", 1);
6299#else
6300 addbool(m, "HAS_SSLv2", 0);
6301#endif
6302
6303#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6304 addbool(m, "HAS_SSLv3", 1);
6305#else
6306 addbool(m, "HAS_SSLv3", 0);
6307#endif
6308
6309#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6310 addbool(m, "HAS_TLSv1", 1);
6311#else
6312 addbool(m, "HAS_TLSv1", 0);
6313#endif
6314
6315#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6316 addbool(m, "HAS_TLSv1_1", 1);
6317#else
6318 addbool(m, "HAS_TLSv1_1", 0);
6319#endif
6320
6321#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6322 addbool(m, "HAS_TLSv1_2", 1);
6323#else
6324 addbool(m, "HAS_TLSv1_2", 0);
6325#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006326
Christian Heimescb5b68a2017-09-07 18:07:00 -07006327#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006328 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006329#else
Christian Heimes698dde12018-02-27 11:54:43 +01006330 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006331#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006332
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006333 /* Mappings for error codes */
6334 err_codes_to_names = PyDict_New();
6335 err_names_to_codes = PyDict_New();
6336 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6337 return NULL;
6338 errcode = error_codes;
6339 while (errcode->mnemonic != NULL) {
6340 PyObject *mnemo, *key;
6341 mnemo = PyUnicode_FromString(errcode->mnemonic);
6342 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6343 if (mnemo == NULL || key == NULL)
6344 return NULL;
6345 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6346 return NULL;
6347 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6348 return NULL;
6349 Py_DECREF(key);
6350 Py_DECREF(mnemo);
6351 errcode++;
6352 }
6353 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6354 return NULL;
6355 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6356 return NULL;
6357
6358 lib_codes_to_names = PyDict_New();
6359 if (lib_codes_to_names == NULL)
6360 return NULL;
6361 libcode = library_codes;
6362 while (libcode->library != NULL) {
6363 PyObject *mnemo, *key;
6364 key = PyLong_FromLong(libcode->code);
6365 mnemo = PyUnicode_FromString(libcode->library);
6366 if (key == NULL || mnemo == NULL)
6367 return NULL;
6368 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6369 return NULL;
6370 Py_DECREF(key);
6371 Py_DECREF(mnemo);
6372 libcode++;
6373 }
6374 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6375 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006376
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006377 /* OpenSSL version */
6378 /* SSLeay() gives us the version of the library linked against,
6379 which could be different from the headers version.
6380 */
6381 libver = SSLeay();
6382 r = PyLong_FromUnsignedLong(libver);
6383 if (r == NULL)
6384 return NULL;
6385 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6386 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006387 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006388 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6389 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6390 return NULL;
6391 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6392 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6393 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006394
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006395 libver = OPENSSL_VERSION_NUMBER;
6396 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6397 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6398 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6399 return NULL;
6400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006401 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006402}