blob: d633a06053ae3ba786766bef5bb4b90818436bb3 [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
Steve Dower68d663c2017-07-17 11:15:48 +020021/* Redefined below for Windows debug builds after important #includes */
22#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020027 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000034
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010035/* Include symbols from _socket module */
36#include "socketmodule.h"
37
38static PySocketModule_APIObject PySocketModule;
39
40#if defined(HAVE_POLL_H)
41#include <poll.h>
42#elif defined(HAVE_SYS_POLL_H)
43#include <sys/poll.h>
44#endif
45
Christian Heimes598894f2016-09-05 23:19:05 +020046/* Don't warn about deprecated functions */
47#ifdef __GNUC__
48#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
49#endif
50#ifdef __clang__
51#pragma clang diagnostic ignored "-Wdeprecated-declarations"
52#endif
53
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010054/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesff5be6e2018-01-20 13:19:21 +010066#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010067# ifdef LIBRESSL_VERSION_NUMBER
68# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
69# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010070# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010071# else
72# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010073# endif
74#endif
75
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010076/* SSL error object */
77static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070078static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010079static PyObject *PySSLZeroReturnErrorObject;
80static PyObject *PySSLWantReadErrorObject;
81static PyObject *PySSLWantWriteErrorObject;
82static PyObject *PySSLSyscallErrorObject;
83static PyObject *PySSLEOFErrorObject;
84
85/* Error mappings */
86static PyObject *err_codes_to_names;
87static PyObject *err_names_to_codes;
88static PyObject *lib_codes_to_names;
89
90struct py_ssl_error_code {
91 const char *mnemonic;
92 int library, reason;
93};
94struct py_ssl_library_code {
95 const char *library;
96 int code;
97};
98
Steve Dower68d663c2017-07-17 11:15:48 +020099#if defined(MS_WINDOWS) && defined(Py_DEBUG)
100/* Debug builds on Windows rely on getting errno directly from OpenSSL.
101 * However, because it uses a different CRT, we need to transfer the
102 * value of errno from OpenSSL into our debug CRT.
103 *
104 * Don't be fooled - this is horribly ugly code. The only reasonable
105 * alternative is to do both debug and release builds of OpenSSL, which
106 * requires much uglier code to transform their automatically generated
107 * makefile. This is the lesser of all the evils.
108 */
109
110static void _PySSLFixErrno(void) {
111 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
112 if (!ucrtbase) {
113 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
114 * have a catastrophic failure, but this function is not the
115 * place to raise it. */
116 return;
117 }
118
119 typedef int *(__stdcall *errno_func)(void);
120 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
121 if (ssl_errno) {
122 errno = *ssl_errno();
123 *ssl_errno() = 0;
124 } else {
125 errno = ENOTRECOVERABLE;
126 }
127}
128
129#undef _PySSL_FIX_ERRNO
130#define _PySSL_FIX_ERRNO _PySSLFixErrno()
131#endif
132
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100133/* Include generated data (error codes) */
134#include "_ssl_data.h"
135
Christian Heimes598894f2016-09-05 23:19:05 +0200136#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
137# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100138# define PY_OPENSSL_1_1_API 1
139#endif
140
141/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
142#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
143# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200144#endif
145
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100146/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
147 http://www.openssl.org/news/changelog.html
148 */
149#if OPENSSL_VERSION_NUMBER >= 0x10001000L
150# define HAVE_TLSv1_2 1
151#else
152# define HAVE_TLSv1_2 0
153#endif
154
Christian Heimes470fba12013-11-28 15:12:15 +0100155/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100156 * This includes the SSL_set_SSL_CTX() function.
157 */
158#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
159# define HAVE_SNI 1
160#else
161# define HAVE_SNI 0
162#endif
163
Benjamin Petersond3308222015-09-27 00:09:02 -0700164#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100165# define HAVE_ALPN 1
166#else
167# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500168#endif
169
Christian Heimes6cdb7952018-02-24 22:12:40 +0100170/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
171 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
172 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
173 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100174 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100175 */
176#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100177# define HAVE_NPN 0
178#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
179# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100180#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100181# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100182#else
Christian Heimes29eab552018-02-25 12:31:33 +0100183# define HAVE_NPN 0
184#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100185
Christian Heimesc7f70692019-05-31 11:44:05 +0200186#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
187#define HAVE_OPENSSL_KEYLOG 1
188#endif
189
Victor Stinner524714e2016-07-22 17:43:59 +0200190#ifndef INVALID_SOCKET /* MS defines this */
191#define INVALID_SOCKET (-1)
192#endif
193
Christian Heimes4ca07392018-03-24 15:41:37 +0100194/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
195#ifndef OPENSSL_VERSION_1_1
196#define HAVE_OPENSSL_CRYPTO_LOCK
197#endif
198
199#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200200#define OPENSSL_NO_SSL2
201#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100202
203#ifndef PY_OPENSSL_1_1_API
204/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200205
206#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200207#define TLS_client_method SSLv23_client_method
208#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200209
210static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
211{
212 return ne->set;
213}
214
215#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200216/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200217static int COMP_get_type(const COMP_METHOD *meth)
218{
219 return meth->type;
220}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200221/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200222#endif
223
224static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
225{
226 return ctx->default_passwd_callback;
227}
228
229static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
230{
231 return ctx->default_passwd_callback_userdata;
232}
233
234static int X509_OBJECT_get_type(X509_OBJECT *x)
235{
236 return x->type;
237}
238
239static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
240{
241 return x->data.x509;
242}
243
244static int BIO_up_ref(BIO *b)
245{
246 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
247 return 1;
248}
249
250static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
251 return store->objs;
252}
253
Christian Heimes99a65702016-09-10 23:44:53 +0200254static int
255SSL_SESSION_has_ticket(const SSL_SESSION *s)
256{
257 return (s->tlsext_ticklen > 0) ? 1 : 0;
258}
259
260static unsigned long
261SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
262{
263 return s->tlsext_tick_lifetime_hint;
264}
265
Christian Heimes4ca07392018-03-24 15:41:37 +0100266#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200267
Christian Heimes892d66e2018-01-29 14:10:18 +0100268/* Default cipher suites */
269#ifndef PY_SSL_DEFAULT_CIPHERS
270#define PY_SSL_DEFAULT_CIPHERS 1
271#endif
272
273#if PY_SSL_DEFAULT_CIPHERS == 0
274 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
275 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
276 #endif
277#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200278/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100279 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
280 * !aNULL:!eNULL: really no NULL ciphers
281 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
282 * !aDSS: no authentication with discrete logarithm DSA algorithm
283 * !SRP:!PSK: no secure remote password or pre-shared key authentication
284 */
285 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
286#elif PY_SSL_DEFAULT_CIPHERS == 2
287/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
288 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
289#else
290 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
291#endif
292
Christian Heimes598894f2016-09-05 23:19:05 +0200293
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000294enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000295 /* these mirror ssl.h */
296 PY_SSL_ERROR_NONE,
297 PY_SSL_ERROR_SSL,
298 PY_SSL_ERROR_WANT_READ,
299 PY_SSL_ERROR_WANT_WRITE,
300 PY_SSL_ERROR_WANT_X509_LOOKUP,
301 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
302 PY_SSL_ERROR_ZERO_RETURN,
303 PY_SSL_ERROR_WANT_CONNECT,
304 /* start of non ssl.h errorcodes */
305 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
306 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
307 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000308};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000309
Thomas Woutersed03b412007-08-28 21:37:11 +0000310enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000311 PY_SSL_CLIENT,
312 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000313};
314
315enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 PY_SSL_CERT_NONE,
317 PY_SSL_CERT_OPTIONAL,
318 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000319};
320
321enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200323 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200324 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100325#if HAVE_TLSv1_2
326 PY_SSL_VERSION_TLS1,
327 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200328 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100329#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000331#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200332 PY_SSL_VERSION_TLS_CLIENT=0x10,
333 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100334};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200335
Christian Heimes698dde12018-02-27 11:54:43 +0100336enum py_proto_version {
337 PY_PROTO_MINIMUM_SUPPORTED = -2,
338 PY_PROTO_SSLv3 = SSL3_VERSION,
339 PY_PROTO_TLSv1 = TLS1_VERSION,
340 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
341 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
342#ifdef TLS1_3_VERSION
343 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
344#else
345 PY_PROTO_TLSv1_3 = 0x304,
346#endif
347 PY_PROTO_MAXIMUM_SUPPORTED = -1,
348
349/* OpenSSL has no dedicated API to set the minimum version to the maximum
350 * available version, and the other way around. We have to figure out the
351 * minimum and maximum available version on our own and hope for the best.
352 */
353#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
354 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
355#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
357#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
359#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
361#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
362 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
363#else
364 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
365#endif
366
367#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
368 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
369#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
371#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
373#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
375#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
376 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
377#else
378 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
379#endif
380};
381
382
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000383/* serves as a flag to see whether we've initialized the SSL thread support. */
384/* 0 means no, greater than 0 means yes */
385
386static unsigned int _ssl_locks_count = 0;
387
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388/* SSL socket object */
389
390#define X509_NAME_MAXLEN 256
391
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000392/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
393 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
394 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
395#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000396# define HAVE_SSL_CTX_CLEAR_OPTIONS
397#else
398# undef HAVE_SSL_CTX_CLEAR_OPTIONS
399#endif
400
Antoine Pitroud6494802011-07-21 01:11:30 +0200401/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
402 * older SSL, but let's be safe */
403#define PySSL_CB_MAXLEN 128
404
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100405
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000406typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000407 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000408 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100409#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500410 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100411 int npn_protocols_len;
412#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100413#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500414 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300415 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500416#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100417#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100418 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100419#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100420 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100421 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
422 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
423 */
424 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100425 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200426#ifdef TLS1_3_VERSION
427 int post_handshake_auth;
428#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200429 PyObject *msg_cb;
430#ifdef HAVE_OPENSSL_KEYLOG
431 PyObject *keylog_filename;
432 BIO *keylog_bio;
433#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000434} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000435
Antoine Pitrou152efa22010-05-16 18:19:27 +0000436typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700437 int ssl; /* last seen error from SSL */
438 int c; /* last seen error from libc */
439#ifdef MS_WINDOWS
440 int ws; /* last seen error from winsock */
441#endif
442} _PySSLError;
443
444typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000445 PyObject_HEAD
446 PyObject *Socket; /* weakref to socket on which we're layered */
447 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100448 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200449 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200450 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200451 PyObject *owner; /* Python level "owner" passed to servername callback */
452 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700453 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200454 /* Some SSL callbacks don't have error reporting. Callback wrappers
455 * store exception information on the socket. The handshake, read, write,
456 * and shutdown methods check for chained exceptions.
457 */
458 PyObject *exc_type;
459 PyObject *exc_value;
460 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000461} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000462
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200463typedef struct {
464 PyObject_HEAD
465 BIO *bio;
466 int eof_written;
467} PySSLMemoryBIO;
468
Christian Heimes99a65702016-09-10 23:44:53 +0200469typedef struct {
470 PyObject_HEAD
471 SSL_SESSION *session;
472 PySSLContext *ctx;
473} PySSLSession;
474
Antoine Pitrou152efa22010-05-16 18:19:27 +0000475static PyTypeObject PySSLContext_Type;
476static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200477static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200478static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700480static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
481{
482 _PySSLError err = { 0 };
483 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700484#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700485 err.ws = WSAGetLastError();
486 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700487#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700488 err.c = errno;
489 err.ssl = SSL_get_error(ssl, retcode);
490 }
491 return err;
492}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300494/*[clinic input]
495module _ssl
496class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
497class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
498class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200499class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300500[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200501/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300502
503#include "clinic/_ssl.c.h"
504
Victor Stinner14690702015-04-06 22:46:13 +0200505static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000506
Christian Heimes141c5e82018-02-24 21:10:57 +0100507static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
508static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Dong-hee Na1b55b652020-02-17 19:09:15 +0900509#define PySSLSocket_Check(v) Py_IS_TYPE(v, &PySSLSocket_Type)
510#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, &PySSLMemoryBIO_Type)
511#define PySSLSession_Check(v) Py_IS_TYPE(v, &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000512
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000513typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 SOCKET_IS_NONBLOCKING,
515 SOCKET_IS_BLOCKING,
516 SOCKET_HAS_TIMED_OUT,
517 SOCKET_HAS_BEEN_CLOSED,
518 SOCKET_TOO_LARGE_FOR_SELECT,
519 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000520} timeout_state;
521
Thomas Woutersed03b412007-08-28 21:37:11 +0000522/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000523#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200524#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000525
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200526/* Get the socket from a PySSLSocket, if it has one */
527#define GET_SOCKET(obj) ((obj)->Socket ? \
528 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200529
Victor Stinner14690702015-04-06 22:46:13 +0200530/* If sock is NULL, use a timeout of 0 second */
531#define GET_SOCKET_TIMEOUT(sock) \
532 ((sock != NULL) ? (sock)->sock_timeout : 0)
533
Christian Heimesc7f70692019-05-31 11:44:05 +0200534#include "_ssl/debughelpers.c"
535
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200536/*
537 * SSL errors.
538 */
539
540PyDoc_STRVAR(SSLError_doc,
541"An error occurred in the SSL implementation.");
542
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700543PyDoc_STRVAR(SSLCertVerificationError_doc,
544"A certificate could not be verified.");
545
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200546PyDoc_STRVAR(SSLZeroReturnError_doc,
547"SSL/TLS session closed cleanly.");
548
549PyDoc_STRVAR(SSLWantReadError_doc,
550"Non-blocking SSL socket needs to read more data\n"
551"before the requested operation can be completed.");
552
553PyDoc_STRVAR(SSLWantWriteError_doc,
554"Non-blocking SSL socket needs to write more data\n"
555"before the requested operation can be completed.");
556
557PyDoc_STRVAR(SSLSyscallError_doc,
558"System error when attempting SSL operation.");
559
560PyDoc_STRVAR(SSLEOFError_doc,
561"SSL/TLS connection terminated abruptly.");
562
563static PyObject *
564SSLError_str(PyOSErrorObject *self)
565{
566 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
567 Py_INCREF(self->strerror);
568 return self->strerror;
569 }
570 else
571 return PyObject_Str(self->args);
572}
573
574static PyType_Slot sslerror_type_slots[] = {
575 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900576 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577 {Py_tp_str, SSLError_str},
578 {0, 0},
579};
580
581static PyType_Spec sslerror_type_spec = {
582 "ssl.SSLError",
583 sizeof(PyOSErrorObject),
584 0,
585 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
586 sslerror_type_slots
587};
588
589static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700590fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
591 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200592{
593 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700594 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200595 PyObject *init_value, *msg, *key;
596 _Py_IDENTIFIER(reason);
597 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700598 _Py_IDENTIFIER(verify_message);
599 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200600
601 if (errcode != 0) {
602 int lib, reason;
603
604 lib = ERR_GET_LIB(errcode);
605 reason = ERR_GET_REASON(errcode);
606 key = Py_BuildValue("ii", lib, reason);
607 if (key == NULL)
608 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300609 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200610 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300611 if (reason_obj == NULL && PyErr_Occurred()) {
612 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200613 }
614 key = PyLong_FromLong(lib);
615 if (key == NULL)
616 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300617 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200618 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300619 if (lib_obj == NULL && PyErr_Occurred()) {
620 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200621 }
622 if (errstr == NULL)
623 errstr = ERR_reason_error_string(errcode);
624 }
625 if (errstr == NULL)
626 errstr = "unknown error";
627
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700628 /* verify code for cert validation error */
629 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
630 const char *verify_str = NULL;
631 long verify_code;
632
633 verify_code = SSL_get_verify_result(sslsock->ssl);
634 verify_code_obj = PyLong_FromLong(verify_code);
635 if (verify_code_obj == NULL) {
636 goto fail;
637 }
638
639 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700640#ifdef X509_V_ERR_HOSTNAME_MISMATCH
641 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700642 case X509_V_ERR_HOSTNAME_MISMATCH:
643 verify_obj = PyUnicode_FromFormat(
644 "Hostname mismatch, certificate is not valid for '%S'.",
645 sslsock->server_hostname
646 );
647 break;
Christian Heimes09153602017-09-08 14:47:58 -0700648#endif
649#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700650 case X509_V_ERR_IP_ADDRESS_MISMATCH:
651 verify_obj = PyUnicode_FromFormat(
652 "IP address mismatch, certificate is not valid for '%S'.",
653 sslsock->server_hostname
654 );
655 break;
Christian Heimes09153602017-09-08 14:47:58 -0700656#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700657 default:
658 verify_str = X509_verify_cert_error_string(verify_code);
659 if (verify_str != NULL) {
660 verify_obj = PyUnicode_FromString(verify_str);
661 } else {
662 verify_obj = Py_None;
663 Py_INCREF(verify_obj);
664 }
665 break;
666 }
667 if (verify_obj == NULL) {
668 goto fail;
669 }
670 }
671
672 if (verify_obj && reason_obj && lib_obj)
673 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
674 lib_obj, reason_obj, errstr, verify_obj,
675 lineno);
676 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200677 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
678 lib_obj, reason_obj, errstr, lineno);
679 else if (lib_obj)
680 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
681 lib_obj, errstr, lineno);
682 else
683 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200684 if (msg == NULL)
685 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100686
Paul Monsonfb7e7502019-05-15 15:38:55 -0700687 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100688 if (init_value == NULL)
689 goto fail;
690
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200691 err_value = PyObject_CallObject(type, init_value);
692 Py_DECREF(init_value);
693 if (err_value == NULL)
694 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100695
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200696 if (reason_obj == NULL)
697 reason_obj = Py_None;
698 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
699 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700700
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200701 if (lib_obj == NULL)
702 lib_obj = Py_None;
703 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
704 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700705
706 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
707 /* Only set verify code / message for SSLCertVerificationError */
708 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
709 verify_code_obj))
710 goto fail;
711 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
712 goto fail;
713 }
714
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200715 PyErr_SetObject(type, err_value);
716fail:
717 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700718 Py_XDECREF(verify_code_obj);
719 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200720}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000721
Christian Heimesc7f70692019-05-31 11:44:05 +0200722static int
723PySSL_ChainExceptions(PySSLSocket *sslsock) {
724 if (sslsock->exc_type == NULL)
725 return 0;
726
727 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
728 sslsock->exc_type = NULL;
729 sslsock->exc_value = NULL;
730 sslsock->exc_tb = NULL;
731 return -1;
732}
733
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000734static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700735PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200737 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200738 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700739 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200741 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000742
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200744 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000745
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700746 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700747 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000748
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700749 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000750 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200751 errstr = "TLS/SSL connection has been closed (EOF)";
752 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000753 p = PY_SSL_ERROR_ZERO_RETURN;
754 break;
755 case SSL_ERROR_WANT_READ:
756 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200757 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 p = PY_SSL_ERROR_WANT_READ;
759 break;
760 case SSL_ERROR_WANT_WRITE:
761 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200762 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000763 errstr = "The operation did not complete (write)";
764 break;
765 case SSL_ERROR_WANT_X509_LOOKUP:
766 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000767 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 break;
769 case SSL_ERROR_WANT_CONNECT:
770 p = PY_SSL_ERROR_WANT_CONNECT;
771 errstr = "The operation did not complete (connect)";
772 break;
773 case SSL_ERROR_SYSCALL:
774 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000775 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700776 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000778 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200779 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000780 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200781 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000783 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700784#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700785 if (err.ws) {
786 return PyErr_SetFromWindowsErr(err.ws);
787 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700788#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700789 if (err.c) {
790 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700791 return PyErr_SetFromErrno(PyExc_OSError);
792 }
793 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200794 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000795 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200796 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000798 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200799 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000800 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 }
802 } else {
803 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 }
805 break;
806 }
807 case SSL_ERROR_SSL:
808 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700810 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200811 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000812 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700813 }
814 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
815 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
816 type = PySSLCertVerificationErrorObject;
817 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000818 break;
819 }
820 default:
821 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
822 errstr = "Invalid error code";
823 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700825 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000826 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200827 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000829}
830
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200832_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200834 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200836 else
837 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700838 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000839 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000841}
842
Christian Heimes61d478c2018-01-27 15:51:38 +0100843/*
844 * SSL objects
845 */
846
847static int
848_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
849{
850 int retval = -1;
851 ASN1_OCTET_STRING *ip;
852 PyObject *hostname;
853 size_t len;
854
855 assert(server_hostname);
856
857 /* Disable OpenSSL's special mode with leading dot in hostname:
858 * When name starts with a dot (e.g ".example.com"), it will be
859 * matched by a certificate valid for any sub-domain of name.
860 */
861 len = strlen(server_hostname);
862 if (len == 0 || *server_hostname == '.') {
863 PyErr_SetString(
864 PyExc_ValueError,
865 "server_hostname cannot be an empty string or start with a "
866 "leading dot.");
867 return retval;
868 }
869
870 /* inet_pton is not available on all platforms. */
871 ip = a2i_IPADDRESS(server_hostname);
872 if (ip == NULL) {
873 ERR_clear_error();
874 }
875
Christian Heimes11a14932018-02-24 02:35:08 +0100876 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100877 if (hostname == NULL) {
878 goto error;
879 }
880 self->server_hostname = hostname;
881
882 /* Only send SNI extension for non-IP hostnames */
883 if (ip == NULL) {
884 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
885 _setSSLError(NULL, 0, __FILE__, __LINE__);
886 }
887 }
888 if (self->ctx->check_hostname) {
889 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
890 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200891 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
892 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100893 _setSSLError(NULL, 0, __FILE__, __LINE__);
894 goto error;
895 }
896 } else {
897 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
898 ASN1_STRING_length(ip))) {
899 _setSSLError(NULL, 0, __FILE__, __LINE__);
900 goto error;
901 }
902 }
903 }
904 retval = 0;
905 error:
906 if (ip != NULL) {
907 ASN1_OCTET_STRING_free(ip);
908 }
909 return retval;
910}
911
Antoine Pitrou152efa22010-05-16 18:19:27 +0000912static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100913newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000914 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200915 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100916 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200917 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000918{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000919 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100920 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700921 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000922
Antoine Pitrou152efa22010-05-16 18:19:27 +0000923 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 if (self == NULL)
925 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100929 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700930 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200931 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200932 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700933 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700934 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200935 self->exc_type = NULL;
936 self->exc_value = NULL;
937 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000943 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700945 if (self->ssl == NULL) {
946 Py_DECREF(self);
947 _setSSLError(NULL, 0, __FILE__, __LINE__);
948 return NULL;
949 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200950 SSL_set_app_data(self->ssl, self);
951 if (sock) {
952 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
953 } else {
954 /* BIOs are reference counted and SSL_set_bio borrows our reference.
955 * To prevent a double free in memory_bio_dealloc() we need to take an
956 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200957 BIO_up_ref(inbio->bio);
958 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200959 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
960 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400961 SSL_set_mode(self->ssl,
962 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000963
Christian Heimesf0f59302019-07-01 08:29:17 +0200964#ifdef TLS1_3_VERSION
965 if (sslctx->post_handshake_auth == 1) {
966 if (socket_type == PY_SSL_SERVER) {
967 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
968 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
969 * only in combination with SSL_VERIFY_PEER flag. */
970 int mode = SSL_get_verify_mode(self->ssl);
971 if (mode & SSL_VERIFY_PEER) {
972 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
973 verify_cb = SSL_get_verify_callback(self->ssl);
974 mode |= SSL_VERIFY_POST_HANDSHAKE;
975 SSL_set_verify(self->ssl, mode, verify_cb);
976 }
977 } else {
978 /* client socket */
979 SSL_set_post_handshake_auth(self->ssl, 1);
980 }
981 }
982#endif
983
Christian Heimes61d478c2018-01-27 15:51:38 +0100984 if (server_hostname != NULL) {
985 if (_ssl_configure_hostname(self, server_hostname) < 0) {
986 Py_DECREF(self);
987 return NULL;
988 }
989 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 /* If the socket is in non-blocking mode or timeout mode, set the BIO
991 * to non-blocking mode (blocking is the default)
992 */
Victor Stinnere2452312015-03-28 03:00:46 +0100993 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
995 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
996 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 PySSL_BEGIN_ALLOW_THREADS
999 if (socket_type == PY_SSL_CLIENT)
1000 SSL_set_connect_state(self->ssl);
1001 else
1002 SSL_set_accept_state(self->ssl);
1003 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001004
Antoine Pitroud6494802011-07-21 01:11:30 +02001005 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001006 if (sock != NULL) {
1007 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1008 if (self->Socket == NULL) {
1009 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001010 return NULL;
1011 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001012 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001013 if (owner && owner != Py_None) {
1014 if (PySSL_set_owner(self, owner, NULL) == -1) {
1015 Py_DECREF(self);
1016 return NULL;
1017 }
1018 }
1019 if (session && session != Py_None) {
1020 if (PySSL_set_session(self, session, NULL) == -1) {
1021 Py_DECREF(self);
1022 return NULL;
1023 }
1024 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001026}
1027
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001028/* SSL object methods */
1029
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001030/*[clinic input]
1031_ssl._SSLSocket.do_handshake
1032[clinic start generated code]*/
1033
1034static PyObject *
1035_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1036/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001037{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001039 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001041 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001042 _PyTime_t timeout, deadline = 0;
1043 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001044
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001045 if (sock) {
1046 if (((PyObject*)sock) == Py_None) {
1047 _setSSLError("Underlying socket connection gone",
1048 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1049 return NULL;
1050 }
1051 Py_INCREF(sock);
1052
1053 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001054 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001055 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1056 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001058
Victor Stinner14690702015-04-06 22:46:13 +02001059 timeout = GET_SOCKET_TIMEOUT(sock);
1060 has_timeout = (timeout > 0);
1061 if (has_timeout)
1062 deadline = _PyTime_GetMonotonicClock() + timeout;
1063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 /* Actually negotiate SSL connection */
1065 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001067 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001069 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001071 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001072
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001073 if (PyErr_CheckSignals())
1074 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001075
Victor Stinner14690702015-04-06 22:46:13 +02001076 if (has_timeout)
1077 timeout = deadline - _PyTime_GetMonotonicClock();
1078
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001079 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001080 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001081 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001082 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 } else {
1084 sockstate = SOCKET_OPERATION_OK;
1085 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001088 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001089 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001090 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1092 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001093 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001094 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1096 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001097 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001098 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1100 break;
1101 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001102 } while (err.ssl == SSL_ERROR_WANT_READ ||
1103 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001104 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 if (ret < 1)
1106 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001107 if (PySSL_ChainExceptions(self) < 0)
1108 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001109 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001110error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001111 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001112 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001113 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001114}
1115
Thomas Woutersed03b412007-08-28 21:37:11 +00001116static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001117_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1118{
1119 char buf[X509_NAME_MAXLEN];
1120 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001122 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001123
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001124 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 if (buflen < 0) {
1126 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001127 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001128 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001129 /* initial buffer is too small for oid + terminating null byte */
1130 if (buflen > X509_NAME_MAXLEN - 1) {
1131 /* make OBJ_obj2txt() calculate the required buflen */
1132 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1133 /* allocate len + 1 for terminating NULL byte */
1134 namebuf = PyMem_Malloc(buflen + 1);
1135 if (namebuf == NULL) {
1136 PyErr_NoMemory();
1137 return NULL;
1138 }
1139 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1140 if (buflen < 0) {
1141 _setSSLError(NULL, 0, __FILE__, __LINE__);
1142 goto done;
1143 }
1144 }
1145 if (!buflen && no_name) {
1146 Py_INCREF(Py_None);
1147 name_obj = Py_None;
1148 }
1149 else {
1150 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1151 }
1152
1153 done:
1154 if (buf != namebuf) {
1155 PyMem_Free(namebuf);
1156 }
1157 return name_obj;
1158}
1159
1160static PyObject *
1161_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1162{
1163 Py_ssize_t buflen;
1164 unsigned char *valuebuf = NULL;
1165 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1168 if (buflen < 0) {
1169 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001170 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001172 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001175}
1176
1177static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001179{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1181 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1182 PyObject *rdnt;
1183 PyObject *attr = NULL; /* tuple to hold an attribute */
1184 int entry_count = X509_NAME_entry_count(xname);
1185 X509_NAME_ENTRY *entry;
1186 ASN1_OBJECT *name;
1187 ASN1_STRING *value;
1188 int index_counter;
1189 int rdn_level = -1;
1190 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 dn = PyList_New(0);
1193 if (dn == NULL)
1194 return NULL;
1195 /* now create another tuple to hold the top-level RDN */
1196 rdn = PyList_New(0);
1197 if (rdn == NULL)
1198 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 for (index_counter = 0;
1201 index_counter < entry_count;
1202 index_counter++)
1203 {
1204 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 /* check to see if we've gotten to a new RDN */
1207 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001208 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 /* yes, new RDN */
1210 /* add old RDN to DN */
1211 rdnt = PyList_AsTuple(rdn);
1212 Py_DECREF(rdn);
1213 if (rdnt == NULL)
1214 goto fail0;
1215 retcode = PyList_Append(dn, rdnt);
1216 Py_DECREF(rdnt);
1217 if (retcode < 0)
1218 goto fail0;
1219 /* create new RDN */
1220 rdn = PyList_New(0);
1221 if (rdn == NULL)
1222 goto fail0;
1223 }
1224 }
Christian Heimes598894f2016-09-05 23:19:05 +02001225 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 /* now add this attribute to the current RDN */
1228 name = X509_NAME_ENTRY_get_object(entry);
1229 value = X509_NAME_ENTRY_get_data(entry);
1230 attr = _create_tuple_for_attribute(name, value);
1231 /*
1232 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1233 entry->set,
1234 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1235 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1236 */
1237 if (attr == NULL)
1238 goto fail1;
1239 retcode = PyList_Append(rdn, attr);
1240 Py_DECREF(attr);
1241 if (retcode < 0)
1242 goto fail1;
1243 }
1244 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001245 if (rdn != NULL) {
1246 if (PyList_GET_SIZE(rdn) > 0) {
1247 rdnt = PyList_AsTuple(rdn);
1248 Py_DECREF(rdn);
1249 if (rdnt == NULL)
1250 goto fail0;
1251 retcode = PyList_Append(dn, rdnt);
1252 Py_DECREF(rdnt);
1253 if (retcode < 0)
1254 goto fail0;
1255 }
1256 else {
1257 Py_DECREF(rdn);
1258 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 /* convert list to tuple */
1262 rdnt = PyList_AsTuple(dn);
1263 Py_DECREF(dn);
1264 if (rdnt == NULL)
1265 return NULL;
1266 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
1268 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270
1271 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 Py_XDECREF(dn);
1273 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274}
1275
1276static PyObject *
1277_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 /* this code follows the procedure outlined in
1280 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1281 function to extract the STACK_OF(GENERAL_NAME),
1282 then iterates through the stack to add the
1283 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001284
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001285 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001287 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 GENERAL_NAMES *names = NULL;
1289 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 BIO *biobuf = NULL;
1291 char buf[2048];
1292 char *vptr;
1293 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001295 if (certificate == NULL)
1296 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001298 /* get a memory buffer */
1299 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001300 if (biobuf == NULL) {
1301 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1302 return NULL;
1303 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001304
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001305 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1306 certificate, NID_subject_alt_name, NULL, NULL);
1307 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 if (peer_alt_names == Py_None) {
1309 peer_alt_names = PyList_New(0);
1310 if (peer_alt_names == NULL)
1311 goto fail;
1312 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001313
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001315 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001316 int gntype;
1317 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001320 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001321 switch (gntype) {
1322 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 /* we special-case DirName as a tuple of
1324 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 t = PyTuple_New(2);
1327 if (t == NULL) {
1328 goto fail;
1329 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 v = PyUnicode_FromString("DirName");
1332 if (v == NULL) {
1333 Py_DECREF(t);
1334 goto fail;
1335 }
1336 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 v = _create_tuple_for_X509_NAME (name->d.dirn);
1339 if (v == NULL) {
1340 Py_DECREF(t);
1341 goto fail;
1342 }
1343 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001344 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001345
Christian Heimes824f7f32013-08-17 00:54:47 +02001346 case GEN_EMAIL:
1347 case GEN_DNS:
1348 case GEN_URI:
1349 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1350 correctly, CVE-2013-4238 */
1351 t = PyTuple_New(2);
1352 if (t == NULL)
1353 goto fail;
1354 switch (gntype) {
1355 case GEN_EMAIL:
1356 v = PyUnicode_FromString("email");
1357 as = name->d.rfc822Name;
1358 break;
1359 case GEN_DNS:
1360 v = PyUnicode_FromString("DNS");
1361 as = name->d.dNSName;
1362 break;
1363 case GEN_URI:
1364 v = PyUnicode_FromString("URI");
1365 as = name->d.uniformResourceIdentifier;
1366 break;
1367 }
1368 if (v == NULL) {
1369 Py_DECREF(t);
1370 goto fail;
1371 }
1372 PyTuple_SET_ITEM(t, 0, v);
1373 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1374 ASN1_STRING_length(as));
1375 if (v == NULL) {
1376 Py_DECREF(t);
1377 goto fail;
1378 }
1379 PyTuple_SET_ITEM(t, 1, v);
1380 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001381
Christian Heimes1c03abd2016-09-06 23:25:35 +02001382 case GEN_RID:
1383 t = PyTuple_New(2);
1384 if (t == NULL)
1385 goto fail;
1386
1387 v = PyUnicode_FromString("Registered ID");
1388 if (v == NULL) {
1389 Py_DECREF(t);
1390 goto fail;
1391 }
1392 PyTuple_SET_ITEM(t, 0, v);
1393
1394 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1395 if (len < 0) {
1396 Py_DECREF(t);
1397 _setSSLError(NULL, 0, __FILE__, __LINE__);
1398 goto fail;
1399 } else if (len >= (int)sizeof(buf)) {
1400 v = PyUnicode_FromString("<INVALID>");
1401 } else {
1402 v = PyUnicode_FromStringAndSize(buf, len);
1403 }
1404 if (v == NULL) {
1405 Py_DECREF(t);
1406 goto fail;
1407 }
1408 PyTuple_SET_ITEM(t, 1, v);
1409 break;
1410
Christian Heimes2b7de662019-12-07 17:59:36 +01001411 case GEN_IPADD:
1412 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1413 * the trailing newline. Remove it in all versions
1414 */
1415 t = PyTuple_New(2);
1416 if (t == NULL)
1417 goto fail;
1418
1419 v = PyUnicode_FromString("IP Address");
1420 if (v == NULL) {
1421 Py_DECREF(t);
1422 goto fail;
1423 }
1424 PyTuple_SET_ITEM(t, 0, v);
1425
1426 if (name->d.ip->length == 4) {
1427 unsigned char *p = name->d.ip->data;
1428 v = PyUnicode_FromFormat(
1429 "%d.%d.%d.%d",
1430 p[0], p[1], p[2], p[3]
1431 );
1432 } else if (name->d.ip->length == 16) {
1433 /* PyUnicode_FromFormat() does not support %X */
1434 unsigned char *p = name->d.ip->data;
1435 len = sprintf(
1436 buf,
1437 "%X:%X:%X:%X:%X:%X:%X:%X",
1438 p[0] << 8 | p[1],
1439 p[2] << 8 | p[3],
1440 p[4] << 8 | p[5],
1441 p[6] << 8 | p[7],
1442 p[8] << 8 | p[9],
1443 p[10] << 8 | p[11],
1444 p[12] << 8 | p[13],
1445 p[14] << 8 | p[15]
1446 );
1447 v = PyUnicode_FromStringAndSize(buf, len);
1448 } else {
1449 v = PyUnicode_FromString("<invalid>");
1450 }
1451
1452 if (v == NULL) {
1453 Py_DECREF(t);
1454 goto fail;
1455 }
1456 PyTuple_SET_ITEM(t, 1, v);
1457 break;
1458
Christian Heimes824f7f32013-08-17 00:54:47 +02001459 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001460 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001461 switch (gntype) {
1462 /* check for new general name type */
1463 case GEN_OTHERNAME:
1464 case GEN_X400:
1465 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001466 case GEN_RID:
1467 break;
1468 default:
1469 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1470 "Unknown general name type %d",
1471 gntype) == -1) {
1472 goto fail;
1473 }
1474 break;
1475 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 (void) BIO_reset(biobuf);
1477 GENERAL_NAME_print(biobuf, name);
1478 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1479 if (len < 0) {
1480 _setSSLError(NULL, 0, __FILE__, __LINE__);
1481 goto fail;
1482 }
1483 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001484 if (vptr == NULL) {
1485 PyErr_Format(PyExc_ValueError,
1486 "Invalid value %.200s",
1487 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001489 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 t = PyTuple_New(2);
1491 if (t == NULL)
1492 goto fail;
1493 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1494 if (v == NULL) {
1495 Py_DECREF(t);
1496 goto fail;
1497 }
1498 PyTuple_SET_ITEM(t, 0, v);
1499 v = PyUnicode_FromStringAndSize((vptr + 1),
1500 (len - (vptr - buf + 1)));
1501 if (v == NULL) {
1502 Py_DECREF(t);
1503 goto fail;
1504 }
1505 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001506 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001507 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 if (PyList_Append(peer_alt_names, t) < 0) {
1512 Py_DECREF(t);
1513 goto fail;
1514 }
1515 Py_DECREF(t);
1516 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001517 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 }
1519 BIO_free(biobuf);
1520 if (peer_alt_names != Py_None) {
1521 v = PyList_AsTuple(peer_alt_names);
1522 Py_DECREF(peer_alt_names);
1523 return v;
1524 } else {
1525 return peer_alt_names;
1526 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001527
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528
1529 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001530 if (biobuf != NULL)
1531 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001533 if (peer_alt_names != Py_None) {
1534 Py_XDECREF(peer_alt_names);
1535 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001537 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538}
1539
1540static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001541_get_aia_uri(X509 *certificate, int nid) {
1542 PyObject *lst = NULL, *ostr = NULL;
1543 int i, result;
1544 AUTHORITY_INFO_ACCESS *info;
1545
1546 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001547 if (info == NULL)
1548 return Py_None;
1549 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1550 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001551 return Py_None;
1552 }
1553
1554 if ((lst = PyList_New(0)) == NULL) {
1555 goto fail;
1556 }
1557
1558 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1559 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1560 ASN1_IA5STRING *uri;
1561
1562 if ((OBJ_obj2nid(ad->method) != nid) ||
1563 (ad->location->type != GEN_URI)) {
1564 continue;
1565 }
1566 uri = ad->location->d.uniformResourceIdentifier;
1567 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1568 uri->length);
1569 if (ostr == NULL) {
1570 goto fail;
1571 }
1572 result = PyList_Append(lst, ostr);
1573 Py_DECREF(ostr);
1574 if (result < 0) {
1575 goto fail;
1576 }
1577 }
1578 AUTHORITY_INFO_ACCESS_free(info);
1579
1580 /* convert to tuple or None */
1581 if (PyList_Size(lst) == 0) {
1582 Py_DECREF(lst);
1583 return Py_None;
1584 } else {
1585 PyObject *tup;
1586 tup = PyList_AsTuple(lst);
1587 Py_DECREF(lst);
1588 return tup;
1589 }
1590
1591 fail:
1592 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001593 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001594 return NULL;
1595}
1596
1597static PyObject *
1598_get_crl_dp(X509 *certificate) {
1599 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001600 int i, j;
1601 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001602
Christian Heimes598894f2016-09-05 23:19:05 +02001603 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001604
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001605 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001606 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001607
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001608 lst = PyList_New(0);
1609 if (lst == NULL)
1610 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001611
1612 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1613 DIST_POINT *dp;
1614 STACK_OF(GENERAL_NAME) *gns;
1615
1616 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001617 if (dp->distpoint == NULL) {
1618 /* Ignore empty DP value, CVE-2019-5010 */
1619 continue;
1620 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001621 gns = dp->distpoint->name.fullname;
1622
1623 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1624 GENERAL_NAME *gn;
1625 ASN1_IA5STRING *uri;
1626 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001627 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001628
1629 gn = sk_GENERAL_NAME_value(gns, j);
1630 if (gn->type != GEN_URI) {
1631 continue;
1632 }
1633 uri = gn->d.uniformResourceIdentifier;
1634 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1635 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001636 if (ouri == NULL)
1637 goto done;
1638
1639 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001640 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001641 if (err < 0)
1642 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001643 }
1644 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001645
1646 /* Convert to tuple. */
1647 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1648
1649 done:
1650 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001651 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001652 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001653}
1654
1655static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001656_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001657
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001658 PyObject *retval = NULL;
1659 BIO *biobuf = NULL;
1660 PyObject *peer;
1661 PyObject *peer_alt_names = NULL;
1662 PyObject *issuer;
1663 PyObject *version;
1664 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001665 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 ASN1_INTEGER *serialNumber;
1667 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001668 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001669 ASN1_TIME *notBefore, *notAfter;
1670 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 retval = PyDict_New();
1673 if (retval == NULL)
1674 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676 peer = _create_tuple_for_X509_NAME(
1677 X509_get_subject_name(certificate));
1678 if (peer == NULL)
1679 goto fail0;
1680 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1681 Py_DECREF(peer);
1682 goto fail0;
1683 }
1684 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001685
Antoine Pitroufb046912010-11-09 20:21:19 +00001686 issuer = _create_tuple_for_X509_NAME(
1687 X509_get_issuer_name(certificate));
1688 if (issuer == NULL)
1689 goto fail0;
1690 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001692 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001694 Py_DECREF(issuer);
1695
1696 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001697 if (version == NULL)
1698 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001699 if (PyDict_SetItemString(retval, "version", version) < 0) {
1700 Py_DECREF(version);
1701 goto fail0;
1702 }
1703 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001705 /* get a memory buffer */
1706 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001707 if (biobuf == NULL) {
1708 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1709 goto fail0;
1710 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001711
Antoine Pitroufb046912010-11-09 20:21:19 +00001712 (void) BIO_reset(biobuf);
1713 serialNumber = X509_get_serialNumber(certificate);
1714 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1715 i2a_ASN1_INTEGER(biobuf, serialNumber);
1716 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1717 if (len < 0) {
1718 _setSSLError(NULL, 0, __FILE__, __LINE__);
1719 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001721 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1722 if (sn_obj == NULL)
1723 goto fail1;
1724 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1725 Py_DECREF(sn_obj);
1726 goto fail1;
1727 }
1728 Py_DECREF(sn_obj);
1729
1730 (void) BIO_reset(biobuf);
1731 notBefore = X509_get_notBefore(certificate);
1732 ASN1_TIME_print(biobuf, notBefore);
1733 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1734 if (len < 0) {
1735 _setSSLError(NULL, 0, __FILE__, __LINE__);
1736 goto fail1;
1737 }
1738 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1739 if (pnotBefore == NULL)
1740 goto fail1;
1741 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1742 Py_DECREF(pnotBefore);
1743 goto fail1;
1744 }
1745 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 (void) BIO_reset(biobuf);
1748 notAfter = X509_get_notAfter(certificate);
1749 ASN1_TIME_print(biobuf, notAfter);
1750 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1751 if (len < 0) {
1752 _setSSLError(NULL, 0, __FILE__, __LINE__);
1753 goto fail1;
1754 }
1755 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1756 if (pnotAfter == NULL)
1757 goto fail1;
1758 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1759 Py_DECREF(pnotAfter);
1760 goto fail1;
1761 }
1762 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001766 peer_alt_names = _get_peer_alt_names(certificate);
1767 if (peer_alt_names == NULL)
1768 goto fail1;
1769 else if (peer_alt_names != Py_None) {
1770 if (PyDict_SetItemString(retval, "subjectAltName",
1771 peer_alt_names) < 0) {
1772 Py_DECREF(peer_alt_names);
1773 goto fail1;
1774 }
1775 Py_DECREF(peer_alt_names);
1776 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001777
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001778 /* Authority Information Access: OCSP URIs */
1779 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1780 if (obj == NULL) {
1781 goto fail1;
1782 } else if (obj != Py_None) {
1783 result = PyDict_SetItemString(retval, "OCSP", obj);
1784 Py_DECREF(obj);
1785 if (result < 0) {
1786 goto fail1;
1787 }
1788 }
1789
1790 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1791 if (obj == NULL) {
1792 goto fail1;
1793 } else if (obj != Py_None) {
1794 result = PyDict_SetItemString(retval, "caIssuers", obj);
1795 Py_DECREF(obj);
1796 if (result < 0) {
1797 goto fail1;
1798 }
1799 }
1800
1801 /* CDP (CRL distribution points) */
1802 obj = _get_crl_dp(certificate);
1803 if (obj == NULL) {
1804 goto fail1;
1805 } else if (obj != Py_None) {
1806 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1807 Py_DECREF(obj);
1808 if (result < 0) {
1809 goto fail1;
1810 }
1811 }
1812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 BIO_free(biobuf);
1814 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001815
1816 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 if (biobuf != NULL)
1818 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001819 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 Py_XDECREF(retval);
1821 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001822}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001823
Christian Heimes9a5395a2013-06-17 15:44:12 +02001824static PyObject *
1825_certificate_to_der(X509 *certificate)
1826{
1827 unsigned char *bytes_buf = NULL;
1828 int len;
1829 PyObject *retval;
1830
1831 bytes_buf = NULL;
1832 len = i2d_X509(certificate, &bytes_buf);
1833 if (len < 0) {
1834 _setSSLError(NULL, 0, __FILE__, __LINE__);
1835 return NULL;
1836 }
1837 /* this is actually an immutable bytes sequence */
1838 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1839 OPENSSL_free(bytes_buf);
1840 return retval;
1841}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001842
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001843/*[clinic input]
1844_ssl._test_decode_cert
1845 path: object(converter="PyUnicode_FSConverter")
1846 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001847
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001848[clinic start generated code]*/
1849
1850static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001851_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1852/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001853{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 X509 *x=NULL;
1856 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1859 PyErr_SetString(PySSLErrorObject,
1860 "Can't malloc memory to read file");
1861 goto fail0;
1862 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001863
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001864 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001865 PyErr_SetString(PySSLErrorObject,
1866 "Can't open file");
1867 goto fail0;
1868 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001869
Alex Gaynor40dad952019-08-15 08:31:28 -04001870 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 if (x == NULL) {
1872 PyErr_SetString(PySSLErrorObject,
1873 "Error decoding PEM-encoded file");
1874 goto fail0;
1875 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001876
Antoine Pitroufb046912010-11-09 20:21:19 +00001877 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001878 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001879
1880 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001881 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 if (cert != NULL) BIO_free(cert);
1883 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001884}
1885
1886
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001887/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001888_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001889 der as binary_mode: bool = False
1890 /
1891
1892Returns the certificate for the peer.
1893
1894If no certificate was provided, returns None. If a certificate was
1895provided, but not validated, returns an empty dictionary. Otherwise
1896returns a dict containing information about the peer certificate.
1897
1898If the optional argument is True, returns a DER-encoded copy of the
1899peer certificate, or None if no certificate was provided. This will
1900return the certificate even if it wasn't validated.
1901[clinic start generated code]*/
1902
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001903static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001904_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1905/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001906{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001908 X509 *peer_cert;
1909 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001910
Christian Heimes66dc33b2017-05-23 16:02:02 -07001911 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001912 PyErr_SetString(PyExc_ValueError,
1913 "handshake not done yet");
1914 return NULL;
1915 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001916 peer_cert = SSL_get_peer_certificate(self->ssl);
1917 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001919
Antoine Pitrou721738f2012-08-15 23:20:39 +02001920 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001922 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001924 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001926 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001928 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001930 X509_free(peer_cert);
1931 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001932}
1933
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001934static PyObject *
1935cipher_to_tuple(const SSL_CIPHER *cipher)
1936{
1937 const char *cipher_name, *cipher_protocol;
1938 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 if (retval == NULL)
1940 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001941
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001942 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001944 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 PyTuple_SET_ITEM(retval, 0, Py_None);
1946 } else {
1947 v = PyUnicode_FromString(cipher_name);
1948 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001949 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 PyTuple_SET_ITEM(retval, 0, v);
1951 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001952
1953 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001955 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 PyTuple_SET_ITEM(retval, 1, Py_None);
1957 } else {
1958 v = PyUnicode_FromString(cipher_protocol);
1959 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001960 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 PyTuple_SET_ITEM(retval, 1, v);
1962 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001963
1964 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001966 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001967 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001970
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001971 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001972 Py_DECREF(retval);
1973 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001974}
1975
Christian Heimes25bfcd52016-09-06 00:04:45 +02001976#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1977static PyObject *
1978cipher_to_dict(const SSL_CIPHER *cipher)
1979{
1980 const char *cipher_name, *cipher_protocol;
1981
1982 unsigned long cipher_id;
1983 int alg_bits, strength_bits, len;
1984 char buf[512] = {0};
1985#if OPENSSL_VERSION_1_1
1986 int aead, nid;
1987 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1988#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001989
1990 /* can be NULL */
1991 cipher_name = SSL_CIPHER_get_name(cipher);
1992 cipher_protocol = SSL_CIPHER_get_version(cipher);
1993 cipher_id = SSL_CIPHER_get_id(cipher);
1994 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001995 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1996 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001997 if (len > 1 && buf[len-1] == '\n')
1998 buf[len-1] = '\0';
1999 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2000
2001#if OPENSSL_VERSION_1_1
2002 aead = SSL_CIPHER_is_aead(cipher);
2003 nid = SSL_CIPHER_get_cipher_nid(cipher);
2004 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2005 nid = SSL_CIPHER_get_digest_nid(cipher);
2006 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2007 nid = SSL_CIPHER_get_kx_nid(cipher);
2008 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2009 nid = SSL_CIPHER_get_auth_nid(cipher);
2010 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2011#endif
2012
Victor Stinner410b9882016-09-12 12:00:23 +02002013 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002014 "{sksssssssisi"
2015#if OPENSSL_VERSION_1_1
2016 "sOssssssss"
2017#endif
2018 "}",
2019 "id", cipher_id,
2020 "name", cipher_name,
2021 "protocol", cipher_protocol,
2022 "description", buf,
2023 "strength_bits", strength_bits,
2024 "alg_bits", alg_bits
2025#if OPENSSL_VERSION_1_1
2026 ,"aead", aead ? Py_True : Py_False,
2027 "symmetric", skcipher,
2028 "digest", digest,
2029 "kea", kx,
2030 "auth", auth
2031#endif
2032 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002033}
2034#endif
2035
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002036/*[clinic input]
2037_ssl._SSLSocket.shared_ciphers
2038[clinic start generated code]*/
2039
2040static PyObject *
2041_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2042/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002043{
2044 STACK_OF(SSL_CIPHER) *ciphers;
2045 int i;
2046 PyObject *res;
2047
Christian Heimes598894f2016-09-05 23:19:05 +02002048 ciphers = SSL_get_ciphers(self->ssl);
2049 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002050 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002051 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2052 if (!res)
2053 return NULL;
2054 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2055 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2056 if (!tup) {
2057 Py_DECREF(res);
2058 return NULL;
2059 }
2060 PyList_SET_ITEM(res, i, tup);
2061 }
2062 return res;
2063}
2064
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002065/*[clinic input]
2066_ssl._SSLSocket.cipher
2067[clinic start generated code]*/
2068
2069static PyObject *
2070_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2071/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002072{
2073 const SSL_CIPHER *current;
2074
2075 if (self->ssl == NULL)
2076 Py_RETURN_NONE;
2077 current = SSL_get_current_cipher(self->ssl);
2078 if (current == NULL)
2079 Py_RETURN_NONE;
2080 return cipher_to_tuple(current);
2081}
2082
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002083/*[clinic input]
2084_ssl._SSLSocket.version
2085[clinic start generated code]*/
2086
2087static PyObject *
2088_ssl__SSLSocket_version_impl(PySSLSocket *self)
2089/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002090{
2091 const char *version;
2092
2093 if (self->ssl == NULL)
2094 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002095 if (!SSL_is_init_finished(self->ssl)) {
2096 /* handshake not finished */
2097 Py_RETURN_NONE;
2098 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002099 version = SSL_get_version(self->ssl);
2100 if (!strcmp(version, "unknown"))
2101 Py_RETURN_NONE;
2102 return PyUnicode_FromString(version);
2103}
2104
Christian Heimes29eab552018-02-25 12:31:33 +01002105#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002106/*[clinic input]
2107_ssl._SSLSocket.selected_npn_protocol
2108[clinic start generated code]*/
2109
2110static PyObject *
2111_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2112/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2113{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002114 const unsigned char *out;
2115 unsigned int outlen;
2116
Victor Stinner4569cd52013-06-23 14:58:43 +02002117 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002118 &out, &outlen);
2119
2120 if (out == NULL)
2121 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002122 return PyUnicode_FromStringAndSize((char *)out, outlen);
2123}
2124#endif
2125
Christian Heimes29eab552018-02-25 12:31:33 +01002126#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002127/*[clinic input]
2128_ssl._SSLSocket.selected_alpn_protocol
2129[clinic start generated code]*/
2130
2131static PyObject *
2132_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2133/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2134{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002135 const unsigned char *out;
2136 unsigned int outlen;
2137
2138 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2139
2140 if (out == NULL)
2141 Py_RETURN_NONE;
2142 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002143}
2144#endif
2145
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002146/*[clinic input]
2147_ssl._SSLSocket.compression
2148[clinic start generated code]*/
2149
2150static PyObject *
2151_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2152/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2153{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002154#ifdef OPENSSL_NO_COMP
2155 Py_RETURN_NONE;
2156#else
2157 const COMP_METHOD *comp_method;
2158 const char *short_name;
2159
2160 if (self->ssl == NULL)
2161 Py_RETURN_NONE;
2162 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002163 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002164 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002165 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002166 if (short_name == NULL)
2167 Py_RETURN_NONE;
2168 return PyUnicode_DecodeFSDefault(short_name);
2169#endif
2170}
2171
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002172static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2173 Py_INCREF(self->ctx);
2174 return self->ctx;
2175}
2176
2177static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2178 void *closure) {
2179
2180 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002181#if !HAVE_SNI
2182 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2183 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002184 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002185#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002186 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002187 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002188 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002189#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002190 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002191 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002192 return -1;
2193 }
2194
2195 return 0;
2196}
2197
2198PyDoc_STRVAR(PySSL_set_context_doc,
2199"_setter_context(ctx)\n\
2200\
2201This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002202used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002203on the SSLContext to change the certificate information associated with the\n\
2204SSLSocket before the cryptographic exchange handshake messages\n");
2205
2206
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002207static PyObject *
2208PySSL_get_server_side(PySSLSocket *self, void *c)
2209{
2210 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2211}
2212
2213PyDoc_STRVAR(PySSL_get_server_side_doc,
2214"Whether this is a server-side socket.");
2215
2216static PyObject *
2217PySSL_get_server_hostname(PySSLSocket *self, void *c)
2218{
2219 if (self->server_hostname == NULL)
2220 Py_RETURN_NONE;
2221 Py_INCREF(self->server_hostname);
2222 return self->server_hostname;
2223}
2224
2225PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2226"The currently set server hostname (for SNI).");
2227
2228static PyObject *
2229PySSL_get_owner(PySSLSocket *self, void *c)
2230{
2231 PyObject *owner;
2232
2233 if (self->owner == NULL)
2234 Py_RETURN_NONE;
2235
2236 owner = PyWeakref_GetObject(self->owner);
2237 Py_INCREF(owner);
2238 return owner;
2239}
2240
2241static int
2242PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2243{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002244 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002245 if (self->owner == NULL)
2246 return -1;
2247 return 0;
2248}
2249
2250PyDoc_STRVAR(PySSL_get_owner_doc,
2251"The Python-level owner of this object.\
2252Passed as \"self\" in servername callback.");
2253
Christian Heimesc7f70692019-05-31 11:44:05 +02002254static int
2255PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2256{
2257 Py_VISIT(self->exc_type);
2258 Py_VISIT(self->exc_value);
2259 Py_VISIT(self->exc_tb);
2260 return 0;
2261}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002262
Christian Heimesc7f70692019-05-31 11:44:05 +02002263static int
2264PySSL_clear(PySSLSocket *self)
2265{
2266 Py_CLEAR(self->exc_type);
2267 Py_CLEAR(self->exc_value);
2268 Py_CLEAR(self->exc_tb);
2269 return 0;
2270}
2271
2272static void
2273PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002274{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 if (self->ssl)
2276 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002278 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002279 Py_XDECREF(self->server_hostname);
2280 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002282}
2283
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002284/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002285 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002286 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002287 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002288
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002289static int
Victor Stinner14690702015-04-06 22:46:13 +02002290PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002291{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002292 int rc;
2293#ifdef HAVE_POLL
2294 struct pollfd pollfd;
2295 _PyTime_t ms;
2296#else
2297 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 fd_set fds;
2299 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002300#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002303 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002305 else if (timeout < 0) {
2306 if (s->sock_timeout > 0)
2307 return SOCKET_HAS_TIMED_OUT;
2308 else
2309 return SOCKET_IS_BLOCKING;
2310 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002312 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002313 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002316 /* Prefer poll, if available, since you can poll() any fd
2317 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002318#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002319 pollfd.fd = s->sock_fd;
2320 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002321
Victor Stinner14690702015-04-06 22:46:13 +02002322 /* timeout is in seconds, poll() uses milliseconds */
2323 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002324 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002325
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002326 PySSL_BEGIN_ALLOW_THREADS
2327 rc = poll(&pollfd, 1, (int)ms);
2328 PySSL_END_ALLOW_THREADS
2329#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002330 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002331 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002333
Victor Stinner14690702015-04-06 22:46:13 +02002334 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 FD_ZERO(&fds);
2337 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002338
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002339 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002341 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002344 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002345 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002347#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002348
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002349 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2350 (when we are able to write or when there's something to read) */
2351 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002352}
2353
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002354/*[clinic input]
2355_ssl._SSLSocket.write
2356 b: Py_buffer
2357 /
2358
2359Writes the bytes-like object b into the SSL object.
2360
2361Returns the number of bytes written.
2362[clinic start generated code]*/
2363
2364static PyObject *
2365_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2366/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002367{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002368 int len;
2369 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002370 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002372 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002373 _PyTime_t timeout, deadline = 0;
2374 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002375
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002376 if (sock != NULL) {
2377 if (((PyObject*)sock) == Py_None) {
2378 _setSSLError("Underlying socket connection gone",
2379 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2380 return NULL;
2381 }
2382 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002383 }
2384
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002385 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002386 PyErr_Format(PyExc_OverflowError,
2387 "string longer than %d bytes", INT_MAX);
2388 goto error;
2389 }
2390
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002391 if (sock != NULL) {
2392 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002393 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002394 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2395 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2396 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397
Victor Stinner14690702015-04-06 22:46:13 +02002398 timeout = GET_SOCKET_TIMEOUT(sock);
2399 has_timeout = (timeout > 0);
2400 if (has_timeout)
2401 deadline = _PyTime_GetMonotonicClock() + timeout;
2402
2403 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002404 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002405 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002406 "The write operation timed out");
2407 goto error;
2408 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2409 PyErr_SetString(PySSLErrorObject,
2410 "Underlying socket has been closed.");
2411 goto error;
2412 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2413 PyErr_SetString(PySSLErrorObject,
2414 "Underlying socket too large for select().");
2415 goto error;
2416 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002417
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002418 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002420 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002421 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002423 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002424
2425 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002427
Victor Stinner14690702015-04-06 22:46:13 +02002428 if (has_timeout)
2429 timeout = deadline - _PyTime_GetMonotonicClock();
2430
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002431 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002432 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002433 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002434 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 } else {
2436 sockstate = SOCKET_OPERATION_OK;
2437 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002440 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 "The write operation timed out");
2442 goto error;
2443 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2444 PyErr_SetString(PySSLErrorObject,
2445 "Underlying socket has been closed.");
2446 goto error;
2447 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2448 break;
2449 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002450 } while (err.ssl == SSL_ERROR_WANT_READ ||
2451 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002452
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002453 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002454 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002456 if (PySSL_ChainExceptions(self) < 0)
2457 return NULL;
2458 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002459error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002460 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002461 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002462 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002463}
2464
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002465/*[clinic input]
2466_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002467
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002468Returns the number of already decrypted bytes available for read, pending on the connection.
2469[clinic start generated code]*/
2470
2471static PyObject *
2472_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2473/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002474{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002476 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002478 PySSL_BEGIN_ALLOW_THREADS
2479 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002480 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002481 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002482 self->err = err;
2483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484 if (count < 0)
2485 return PySSL_SetError(self, count, __FILE__, __LINE__);
2486 else
2487 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002488}
2489
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002490/*[clinic input]
2491_ssl._SSLSocket.read
2492 size as len: int
2493 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002494 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002495 ]
2496 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002497
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002498Read up to size bytes from the SSL socket.
2499[clinic start generated code]*/
2500
2501static PyObject *
2502_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2503 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002504/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002505{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002506 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002508 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002510 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002512 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002513 _PyTime_t timeout, deadline = 0;
2514 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002515
Martin Panter5503d472016-03-27 05:35:19 +00002516 if (!group_right_1 && len < 0) {
2517 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2518 return NULL;
2519 }
2520
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002521 if (sock != NULL) {
2522 if (((PyObject*)sock) == Py_None) {
2523 _setSSLError("Underlying socket connection gone",
2524 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2525 return NULL;
2526 }
2527 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002528 }
2529
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002530 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002531 dest = PyBytes_FromStringAndSize(NULL, len);
2532 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002533 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002534 if (len == 0) {
2535 Py_XDECREF(sock);
2536 return dest;
2537 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002538 mem = PyBytes_AS_STRING(dest);
2539 }
2540 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002541 mem = buffer->buf;
2542 if (len <= 0 || len > buffer->len) {
2543 len = (int) buffer->len;
2544 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002545 PyErr_SetString(PyExc_OverflowError,
2546 "maximum length can't fit in a C 'int'");
2547 goto error;
2548 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002549 if (len == 0) {
2550 count = 0;
2551 goto done;
2552 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002553 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002554 }
2555
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002556 if (sock != NULL) {
2557 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002558 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002559 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2560 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2561 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562
Victor Stinner14690702015-04-06 22:46:13 +02002563 timeout = GET_SOCKET_TIMEOUT(sock);
2564 has_timeout = (timeout > 0);
2565 if (has_timeout)
2566 deadline = _PyTime_GetMonotonicClock() + timeout;
2567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002569 PySSL_BEGIN_ALLOW_THREADS
2570 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002571 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002573 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002575 if (PyErr_CheckSignals())
2576 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002577
Victor Stinner14690702015-04-06 22:46:13 +02002578 if (has_timeout)
2579 timeout = deadline - _PyTime_GetMonotonicClock();
2580
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002581 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002582 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002583 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002584 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002585 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002586 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002587 {
2588 count = 0;
2589 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002590 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002591 else
2592 sockstate = SOCKET_OPERATION_OK;
2593
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002594 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002595 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 "The read operation timed out");
2597 goto error;
2598 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2599 break;
2600 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002601 } while (err.ssl == SSL_ERROR_WANT_READ ||
2602 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002604 if (count <= 0) {
2605 PySSL_SetError(self, count, __FILE__, __LINE__);
2606 goto error;
2607 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002608 if (self->exc_type != NULL)
2609 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002610
2611done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002612 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002613 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002614 _PyBytes_Resize(&dest, count);
2615 return dest;
2616 }
2617 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002618 return PyLong_FromLong(count);
2619 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002620
2621error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002622 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002623 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002624 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002625 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002626 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002627}
2628
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002629/*[clinic input]
2630_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002631
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002632Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002633[clinic start generated code]*/
2634
2635static PyObject *
2636_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002637/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002638{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002639 _PySSLError err;
2640 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002641 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002642 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002643 _PyTime_t timeout, deadline = 0;
2644 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002645
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002646 if (sock != NULL) {
2647 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002648 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002649 _setSSLError("Underlying socket connection gone",
2650 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2651 return NULL;
2652 }
2653 Py_INCREF(sock);
2654
2655 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002656 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002657 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2658 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002659 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002660
Victor Stinner14690702015-04-06 22:46:13 +02002661 timeout = GET_SOCKET_TIMEOUT(sock);
2662 has_timeout = (timeout > 0);
2663 if (has_timeout)
2664 deadline = _PyTime_GetMonotonicClock() + timeout;
2665
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002666 while (1) {
2667 PySSL_BEGIN_ALLOW_THREADS
2668 /* Disable read-ahead so that unwrap can work correctly.
2669 * Otherwise OpenSSL might read in too much data,
2670 * eating clear text data that happens to be
2671 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002672 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002673 * function is used and the shutdown_seen_zero != 0
2674 * condition is met.
2675 */
2676 if (self->shutdown_seen_zero)
2677 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002678 ret = SSL_shutdown(self->ssl);
2679 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002680 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002681 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002683 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002684 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002685 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002686 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002687 /* Don't loop endlessly; instead preserve legacy
2688 behaviour of trying SSL_shutdown() only twice.
2689 This looks necessary for OpenSSL < 0.9.8m */
2690 if (++zeros > 1)
2691 break;
2692 /* Shutdown was sent, now try receiving */
2693 self->shutdown_seen_zero = 1;
2694 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002695 }
2696
Victor Stinner14690702015-04-06 22:46:13 +02002697 if (has_timeout)
2698 timeout = deadline - _PyTime_GetMonotonicClock();
2699
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002700 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002701 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002702 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002703 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002704 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002705 else
2706 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002707
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002708 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002709 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002710 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002711 "The read operation timed out");
2712 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002713 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002714 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002715 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002716 }
2717 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2718 PyErr_SetString(PySSLErrorObject,
2719 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002720 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002721 }
2722 else if (sockstate != SOCKET_OPERATION_OK)
2723 /* Retain the SSL error code */
2724 break;
2725 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002726 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002727 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002728 PySSL_SetError(self, ret, __FILE__, __LINE__);
2729 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002730 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002731 if (self->exc_type != NULL)
2732 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002733 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002734 /* It's already INCREF'ed */
2735 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002736 else
2737 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002738
2739error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002740 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002741 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002742 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002743}
2744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002745/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002746_ssl._SSLSocket.get_channel_binding
2747 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002748
Christian Heimes141c5e82018-02-24 21:10:57 +01002749Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002750
Christian Heimes141c5e82018-02-24 21:10:57 +01002751Raise ValueError if the requested `cb_type` is not supported. Return bytes
2752of the data or None if the data is not available (e.g. before the handshake).
2753Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002754[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002755
Antoine Pitroud6494802011-07-21 01:11:30 +02002756static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002757_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2758 const char *cb_type)
2759/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002760{
Antoine Pitroud6494802011-07-21 01:11:30 +02002761 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002762 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002763
Christian Heimes141c5e82018-02-24 21:10:57 +01002764 if (strcmp(cb_type, "tls-unique") == 0) {
2765 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2766 /* if session is resumed XOR we are the client */
2767 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2768 }
2769 else {
2770 /* if a new session XOR we are the server */
2771 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2772 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002773 }
2774 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002775 PyErr_Format(
2776 PyExc_ValueError,
2777 "'%s' channel binding type not implemented",
2778 cb_type
2779 );
2780 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002781 }
2782
2783 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002784 if (len == 0)
2785 Py_RETURN_NONE;
2786
Christian Heimes141c5e82018-02-24 21:10:57 +01002787 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002788}
2789
Christian Heimes9fb051f2018-09-23 08:32:31 +02002790/*[clinic input]
2791_ssl._SSLSocket.verify_client_post_handshake
2792
2793Initiate TLS 1.3 post-handshake authentication
2794[clinic start generated code]*/
2795
2796static PyObject *
2797_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2798/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2799{
2800#ifdef TLS1_3_VERSION
2801 int err = SSL_verify_client_post_handshake(self->ssl);
2802 if (err == 0)
2803 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2804 else
2805 Py_RETURN_NONE;
2806#else
2807 PyErr_SetString(PyExc_NotImplementedError,
2808 "Post-handshake auth is not supported by your "
2809 "OpenSSL version.");
2810 return NULL;
2811#endif
2812}
2813
Christian Heimes99a65702016-09-10 23:44:53 +02002814#ifdef OPENSSL_VERSION_1_1
2815
2816static SSL_SESSION*
2817_ssl_session_dup(SSL_SESSION *session) {
2818 SSL_SESSION *newsession = NULL;
2819 int slen;
2820 unsigned char *senc = NULL, *p;
2821 const unsigned char *const_p;
2822
2823 if (session == NULL) {
2824 PyErr_SetString(PyExc_ValueError, "Invalid session");
2825 goto error;
2826 }
2827
2828 /* get length */
2829 slen = i2d_SSL_SESSION(session, NULL);
2830 if (slen == 0 || slen > 0xFF00) {
2831 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2832 goto error;
2833 }
2834 if ((senc = PyMem_Malloc(slen)) == NULL) {
2835 PyErr_NoMemory();
2836 goto error;
2837 }
2838 p = senc;
2839 if (!i2d_SSL_SESSION(session, &p)) {
2840 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2841 goto error;
2842 }
2843 const_p = senc;
2844 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2845 if (session == NULL) {
2846 goto error;
2847 }
2848 PyMem_Free(senc);
2849 return newsession;
2850 error:
2851 if (senc != NULL) {
2852 PyMem_Free(senc);
2853 }
2854 return NULL;
2855}
2856#endif
2857
2858static PyObject *
2859PySSL_get_session(PySSLSocket *self, void *closure) {
2860 /* get_session can return sessions from a server-side connection,
2861 * it does not check for handshake done or client socket. */
2862 PySSLSession *pysess;
2863 SSL_SESSION *session;
2864
2865#ifdef OPENSSL_VERSION_1_1
2866 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2867 * https://github.com/openssl/openssl/issues/1550 */
2868 session = SSL_get0_session(self->ssl); /* borrowed reference */
2869 if (session == NULL) {
2870 Py_RETURN_NONE;
2871 }
2872 if ((session = _ssl_session_dup(session)) == NULL) {
2873 return NULL;
2874 }
2875#else
2876 session = SSL_get1_session(self->ssl);
2877 if (session == NULL) {
2878 Py_RETURN_NONE;
2879 }
2880#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002881 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002882 if (pysess == NULL) {
2883 SSL_SESSION_free(session);
2884 return NULL;
2885 }
2886
2887 assert(self->ctx);
2888 pysess->ctx = self->ctx;
2889 Py_INCREF(pysess->ctx);
2890 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002891 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002892 return (PyObject *)pysess;
2893}
2894
2895static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2896 void *closure)
2897 {
2898 PySSLSession *pysess;
2899#ifdef OPENSSL_VERSION_1_1
2900 SSL_SESSION *session;
2901#endif
2902 int result;
2903
2904 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002905 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002906 return -1;
2907 }
2908 pysess = (PySSLSession *)value;
2909
2910 if (self->ctx->ctx != pysess->ctx->ctx) {
2911 PyErr_SetString(PyExc_ValueError,
2912 "Session refers to a different SSLContext.");
2913 return -1;
2914 }
2915 if (self->socket_type != PY_SSL_CLIENT) {
2916 PyErr_SetString(PyExc_ValueError,
2917 "Cannot set session for server-side SSLSocket.");
2918 return -1;
2919 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002920 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002921 PyErr_SetString(PyExc_ValueError,
2922 "Cannot set session after handshake.");
2923 return -1;
2924 }
2925#ifdef OPENSSL_VERSION_1_1
2926 /* duplicate session */
2927 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2928 return -1;
2929 }
2930 result = SSL_set_session(self->ssl, session);
2931 /* free duplicate, SSL_set_session() bumps ref count */
2932 SSL_SESSION_free(session);
2933#else
2934 result = SSL_set_session(self->ssl, pysess->session);
2935#endif
2936 if (result == 0) {
2937 _setSSLError(NULL, 0, __FILE__, __LINE__);
2938 return -1;
2939 }
2940 return 0;
2941}
2942
2943PyDoc_STRVAR(PySSL_set_session_doc,
2944"_setter_session(session)\n\
2945\
2946Get / set SSLSession.");
2947
2948static PyObject *
2949PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2950 if (SSL_session_reused(self->ssl)) {
2951 Py_RETURN_TRUE;
2952 } else {
2953 Py_RETURN_FALSE;
2954 }
2955}
2956
2957PyDoc_STRVAR(PySSL_get_session_reused_doc,
2958"Was the client session reused during handshake?");
2959
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002960static PyGetSetDef ssl_getsetlist[] = {
2961 {"context", (getter) PySSL_get_context,
2962 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002963 {"server_side", (getter) PySSL_get_server_side, NULL,
2964 PySSL_get_server_side_doc},
2965 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2966 PySSL_get_server_hostname_doc},
2967 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2968 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002969 {"session", (getter) PySSL_get_session,
2970 (setter) PySSL_set_session, PySSL_set_session_doc},
2971 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2972 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002973 {NULL}, /* sentinel */
2974};
2975
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002976static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002977 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2978 _SSL__SSLSOCKET_WRITE_METHODDEF
2979 _SSL__SSLSOCKET_READ_METHODDEF
2980 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002981 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2982 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002983 _SSL__SSLSOCKET_CIPHER_METHODDEF
2984 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2985 _SSL__SSLSOCKET_VERSION_METHODDEF
2986 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2987 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2988 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2989 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002990 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002991 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002992};
2993
Antoine Pitrou152efa22010-05-16 18:19:27 +00002994static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002995 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996 "_ssl._SSLSocket", /*tp_name*/
2997 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002998 0, /*tp_itemsize*/
2999 /* methods */
3000 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003001 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003002 0, /*tp_getattr*/
3003 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003004 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003005 0, /*tp_repr*/
3006 0, /*tp_as_number*/
3007 0, /*tp_as_sequence*/
3008 0, /*tp_as_mapping*/
3009 0, /*tp_hash*/
3010 0, /*tp_call*/
3011 0, /*tp_str*/
3012 0, /*tp_getattro*/
3013 0, /*tp_setattro*/
3014 0, /*tp_as_buffer*/
3015 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3016 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003017 (traverseproc) PySSL_traverse, /*tp_traverse*/
3018 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003019 0, /*tp_richcompare*/
3020 0, /*tp_weaklistoffset*/
3021 0, /*tp_iter*/
3022 0, /*tp_iternext*/
3023 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003024 0, /*tp_members*/
3025 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003026};
3027
Antoine Pitrou152efa22010-05-16 18:19:27 +00003028
3029/*
3030 * _SSLContext objects
3031 */
3032
Christian Heimes5fe668c2016-09-12 00:01:11 +02003033static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003034_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003035{
3036 int mode;
3037 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3038
3039 switch(n) {
3040 case PY_SSL_CERT_NONE:
3041 mode = SSL_VERIFY_NONE;
3042 break;
3043 case PY_SSL_CERT_OPTIONAL:
3044 mode = SSL_VERIFY_PEER;
3045 break;
3046 case PY_SSL_CERT_REQUIRED:
3047 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3048 break;
3049 default:
3050 PyErr_SetString(PyExc_ValueError,
3051 "invalid value for verify_mode");
3052 return -1;
3053 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003054
3055 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3056 * server sockets and SSL_set_post_handshake_auth() for client. */
3057
Christian Heimes5fe668c2016-09-12 00:01:11 +02003058 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003059 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3060 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003061 return 0;
3062}
3063
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003064/*[clinic input]
3065@classmethod
3066_ssl._SSLContext.__new__
3067 protocol as proto_version: int
3068 /
3069[clinic start generated code]*/
3070
Antoine Pitrou152efa22010-05-16 18:19:27 +00003071static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003072_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3073/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003074{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003076 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003077 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003078 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003079 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003080#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003081 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003082#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083
Antoine Pitrou152efa22010-05-16 18:19:27 +00003084 PySSL_BEGIN_ALLOW_THREADS
3085 if (proto_version == PY_SSL_VERSION_TLS1)
3086 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003087#if HAVE_TLSv1_2
3088 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3089 ctx = SSL_CTX_new(TLSv1_1_method());
3090 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3091 ctx = SSL_CTX_new(TLSv1_2_method());
3092#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003093#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003094 else if (proto_version == PY_SSL_VERSION_SSL3)
3095 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003096#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003097#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003098 else if (proto_version == PY_SSL_VERSION_SSL2)
3099 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003100#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003101 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003102 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003103 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3104 ctx = SSL_CTX_new(TLS_client_method());
3105 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3106 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003107 else
3108 proto_version = -1;
3109 PySSL_END_ALLOW_THREADS
3110
3111 if (proto_version == -1) {
3112 PyErr_SetString(PyExc_ValueError,
3113 "invalid protocol version");
3114 return NULL;
3115 }
3116 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003117 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003118 return NULL;
3119 }
3120
3121 assert(type != NULL && type->tp_alloc != NULL);
3122 self = (PySSLContext *) type->tp_alloc(type, 0);
3123 if (self == NULL) {
3124 SSL_CTX_free(ctx);
3125 return NULL;
3126 }
3127 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003128 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003129 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003130 self->msg_cb = NULL;
3131#ifdef HAVE_OPENSSL_KEYLOG
3132 self->keylog_filename = NULL;
3133 self->keylog_bio = NULL;
3134#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003135#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003136 self->npn_protocols = NULL;
3137#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003138#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003139 self->alpn_protocols = NULL;
3140#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003141#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003142 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003143#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003144 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003145 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3146 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003147 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003148 Py_DECREF(self);
3149 return NULL;
3150 }
3151 } else {
3152 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003153 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003154 Py_DECREF(self);
3155 return NULL;
3156 }
3157 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003158 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003159 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3160 if (proto_version != PY_SSL_VERSION_SSL2)
3161 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003162 if (proto_version != PY_SSL_VERSION_SSL3)
3163 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003164 /* Minimal security flags for server and client side context.
3165 * Client sockets ignore server-side parameters. */
3166#ifdef SSL_OP_NO_COMPRESSION
3167 options |= SSL_OP_NO_COMPRESSION;
3168#endif
3169#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3170 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3171#endif
3172#ifdef SSL_OP_SINGLE_DH_USE
3173 options |= SSL_OP_SINGLE_DH_USE;
3174#endif
3175#ifdef SSL_OP_SINGLE_ECDH_USE
3176 options |= SSL_OP_SINGLE_ECDH_USE;
3177#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003178 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003179
Semen Zhydenko1295e112017-10-15 21:28:31 +02003180 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003181 * It's far from perfect but gives users a better head start. */
3182 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003183#if PY_SSL_DEFAULT_CIPHERS == 2
3184 /* stick to OpenSSL's default settings */
3185 result = 1;
3186#else
3187 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3188#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003189 } else {
3190 /* SSLv2 needs MD5 */
3191 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3192 }
3193 if (result == 0) {
3194 Py_DECREF(self);
3195 ERR_clear_error();
3196 PyErr_SetString(PySSLErrorObject,
3197 "No cipher can be selected.");
3198 return NULL;
3199 }
3200
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003201#if defined(SSL_MODE_RELEASE_BUFFERS)
3202 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3203 usage for no cost at all. However, don't do this for OpenSSL versions
3204 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3205 2014-0198. I can't find exactly which beta fixed this CVE, so be
3206 conservative and assume it wasn't fixed until release. We do this check
3207 at runtime to avoid problems from the dynamic linker.
3208 See #25672 for more on this. */
3209 libver = SSLeay();
3210 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3211 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3212 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3213 }
3214#endif
3215
3216
Donald Stufft8ae264c2017-03-02 11:45:29 -05003217#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003218 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3219 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003220 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3221 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003222#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003223 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3224#else
3225 {
3226 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3227 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3228 EC_KEY_free(key);
3229 }
3230#endif
3231#endif
3232
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003233#define SID_CTX "Python"
3234 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3235 sizeof(SID_CTX));
3236#undef SID_CTX
3237
Christian Heimes61d478c2018-01-27 15:51:38 +01003238 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003239#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003240 /* Improve trust chain building when cross-signed intermediate
3241 certificates are present. See https://bugs.python.org/issue23476. */
3242 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003243#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003244 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003245
Christian Heimes9fb051f2018-09-23 08:32:31 +02003246#ifdef TLS1_3_VERSION
3247 self->post_handshake_auth = 0;
3248 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3249#endif
3250
Antoine Pitrou152efa22010-05-16 18:19:27 +00003251 return (PyObject *)self;
3252}
3253
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003254static int
3255context_traverse(PySSLContext *self, visitproc visit, void *arg)
3256{
3257#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003258 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003259#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003260 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003261 return 0;
3262}
3263
3264static int
3265context_clear(PySSLContext *self)
3266{
3267#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003268 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003269#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003270 Py_CLEAR(self->msg_cb);
3271#ifdef HAVE_OPENSSL_KEYLOG
3272 Py_CLEAR(self->keylog_filename);
3273 if (self->keylog_bio != NULL) {
3274 PySSL_BEGIN_ALLOW_THREADS
3275 BIO_free_all(self->keylog_bio);
3276 PySSL_END_ALLOW_THREADS
3277 self->keylog_bio = NULL;
3278 }
3279#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003280 return 0;
3281}
3282
Antoine Pitrou152efa22010-05-16 18:19:27 +00003283static void
3284context_dealloc(PySSLContext *self)
3285{
INADA Naokia6296d32017-08-24 14:55:17 +09003286 /* bpo-31095: UnTrack is needed before calling any callbacks */
3287 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003288 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003289 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003290#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003291 PyMem_FREE(self->npn_protocols);
3292#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003293#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003294 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003295#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003296 Py_TYPE(self)->tp_free(self);
3297}
3298
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003299/*[clinic input]
3300_ssl._SSLContext.set_ciphers
3301 cipherlist: str
3302 /
3303[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003304
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003305static PyObject *
3306_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3307/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3308{
3309 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003311 /* Clearing the error queue is necessary on some OpenSSL versions,
3312 otherwise the error will be reported again when another SSL call
3313 is done. */
3314 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315 PyErr_SetString(PySSLErrorObject,
3316 "No cipher can be selected.");
3317 return NULL;
3318 }
3319 Py_RETURN_NONE;
3320}
3321
Christian Heimes25bfcd52016-09-06 00:04:45 +02003322#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3323/*[clinic input]
3324_ssl._SSLContext.get_ciphers
3325[clinic start generated code]*/
3326
3327static PyObject *
3328_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3329/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3330{
3331 SSL *ssl = NULL;
3332 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003333 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003334 int i=0;
3335 PyObject *result = NULL, *dct;
3336
3337 ssl = SSL_new(self->ctx);
3338 if (ssl == NULL) {
3339 _setSSLError(NULL, 0, __FILE__, __LINE__);
3340 goto exit;
3341 }
3342 sk = SSL_get_ciphers(ssl);
3343
3344 result = PyList_New(sk_SSL_CIPHER_num(sk));
3345 if (result == NULL) {
3346 goto exit;
3347 }
3348
3349 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3350 cipher = sk_SSL_CIPHER_value(sk, i);
3351 dct = cipher_to_dict(cipher);
3352 if (dct == NULL) {
3353 Py_CLEAR(result);
3354 goto exit;
3355 }
3356 PyList_SET_ITEM(result, i, dct);
3357 }
3358
3359 exit:
3360 if (ssl != NULL)
3361 SSL_free(ssl);
3362 return result;
3363
3364}
3365#endif
3366
3367
Christian Heimes29eab552018-02-25 12:31:33 +01003368#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003369static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003370do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3371 const unsigned char *server_protocols, unsigned int server_protocols_len,
3372 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003373{
Benjamin Peterson88615022015-01-23 17:30:26 -05003374 int ret;
3375 if (client_protocols == NULL) {
3376 client_protocols = (unsigned char *)"";
3377 client_protocols_len = 0;
3378 }
3379 if (server_protocols == NULL) {
3380 server_protocols = (unsigned char *)"";
3381 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003382 }
3383
Benjamin Peterson88615022015-01-23 17:30:26 -05003384 ret = SSL_select_next_proto(out, outlen,
3385 server_protocols, server_protocols_len,
3386 client_protocols, client_protocols_len);
3387 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3388 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003389
3390 return SSL_TLSEXT_ERR_OK;
3391}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003392#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003393
Christian Heimes29eab552018-02-25 12:31:33 +01003394#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003395/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3396static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003397_advertiseNPN_cb(SSL *s,
3398 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003399 void *args)
3400{
3401 PySSLContext *ssl_ctx = (PySSLContext *) args;
3402
3403 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003404 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003405 *len = 0;
3406 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003407 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003408 *len = ssl_ctx->npn_protocols_len;
3409 }
3410
3411 return SSL_TLSEXT_ERR_OK;
3412}
3413/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3414static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003415_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003416 unsigned char **out, unsigned char *outlen,
3417 const unsigned char *server, unsigned int server_len,
3418 void *args)
3419{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003420 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003421 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003422 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003423}
3424#endif
3425
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003426/*[clinic input]
3427_ssl._SSLContext._set_npn_protocols
3428 protos: Py_buffer
3429 /
3430[clinic start generated code]*/
3431
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003432static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003433_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3434 Py_buffer *protos)
3435/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003436{
Christian Heimes29eab552018-02-25 12:31:33 +01003437#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003438 PyMem_Free(self->npn_protocols);
3439 self->npn_protocols = PyMem_Malloc(protos->len);
3440 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003441 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003442 memcpy(self->npn_protocols, protos->buf, protos->len);
3443 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003444
3445 /* set both server and client callbacks, because the context can
3446 * be used to create both types of sockets */
3447 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3448 _advertiseNPN_cb,
3449 self);
3450 SSL_CTX_set_next_proto_select_cb(self->ctx,
3451 _selectNPN_cb,
3452 self);
3453
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003454 Py_RETURN_NONE;
3455#else
3456 PyErr_SetString(PyExc_NotImplementedError,
3457 "The NPN extension requires OpenSSL 1.0.1 or later.");
3458 return NULL;
3459#endif
3460}
3461
Christian Heimes29eab552018-02-25 12:31:33 +01003462#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003463static int
3464_selectALPN_cb(SSL *s,
3465 const unsigned char **out, unsigned char *outlen,
3466 const unsigned char *client_protocols, unsigned int client_protocols_len,
3467 void *args)
3468{
3469 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003470 return do_protocol_selection(1, (unsigned char **)out, outlen,
3471 ctx->alpn_protocols, ctx->alpn_protocols_len,
3472 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003473}
3474#endif
3475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003476/*[clinic input]
3477_ssl._SSLContext._set_alpn_protocols
3478 protos: Py_buffer
3479 /
3480[clinic start generated code]*/
3481
Benjamin Petersoncca27322015-01-23 16:35:37 -05003482static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003483_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3484 Py_buffer *protos)
3485/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003486{
Christian Heimes29eab552018-02-25 12:31:33 +01003487#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003488 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003489 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003490 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003491 return NULL;
3492 }
3493
Benjamin Petersoncca27322015-01-23 16:35:37 -05003494 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003495 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003496 if (!self->alpn_protocols)
3497 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003498 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003499 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003500
3501 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3502 return PyErr_NoMemory();
3503 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3504
Benjamin Petersoncca27322015-01-23 16:35:37 -05003505 Py_RETURN_NONE;
3506#else
3507 PyErr_SetString(PyExc_NotImplementedError,
3508 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3509 return NULL;
3510#endif
3511}
3512
Antoine Pitrou152efa22010-05-16 18:19:27 +00003513static PyObject *
3514get_verify_mode(PySSLContext *self, void *c)
3515{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003516 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3517 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3518 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3519 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003520 case SSL_VERIFY_NONE:
3521 return PyLong_FromLong(PY_SSL_CERT_NONE);
3522 case SSL_VERIFY_PEER:
3523 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3524 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3525 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3526 }
3527 PyErr_SetString(PySSLErrorObject,
3528 "invalid return value from SSL_CTX_get_verify_mode");
3529 return NULL;
3530}
3531
3532static int
3533set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3534{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003535 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003536 if (!PyArg_Parse(arg, "i", &n))
3537 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003538 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003539 PyErr_SetString(PyExc_ValueError,
3540 "Cannot set verify_mode to CERT_NONE when "
3541 "check_hostname is enabled.");
3542 return -1;
3543 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003544 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545}
3546
3547static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003548get_verify_flags(PySSLContext *self, void *c)
3549{
Christian Heimes598894f2016-09-05 23:19:05 +02003550 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003551 unsigned long flags;
3552
Christian Heimes61d478c2018-01-27 15:51:38 +01003553 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003554 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003555 return PyLong_FromUnsignedLong(flags);
3556}
3557
3558static int
3559set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3560{
Christian Heimes598894f2016-09-05 23:19:05 +02003561 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003562 unsigned long new_flags, flags, set, clear;
3563
3564 if (!PyArg_Parse(arg, "k", &new_flags))
3565 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003566 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003567 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003568 clear = flags & ~new_flags;
3569 set = ~flags & new_flags;
3570 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003571 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003572 _setSSLError(NULL, 0, __FILE__, __LINE__);
3573 return -1;
3574 }
3575 }
3576 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003577 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003578 _setSSLError(NULL, 0, __FILE__, __LINE__);
3579 return -1;
3580 }
3581 }
3582 return 0;
3583}
3584
Christian Heimes698dde12018-02-27 11:54:43 +01003585/* Getter and setter for protocol version */
3586#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3587
3588
3589static int
3590set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3591{
3592 long v;
3593 int result;
3594
3595 if (!PyArg_Parse(arg, "l", &v))
3596 return -1;
3597 if (v > INT_MAX) {
3598 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3599 return -1;
3600 }
3601
3602 switch(self->protocol) {
3603 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3604 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3605 case PY_SSL_VERSION_TLS:
3606 break;
3607 default:
3608 PyErr_SetString(
3609 PyExc_ValueError,
3610 "The context's protocol doesn't support modification of "
3611 "highest and lowest version."
3612 );
3613 return -1;
3614 }
3615
3616 if (what == 0) {
3617 switch(v) {
3618 case PY_PROTO_MINIMUM_SUPPORTED:
3619 v = 0;
3620 break;
3621 case PY_PROTO_MAXIMUM_SUPPORTED:
3622 /* Emulate max for set_min_proto_version */
3623 v = PY_PROTO_MAXIMUM_AVAILABLE;
3624 break;
3625 default:
3626 break;
3627 }
3628 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3629 }
3630 else {
3631 switch(v) {
3632 case PY_PROTO_MAXIMUM_SUPPORTED:
3633 v = 0;
3634 break;
3635 case PY_PROTO_MINIMUM_SUPPORTED:
3636 /* Emulate max for set_min_proto_version */
3637 v = PY_PROTO_MINIMUM_AVAILABLE;
3638 break;
3639 default:
3640 break;
3641 }
3642 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3643 }
3644 if (result == 0) {
3645 PyErr_Format(PyExc_ValueError,
3646 "Unsupported protocol version 0x%x", v);
3647 return -1;
3648 }
3649 return 0;
3650}
3651
3652static PyObject *
3653get_minimum_version(PySSLContext *self, void *c)
3654{
3655 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3656 if (v == 0) {
3657 v = PY_PROTO_MINIMUM_SUPPORTED;
3658 }
3659 return PyLong_FromLong(v);
3660}
3661
3662static int
3663set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3664{
3665 return set_min_max_proto_version(self, arg, 0);
3666}
3667
3668static PyObject *
3669get_maximum_version(PySSLContext *self, void *c)
3670{
3671 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3672 if (v == 0) {
3673 v = PY_PROTO_MAXIMUM_SUPPORTED;
3674 }
3675 return PyLong_FromLong(v);
3676}
3677
3678static int
3679set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3680{
3681 return set_min_max_proto_version(self, arg, 1);
3682}
3683#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3684
Christian Heimes78c7d522019-06-03 21:00:10 +02003685#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3686static PyObject *
3687get_num_tickets(PySSLContext *self, void *c)
3688{
Victor Stinner76611c72019-07-09 13:30:52 +02003689 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003690}
3691
3692static int
3693set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3694{
3695 long num;
3696 if (!PyArg_Parse(arg, "l", &num))
3697 return -1;
3698 if (num < 0) {
3699 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3700 return -1;
3701 }
3702 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3703 PyErr_SetString(PyExc_ValueError,
3704 "SSLContext is not a server context.");
3705 return -1;
3706 }
3707 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3708 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3709 return -1;
3710 }
3711 return 0;
3712}
3713
3714PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3715"Control the number of TLSv1.3 session tickets");
3716#endif /* OpenSSL 1.1.1 */
3717
Christian Heimes22587792013-11-21 23:56:13 +01003718static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003719get_options(PySSLContext *self, void *c)
3720{
3721 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3722}
3723
3724static int
3725set_options(PySSLContext *self, PyObject *arg, void *c)
3726{
3727 long new_opts, opts, set, clear;
3728 if (!PyArg_Parse(arg, "l", &new_opts))
3729 return -1;
3730 opts = SSL_CTX_get_options(self->ctx);
3731 clear = opts & ~new_opts;
3732 set = ~opts & new_opts;
3733 if (clear) {
3734#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3735 SSL_CTX_clear_options(self->ctx, clear);
3736#else
3737 PyErr_SetString(PyExc_ValueError,
3738 "can't clear options before OpenSSL 0.9.8m");
3739 return -1;
3740#endif
3741 }
3742 if (set)
3743 SSL_CTX_set_options(self->ctx, set);
3744 return 0;
3745}
3746
Christian Heimes1aa9a752013-12-02 02:41:19 +01003747static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003748get_host_flags(PySSLContext *self, void *c)
3749{
3750 return PyLong_FromUnsignedLong(self->hostflags);
3751}
3752
3753static int
3754set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3755{
3756 X509_VERIFY_PARAM *param;
3757 unsigned int new_flags = 0;
3758
3759 if (!PyArg_Parse(arg, "I", &new_flags))
3760 return -1;
3761
3762 param = SSL_CTX_get0_param(self->ctx);
3763 self->hostflags = new_flags;
3764 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3765 return 0;
3766}
3767
3768static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003769get_check_hostname(PySSLContext *self, void *c)
3770{
3771 return PyBool_FromLong(self->check_hostname);
3772}
3773
3774static int
3775set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3776{
3777 int check_hostname;
3778 if (!PyArg_Parse(arg, "p", &check_hostname))
3779 return -1;
3780 if (check_hostname &&
3781 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003782 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003783 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003784 return -1;
3785 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003786 }
3787 self->check_hostname = check_hostname;
3788 return 0;
3789}
3790
Christian Heimes11a14932018-02-24 02:35:08 +01003791static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003792get_post_handshake_auth(PySSLContext *self, void *c) {
3793#if TLS1_3_VERSION
3794 return PyBool_FromLong(self->post_handshake_auth);
3795#else
3796 Py_RETURN_NONE;
3797#endif
3798}
3799
3800#if TLS1_3_VERSION
3801static int
3802set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003803 if (arg == NULL) {
3804 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3805 return -1;
3806 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003807 int pha = PyObject_IsTrue(arg);
3808
3809 if (pha == -1) {
3810 return -1;
3811 }
3812 self->post_handshake_auth = pha;
3813
Christian Heimesf0f59302019-07-01 08:29:17 +02003814 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3815 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003816
3817 return 0;
3818}
3819#endif
3820
3821static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003822get_protocol(PySSLContext *self, void *c) {
3823 return PyLong_FromLong(self->protocol);
3824}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003825
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003826typedef struct {
3827 PyThreadState *thread_state;
3828 PyObject *callable;
3829 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003830 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003831 int error;
3832} _PySSLPasswordInfo;
3833
3834static int
3835_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3836 const char *bad_type_error)
3837{
3838 /* Set the password and size fields of a _PySSLPasswordInfo struct
3839 from a unicode, bytes, or byte array object.
3840 The password field will be dynamically allocated and must be freed
3841 by the caller */
3842 PyObject *password_bytes = NULL;
3843 const char *data = NULL;
3844 Py_ssize_t size;
3845
3846 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003847 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003848 if (!password_bytes) {
3849 goto error;
3850 }
3851 data = PyBytes_AS_STRING(password_bytes);
3852 size = PyBytes_GET_SIZE(password_bytes);
3853 } else if (PyBytes_Check(password)) {
3854 data = PyBytes_AS_STRING(password);
3855 size = PyBytes_GET_SIZE(password);
3856 } else if (PyByteArray_Check(password)) {
3857 data = PyByteArray_AS_STRING(password);
3858 size = PyByteArray_GET_SIZE(password);
3859 } else {
3860 PyErr_SetString(PyExc_TypeError, bad_type_error);
3861 goto error;
3862 }
3863
Victor Stinner9ee02032013-06-23 15:08:23 +02003864 if (size > (Py_ssize_t)INT_MAX) {
3865 PyErr_Format(PyExc_ValueError,
3866 "password cannot be longer than %d bytes", INT_MAX);
3867 goto error;
3868 }
3869
Victor Stinner11ebff22013-07-07 17:07:52 +02003870 PyMem_Free(pw_info->password);
3871 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003872 if (!pw_info->password) {
3873 PyErr_SetString(PyExc_MemoryError,
3874 "unable to allocate password buffer");
3875 goto error;
3876 }
3877 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003878 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003879
3880 Py_XDECREF(password_bytes);
3881 return 1;
3882
3883error:
3884 Py_XDECREF(password_bytes);
3885 return 0;
3886}
3887
3888static int
3889_password_callback(char *buf, int size, int rwflag, void *userdata)
3890{
3891 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3892 PyObject *fn_ret = NULL;
3893
3894 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3895
3896 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003897 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003898 if (!fn_ret) {
3899 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3900 core python API, so we could use it to add a frame here */
3901 goto error;
3902 }
3903
3904 if (!_pwinfo_set(pw_info, fn_ret,
3905 "password callback must return a string")) {
3906 goto error;
3907 }
3908 Py_CLEAR(fn_ret);
3909 }
3910
3911 if (pw_info->size > size) {
3912 PyErr_Format(PyExc_ValueError,
3913 "password cannot be longer than %d bytes", size);
3914 goto error;
3915 }
3916
3917 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3918 memcpy(buf, pw_info->password, pw_info->size);
3919 return pw_info->size;
3920
3921error:
3922 Py_XDECREF(fn_ret);
3923 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3924 pw_info->error = 1;
3925 return -1;
3926}
3927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003928/*[clinic input]
3929_ssl._SSLContext.load_cert_chain
3930 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003931 keyfile: object = None
3932 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003933
3934[clinic start generated code]*/
3935
Antoine Pitroub5218772010-05-21 09:56:06 +00003936static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003937_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3938 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003939/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003940{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003941 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003942 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3943 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003944 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003945 int r;
3946
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003947 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003948 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003949 if (keyfile == Py_None)
3950 keyfile = NULL;
3951 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003952 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3953 PyErr_SetString(PyExc_TypeError,
3954 "certfile should be a valid filesystem path");
3955 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003956 return NULL;
3957 }
3958 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003959 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3960 PyErr_SetString(PyExc_TypeError,
3961 "keyfile should be a valid filesystem path");
3962 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003963 goto error;
3964 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003965 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003966 if (PyCallable_Check(password)) {
3967 pw_info.callable = password;
3968 } else if (!_pwinfo_set(&pw_info, password,
3969 "password should be a string or callable")) {
3970 goto error;
3971 }
3972 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3973 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3974 }
3975 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3977 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003978 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003979 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003980 if (pw_info.error) {
3981 ERR_clear_error();
3982 /* the password callback has already set the error information */
3983 }
3984 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003985 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003986 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003987 }
3988 else {
3989 _setSSLError(NULL, 0, __FILE__, __LINE__);
3990 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003991 goto error;
3992 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003993 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003994 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3996 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003997 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3998 Py_CLEAR(keyfile_bytes);
3999 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004000 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004001 if (pw_info.error) {
4002 ERR_clear_error();
4003 /* the password callback has already set the error information */
4004 }
4005 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004006 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004007 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004008 }
4009 else {
4010 _setSSLError(NULL, 0, __FILE__, __LINE__);
4011 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004012 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004013 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004014 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004015 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004016 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004017 if (r != 1) {
4018 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004019 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004021 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4022 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004023 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024 Py_RETURN_NONE;
4025
4026error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004027 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4028 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004029 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004030 Py_XDECREF(keyfile_bytes);
4031 Py_XDECREF(certfile_bytes);
4032 return NULL;
4033}
4034
Christian Heimesefff7062013-11-21 03:35:02 +01004035/* internal helper function, returns -1 on error
4036 */
4037static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004038_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004039 int filetype)
4040{
4041 BIO *biobuf = NULL;
4042 X509_STORE *store;
4043 int retval = 0, err, loaded = 0;
4044
4045 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4046
4047 if (len <= 0) {
4048 PyErr_SetString(PyExc_ValueError,
4049 "Empty certificate data");
4050 return -1;
4051 } else if (len > INT_MAX) {
4052 PyErr_SetString(PyExc_OverflowError,
4053 "Certificate data is too long.");
4054 return -1;
4055 }
4056
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004057 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004058 if (biobuf == NULL) {
4059 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4060 return -1;
4061 }
4062
4063 store = SSL_CTX_get_cert_store(self->ctx);
4064 assert(store != NULL);
4065
4066 while (1) {
4067 X509 *cert = NULL;
4068 int r;
4069
4070 if (filetype == SSL_FILETYPE_ASN1) {
4071 cert = d2i_X509_bio(biobuf, NULL);
4072 } else {
4073 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004074 SSL_CTX_get_default_passwd_cb(self->ctx),
4075 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4076 );
Christian Heimesefff7062013-11-21 03:35:02 +01004077 }
4078 if (cert == NULL) {
4079 break;
4080 }
4081 r = X509_STORE_add_cert(store, cert);
4082 X509_free(cert);
4083 if (!r) {
4084 err = ERR_peek_last_error();
4085 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4086 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4087 /* cert already in hash table, not an error */
4088 ERR_clear_error();
4089 } else {
4090 break;
4091 }
4092 }
4093 loaded++;
4094 }
4095
4096 err = ERR_peek_last_error();
4097 if ((filetype == SSL_FILETYPE_ASN1) &&
4098 (loaded > 0) &&
4099 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4100 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4101 /* EOF ASN1 file, not an error */
4102 ERR_clear_error();
4103 retval = 0;
4104 } else if ((filetype == SSL_FILETYPE_PEM) &&
4105 (loaded > 0) &&
4106 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4107 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4108 /* EOF PEM file, not an error */
4109 ERR_clear_error();
4110 retval = 0;
4111 } else {
4112 _setSSLError(NULL, 0, __FILE__, __LINE__);
4113 retval = -1;
4114 }
4115
4116 BIO_free(biobuf);
4117 return retval;
4118}
4119
4120
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004121/*[clinic input]
4122_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004123 cafile: object = None
4124 capath: object = None
4125 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004126
4127[clinic start generated code]*/
4128
Antoine Pitrou152efa22010-05-16 18:19:27 +00004129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4131 PyObject *cafile,
4132 PyObject *capath,
4133 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004134/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004135{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004136 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4137 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004138 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004139
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004140 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004141 if (cafile == Py_None)
4142 cafile = NULL;
4143 if (capath == Py_None)
4144 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004145 if (cadata == Py_None)
4146 cadata = NULL;
4147
4148 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004149 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004150 "cafile, capath and cadata cannot be all omitted");
4151 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004152 }
4153 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004154 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4155 PyErr_SetString(PyExc_TypeError,
4156 "cafile should be a valid filesystem path");
4157 }
Christian Heimesefff7062013-11-21 03:35:02 +01004158 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004159 }
4160 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004161 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4162 PyErr_SetString(PyExc_TypeError,
4163 "capath should be a valid filesystem path");
4164 }
Christian Heimesefff7062013-11-21 03:35:02 +01004165 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004166 }
Christian Heimesefff7062013-11-21 03:35:02 +01004167
4168 /* validata cadata type and load cadata */
4169 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004170 if (PyUnicode_Check(cadata)) {
4171 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4172 if (cadata_ascii == NULL) {
4173 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4174 goto invalid_cadata;
4175 }
4176 goto error;
4177 }
4178 r = _add_ca_certs(self,
4179 PyBytes_AS_STRING(cadata_ascii),
4180 PyBytes_GET_SIZE(cadata_ascii),
4181 SSL_FILETYPE_PEM);
4182 Py_DECREF(cadata_ascii);
4183 if (r == -1) {
4184 goto error;
4185 }
4186 }
4187 else if (PyObject_CheckBuffer(cadata)) {
4188 Py_buffer buf;
4189 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4190 goto error;
4191 }
Christian Heimesefff7062013-11-21 03:35:02 +01004192 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4193 PyBuffer_Release(&buf);
4194 PyErr_SetString(PyExc_TypeError,
4195 "cadata should be a contiguous buffer with "
4196 "a single dimension");
4197 goto error;
4198 }
4199 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4200 PyBuffer_Release(&buf);
4201 if (r == -1) {
4202 goto error;
4203 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004204 }
4205 else {
4206 invalid_cadata:
4207 PyErr_SetString(PyExc_TypeError,
4208 "cadata should be an ASCII string or a "
4209 "bytes-like object");
4210 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004211 }
4212 }
4213
4214 /* load cafile or capath */
4215 if (cafile || capath) {
4216 if (cafile)
4217 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4218 if (capath)
4219 capath_buf = PyBytes_AS_STRING(capath_bytes);
4220 PySSL_BEGIN_ALLOW_THREADS
4221 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4222 PySSL_END_ALLOW_THREADS
4223 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004224 if (errno != 0) {
4225 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004226 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004227 }
4228 else {
4229 _setSSLError(NULL, 0, __FILE__, __LINE__);
4230 }
4231 goto error;
4232 }
4233 }
4234 goto end;
4235
4236 error:
4237 ok = 0;
4238 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004239 Py_XDECREF(cafile_bytes);
4240 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004241 if (ok) {
4242 Py_RETURN_NONE;
4243 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004244 return NULL;
4245 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004246}
4247
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004248/*[clinic input]
4249_ssl._SSLContext.load_dh_params
4250 path as filepath: object
4251 /
4252
4253[clinic start generated code]*/
4254
Antoine Pitrou152efa22010-05-16 18:19:27 +00004255static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004256_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4257/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004258{
4259 FILE *f;
4260 DH *dh;
4261
Victor Stinnerdaf45552013-08-28 00:53:59 +02004262 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004263 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004264 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004265
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004266 errno = 0;
4267 PySSL_BEGIN_ALLOW_THREADS
4268 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004269 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004270 PySSL_END_ALLOW_THREADS
4271 if (dh == NULL) {
4272 if (errno != 0) {
4273 ERR_clear_error();
4274 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4275 }
4276 else {
4277 _setSSLError(NULL, 0, __FILE__, __LINE__);
4278 }
4279 return NULL;
4280 }
4281 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4282 _setSSLError(NULL, 0, __FILE__, __LINE__);
4283 DH_free(dh);
4284 Py_RETURN_NONE;
4285}
4286
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004287/*[clinic input]
4288_ssl._SSLContext._wrap_socket
4289 sock: object(subclass_of="PySocketModule.Sock_Type")
4290 server_side: int
4291 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004292 *
4293 owner: object = None
4294 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004295
4296[clinic start generated code]*/
4297
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004298static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004299_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004300 int server_side, PyObject *hostname_obj,
4301 PyObject *owner, PyObject *session)
4302/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004303{
Antoine Pitroud5323212010-10-22 18:19:07 +00004304 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004305 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004306
Antoine Pitroud5323212010-10-22 18:19:07 +00004307 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004308 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004309 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004310 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004311 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004312 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004313
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004314 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4315 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004316 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004317 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004318 if (hostname != NULL)
4319 PyMem_Free(hostname);
4320 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004321}
4322
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004323/*[clinic input]
4324_ssl._SSLContext._wrap_bio
4325 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4326 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4327 server_side: int
4328 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004329 *
4330 owner: object = None
4331 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004332
4333[clinic start generated code]*/
4334
Antoine Pitroub0182c82010-10-12 20:09:02 +00004335static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004336_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4337 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004338 PyObject *hostname_obj, PyObject *owner,
4339 PyObject *session)
4340/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004341{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004342 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004343 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004344
4345 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004346 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004347 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004348 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004349 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004350 }
4351
4352 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004353 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004354 incoming, outgoing);
4355
4356 PyMem_Free(hostname);
4357 return res;
4358}
4359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004360/*[clinic input]
4361_ssl._SSLContext.session_stats
4362[clinic start generated code]*/
4363
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004364static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004365_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4366/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004367{
4368 int r;
4369 PyObject *value, *stats = PyDict_New();
4370 if (!stats)
4371 return NULL;
4372
4373#define ADD_STATS(SSL_NAME, KEY_NAME) \
4374 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4375 if (value == NULL) \
4376 goto error; \
4377 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4378 Py_DECREF(value); \
4379 if (r < 0) \
4380 goto error;
4381
4382 ADD_STATS(number, "number");
4383 ADD_STATS(connect, "connect");
4384 ADD_STATS(connect_good, "connect_good");
4385 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4386 ADD_STATS(accept, "accept");
4387 ADD_STATS(accept_good, "accept_good");
4388 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4389 ADD_STATS(accept, "accept");
4390 ADD_STATS(hits, "hits");
4391 ADD_STATS(misses, "misses");
4392 ADD_STATS(timeouts, "timeouts");
4393 ADD_STATS(cache_full, "cache_full");
4394
4395#undef ADD_STATS
4396
4397 return stats;
4398
4399error:
4400 Py_DECREF(stats);
4401 return NULL;
4402}
4403
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004404/*[clinic input]
4405_ssl._SSLContext.set_default_verify_paths
4406[clinic start generated code]*/
4407
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004408static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004409_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4410/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004411{
4412 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4413 _setSSLError(NULL, 0, __FILE__, __LINE__);
4414 return NULL;
4415 }
4416 Py_RETURN_NONE;
4417}
4418
Antoine Pitrou501da612011-12-21 09:27:41 +01004419#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004420/*[clinic input]
4421_ssl._SSLContext.set_ecdh_curve
4422 name: object
4423 /
4424
4425[clinic start generated code]*/
4426
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004427static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004428_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4429/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004430{
4431 PyObject *name_bytes;
4432 int nid;
4433 EC_KEY *key;
4434
4435 if (!PyUnicode_FSConverter(name, &name_bytes))
4436 return NULL;
4437 assert(PyBytes_Check(name_bytes));
4438 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4439 Py_DECREF(name_bytes);
4440 if (nid == 0) {
4441 PyErr_Format(PyExc_ValueError,
4442 "unknown elliptic curve name %R", name);
4443 return NULL;
4444 }
4445 key = EC_KEY_new_by_curve_name(nid);
4446 if (key == NULL) {
4447 _setSSLError(NULL, 0, __FILE__, __LINE__);
4448 return NULL;
4449 }
4450 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4451 EC_KEY_free(key);
4452 Py_RETURN_NONE;
4453}
Antoine Pitrou501da612011-12-21 09:27:41 +01004454#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004455
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004456#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004457static int
4458_servername_callback(SSL *s, int *al, void *args)
4459{
4460 int ret;
4461 PySSLContext *ssl_ctx = (PySSLContext *) args;
4462 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004463 PyObject *result;
4464 /* The high-level ssl.SSLSocket object */
4465 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004466 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004467 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004468
Christian Heimes11a14932018-02-24 02:35:08 +01004469 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004470 /* remove race condition in this the call back while if removing the
4471 * callback is in progress */
4472 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004473 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004474 }
4475
4476 ssl = SSL_get_app_data(s);
4477 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004478
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004479 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004480 * SSL connection and that has a .context attribute that can be changed to
4481 * identify the requested hostname. Since the official API is the Python
4482 * level API we want to pass the callback a Python level object rather than
4483 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4484 * SSLObject) that will be passed. Otherwise if there's a socket then that
4485 * will be passed. If both do not exist only then the C-level object is
4486 * passed. */
4487 if (ssl->owner)
4488 ssl_socket = PyWeakref_GetObject(ssl->owner);
4489 else if (ssl->Socket)
4490 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4491 else
4492 ssl_socket = (PyObject *) ssl;
4493
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004494 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004495 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004496 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004497
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004498 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004499 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004500 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004501 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004502 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004503 PyObject *servername_bytes;
4504 PyObject *servername_str;
4505
4506 servername_bytes = PyBytes_FromString(servername);
4507 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004508 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4509 goto error;
4510 }
Christian Heimes11a14932018-02-24 02:35:08 +01004511 /* server_hostname was encoded to an A-label by our caller; put it
4512 * back into a str object, but still as an A-label (bpo-28414)
4513 */
4514 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4515 Py_DECREF(servername_bytes);
4516 if (servername_str == NULL) {
4517 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004518 goto error;
4519 }
Christian Heimes11a14932018-02-24 02:35:08 +01004520 result = PyObject_CallFunctionObjArgs(
4521 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4522 ssl_ctx, NULL);
4523 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004524 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004525 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004526
4527 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004528 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004529 *al = SSL_AD_HANDSHAKE_FAILURE;
4530 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4531 }
4532 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004533 /* Result may be None, a SSLContext or an integer
4534 * None and SSLContext are OK, integer or other values are an error.
4535 */
4536 if (result == Py_None) {
4537 ret = SSL_TLSEXT_ERR_OK;
4538 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004539 *al = (int) PyLong_AsLong(result);
4540 if (PyErr_Occurred()) {
4541 PyErr_WriteUnraisable(result);
4542 *al = SSL_AD_INTERNAL_ERROR;
4543 }
4544 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4545 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004546 Py_DECREF(result);
4547 }
4548
4549 PyGILState_Release(gstate);
4550 return ret;
4551
4552error:
4553 Py_DECREF(ssl_socket);
4554 *al = SSL_AD_INTERNAL_ERROR;
4555 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4556 PyGILState_Release(gstate);
4557 return ret;
4558}
Antoine Pitroua5963382013-03-30 16:39:00 +01004559#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004560
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004561static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004562get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004563{
Christian Heimes11a14932018-02-24 02:35:08 +01004564 PyObject *cb = self->set_sni_cb;
4565 if (cb == NULL) {
4566 Py_RETURN_NONE;
4567 }
4568 Py_INCREF(cb);
4569 return cb;
4570}
4571
4572static int
4573set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4574{
4575 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4576 PyErr_SetString(PyExc_ValueError,
4577 "sni_callback cannot be set on TLS_CLIENT context");
4578 return -1;
4579 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004580#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004581 Py_CLEAR(self->set_sni_cb);
4582 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004583 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4584 }
4585 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004586 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004587 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4588 PyErr_SetString(PyExc_TypeError,
4589 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004590 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004591 }
Christian Heimes11a14932018-02-24 02:35:08 +01004592 Py_INCREF(arg);
4593 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004594 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4595 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4596 }
Christian Heimes11a14932018-02-24 02:35:08 +01004597 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004598#else
4599 PyErr_SetString(PyExc_NotImplementedError,
4600 "The TLS extension servername callback, "
4601 "SSL_CTX_set_tlsext_servername_callback, "
4602 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004603 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004604#endif
4605}
4606
Christian Heimes11a14932018-02-24 02:35:08 +01004607PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4608"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4609\n\
4610If the argument is None then the callback is disabled. The method is called\n\
4611with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4612See RFC 6066 for details of the SNI extension.");
4613
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004614/*[clinic input]
4615_ssl._SSLContext.cert_store_stats
4616
4617Returns quantities of loaded X.509 certificates.
4618
4619X.509 certificates with a CA extension and certificate revocation lists
4620inside the context's cert store.
4621
4622NOTE: Certificates in a capath directory aren't loaded unless they have
4623been used at least once.
4624[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004625
4626static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004627_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4628/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004629{
4630 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004631 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004632 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004633 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004634
4635 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004636 objs = X509_STORE_get0_objects(store);
4637 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4638 obj = sk_X509_OBJECT_value(objs, i);
4639 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004640 case X509_LU_X509:
4641 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004642 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004643 ca++;
4644 }
4645 break;
4646 case X509_LU_CRL:
4647 crl++;
4648 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004649 default:
4650 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4651 * As far as I can tell they are internal states and never
4652 * stored in a cert store */
4653 break;
4654 }
4655 }
4656 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4657 "x509_ca", ca);
4658}
4659
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004660/*[clinic input]
4661_ssl._SSLContext.get_ca_certs
4662 binary_form: bool = False
4663
4664Returns a list of dicts with information of loaded CA certs.
4665
4666If the optional argument is True, returns a DER-encoded copy of the CA
4667certificate.
4668
4669NOTE: Certificates in a capath directory aren't loaded unless they have
4670been used at least once.
4671[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004672
4673static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004674_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4675/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004676{
4677 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004678 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004679 PyObject *ci = NULL, *rlist = NULL;
4680 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004681
4682 if ((rlist = PyList_New(0)) == NULL) {
4683 return NULL;
4684 }
4685
4686 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004687 objs = X509_STORE_get0_objects(store);
4688 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004689 X509_OBJECT *obj;
4690 X509 *cert;
4691
Christian Heimes598894f2016-09-05 23:19:05 +02004692 obj = sk_X509_OBJECT_value(objs, i);
4693 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004694 /* not a x509 cert */
4695 continue;
4696 }
4697 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004698 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004699 if (!X509_check_ca(cert)) {
4700 continue;
4701 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004702 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004703 ci = _certificate_to_der(cert);
4704 } else {
4705 ci = _decode_certificate(cert);
4706 }
4707 if (ci == NULL) {
4708 goto error;
4709 }
4710 if (PyList_Append(rlist, ci) == -1) {
4711 goto error;
4712 }
4713 Py_CLEAR(ci);
4714 }
4715 return rlist;
4716
4717 error:
4718 Py_XDECREF(ci);
4719 Py_XDECREF(rlist);
4720 return NULL;
4721}
4722
4723
Antoine Pitrou152efa22010-05-16 18:19:27 +00004724static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004725 {"check_hostname", (getter) get_check_hostname,
4726 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004727 {"_host_flags", (getter) get_host_flags,
4728 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004729#if SSL_CTRL_GET_MAX_PROTO_VERSION
4730 {"minimum_version", (getter) get_minimum_version,
4731 (setter) set_minimum_version, NULL},
4732 {"maximum_version", (getter) get_maximum_version,
4733 (setter) set_maximum_version, NULL},
4734#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004735#ifdef HAVE_OPENSSL_KEYLOG
4736 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4737 (setter) _PySSLContext_set_keylog_filename, NULL},
4738#endif
4739 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4740 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004741 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004742 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004743#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4744 {"num_tickets", (getter) get_num_tickets,
4745 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4746#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004747 {"options", (getter) get_options,
4748 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004749 {"post_handshake_auth", (getter) get_post_handshake_auth,
4750#ifdef TLS1_3_VERSION
4751 (setter) set_post_handshake_auth,
4752#else
4753 NULL,
4754#endif
4755 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004756 {"protocol", (getter) get_protocol,
4757 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004758 {"verify_flags", (getter) get_verify_flags,
4759 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004760 {"verify_mode", (getter) get_verify_mode,
4761 (setter) set_verify_mode, NULL},
4762 {NULL}, /* sentinel */
4763};
4764
4765static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004766 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4767 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4768 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4769 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4770 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4771 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4772 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4773 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4774 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4775 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4776 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004777 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4778 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004779 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004780 {NULL, NULL} /* sentinel */
4781};
4782
4783static PyTypeObject PySSLContext_Type = {
4784 PyVarObject_HEAD_INIT(NULL, 0)
4785 "_ssl._SSLContext", /*tp_name*/
4786 sizeof(PySSLContext), /*tp_basicsize*/
4787 0, /*tp_itemsize*/
4788 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004789 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004790 0, /*tp_getattr*/
4791 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004792 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004793 0, /*tp_repr*/
4794 0, /*tp_as_number*/
4795 0, /*tp_as_sequence*/
4796 0, /*tp_as_mapping*/
4797 0, /*tp_hash*/
4798 0, /*tp_call*/
4799 0, /*tp_str*/
4800 0, /*tp_getattro*/
4801 0, /*tp_setattro*/
4802 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004803 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004804 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004805 (traverseproc) context_traverse, /*tp_traverse*/
4806 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004807 0, /*tp_richcompare*/
4808 0, /*tp_weaklistoffset*/
4809 0, /*tp_iter*/
4810 0, /*tp_iternext*/
4811 context_methods, /*tp_methods*/
4812 0, /*tp_members*/
4813 context_getsetlist, /*tp_getset*/
4814 0, /*tp_base*/
4815 0, /*tp_dict*/
4816 0, /*tp_descr_get*/
4817 0, /*tp_descr_set*/
4818 0, /*tp_dictoffset*/
4819 0, /*tp_init*/
4820 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004821 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004822};
4823
4824
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004825/*
4826 * MemoryBIO objects
4827 */
4828
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004829/*[clinic input]
4830@classmethod
4831_ssl.MemoryBIO.__new__
4832
4833[clinic start generated code]*/
4834
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004835static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004836_ssl_MemoryBIO_impl(PyTypeObject *type)
4837/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004838{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004839 BIO *bio;
4840 PySSLMemoryBIO *self;
4841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004842 bio = BIO_new(BIO_s_mem());
4843 if (bio == NULL) {
4844 PyErr_SetString(PySSLErrorObject,
4845 "failed to allocate BIO");
4846 return NULL;
4847 }
4848 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4849 * just that no data is currently available. The SSL routines should retry
4850 * the read, which we can achieve by calling BIO_set_retry_read(). */
4851 BIO_set_retry_read(bio);
4852 BIO_set_mem_eof_return(bio, -1);
4853
4854 assert(type != NULL && type->tp_alloc != NULL);
4855 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4856 if (self == NULL) {
4857 BIO_free(bio);
4858 return NULL;
4859 }
4860 self->bio = bio;
4861 self->eof_written = 0;
4862
4863 return (PyObject *) self;
4864}
4865
4866static void
4867memory_bio_dealloc(PySSLMemoryBIO *self)
4868{
4869 BIO_free(self->bio);
4870 Py_TYPE(self)->tp_free(self);
4871}
4872
4873static PyObject *
4874memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4875{
Segev Finer5cff6372017-07-27 01:19:17 +03004876 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004877}
4878
4879PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4880"The number of bytes pending in the memory BIO.");
4881
4882static PyObject *
4883memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4884{
4885 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4886 && self->eof_written);
4887}
4888
4889PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4890"Whether the memory BIO is at EOF.");
4891
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004892/*[clinic input]
4893_ssl.MemoryBIO.read
4894 size as len: int = -1
4895 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004896
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004897Read up to size bytes from the memory BIO.
4898
4899If size is not specified, read the entire buffer.
4900If the return value is an empty bytes instance, this means either
4901EOF or that no data is available. Use the "eof" property to
4902distinguish between the two.
4903[clinic start generated code]*/
4904
4905static PyObject *
4906_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4907/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4908{
4909 int avail, nbytes;
4910 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004911
Segev Finer5cff6372017-07-27 01:19:17 +03004912 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004913 if ((len < 0) || (len > avail))
4914 len = avail;
4915
4916 result = PyBytes_FromStringAndSize(NULL, len);
4917 if ((result == NULL) || (len == 0))
4918 return result;
4919
4920 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004921 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004922 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004923 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004924 return NULL;
4925 }
4926
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004927 /* There should never be any short reads but check anyway. */
4928 if (nbytes < len) {
4929 _PyBytes_Resize(&result, nbytes);
4930 }
4931
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004932 return result;
4933}
4934
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004935/*[clinic input]
4936_ssl.MemoryBIO.write
4937 b: Py_buffer
4938 /
4939
4940Writes the bytes b into the memory BIO.
4941
4942Returns the number of bytes written.
4943[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004944
4945static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004946_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4947/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004948{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004949 int nbytes;
4950
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004951 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004952 PyErr_Format(PyExc_OverflowError,
4953 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004954 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004955 }
4956
4957 if (self->eof_written) {
4958 PyErr_SetString(PySSLErrorObject,
4959 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004960 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004961 }
4962
Segev Finer5cff6372017-07-27 01:19:17 +03004963 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004964 if (nbytes < 0) {
4965 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004966 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004967 }
4968
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004969 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004970}
4971
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004972/*[clinic input]
4973_ssl.MemoryBIO.write_eof
4974
4975Write an EOF marker to the memory BIO.
4976
4977When all data has been read, the "eof" property will be True.
4978[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004979
4980static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004981_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4982/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004983{
4984 self->eof_written = 1;
4985 /* After an EOF is written, a zero return from read() should be a real EOF
4986 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4987 BIO_clear_retry_flags(self->bio);
4988 BIO_set_mem_eof_return(self->bio, 0);
4989
4990 Py_RETURN_NONE;
4991}
4992
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004993static PyGetSetDef memory_bio_getsetlist[] = {
4994 {"pending", (getter) memory_bio_get_pending, NULL,
4995 PySSL_memory_bio_pending_doc},
4996 {"eof", (getter) memory_bio_get_eof, NULL,
4997 PySSL_memory_bio_eof_doc},
4998 {NULL}, /* sentinel */
4999};
5000
5001static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005002 _SSL_MEMORYBIO_READ_METHODDEF
5003 _SSL_MEMORYBIO_WRITE_METHODDEF
5004 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005005 {NULL, NULL} /* sentinel */
5006};
5007
5008static PyTypeObject PySSLMemoryBIO_Type = {
5009 PyVarObject_HEAD_INIT(NULL, 0)
5010 "_ssl.MemoryBIO", /*tp_name*/
5011 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5012 0, /*tp_itemsize*/
5013 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005014 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005015 0, /*tp_getattr*/
5016 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005017 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005018 0, /*tp_repr*/
5019 0, /*tp_as_number*/
5020 0, /*tp_as_sequence*/
5021 0, /*tp_as_mapping*/
5022 0, /*tp_hash*/
5023 0, /*tp_call*/
5024 0, /*tp_str*/
5025 0, /*tp_getattro*/
5026 0, /*tp_setattro*/
5027 0, /*tp_as_buffer*/
5028 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5029 0, /*tp_doc*/
5030 0, /*tp_traverse*/
5031 0, /*tp_clear*/
5032 0, /*tp_richcompare*/
5033 0, /*tp_weaklistoffset*/
5034 0, /*tp_iter*/
5035 0, /*tp_iternext*/
5036 memory_bio_methods, /*tp_methods*/
5037 0, /*tp_members*/
5038 memory_bio_getsetlist, /*tp_getset*/
5039 0, /*tp_base*/
5040 0, /*tp_dict*/
5041 0, /*tp_descr_get*/
5042 0, /*tp_descr_set*/
5043 0, /*tp_dictoffset*/
5044 0, /*tp_init*/
5045 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005046 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005047};
5048
Antoine Pitrou152efa22010-05-16 18:19:27 +00005049
Christian Heimes99a65702016-09-10 23:44:53 +02005050/*
5051 * SSL Session object
5052 */
5053
5054static void
5055PySSLSession_dealloc(PySSLSession *self)
5056{
INADA Naokia6296d32017-08-24 14:55:17 +09005057 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005058 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005059 Py_XDECREF(self->ctx);
5060 if (self->session != NULL) {
5061 SSL_SESSION_free(self->session);
5062 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005063 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005064}
5065
5066static PyObject *
5067PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5068{
5069 int result;
5070
5071 if (left == NULL || right == NULL) {
5072 PyErr_BadInternalCall();
5073 return NULL;
5074 }
5075
5076 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5077 Py_RETURN_NOTIMPLEMENTED;
5078 }
5079
5080 if (left == right) {
5081 result = 0;
5082 } else {
5083 const unsigned char *left_id, *right_id;
5084 unsigned int left_len, right_len;
5085 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5086 &left_len);
5087 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5088 &right_len);
5089 if (left_len == right_len) {
5090 result = memcmp(left_id, right_id, left_len);
5091 } else {
5092 result = 1;
5093 }
5094 }
5095
5096 switch (op) {
5097 case Py_EQ:
5098 if (result == 0) {
5099 Py_RETURN_TRUE;
5100 } else {
5101 Py_RETURN_FALSE;
5102 }
5103 break;
5104 case Py_NE:
5105 if (result != 0) {
5106 Py_RETURN_TRUE;
5107 } else {
5108 Py_RETURN_FALSE;
5109 }
5110 break;
5111 case Py_LT:
5112 case Py_LE:
5113 case Py_GT:
5114 case Py_GE:
5115 Py_RETURN_NOTIMPLEMENTED;
5116 break;
5117 default:
5118 PyErr_BadArgument();
5119 return NULL;
5120 }
5121}
5122
5123static int
5124PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5125{
5126 Py_VISIT(self->ctx);
5127 return 0;
5128}
5129
5130static int
5131PySSLSession_clear(PySSLSession *self)
5132{
5133 Py_CLEAR(self->ctx);
5134 return 0;
5135}
5136
5137
5138static PyObject *
5139PySSLSession_get_time(PySSLSession *self, void *closure) {
5140 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5141}
5142
5143PyDoc_STRVAR(PySSLSession_get_time_doc,
5144"Session creation time (seconds since epoch).");
5145
5146
5147static PyObject *
5148PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5149 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5150}
5151
5152PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5153"Session timeout (delta in seconds).");
5154
5155
5156static PyObject *
5157PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5158 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5159 return PyLong_FromUnsignedLong(hint);
5160}
5161
5162PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5163"Ticket life time hint.");
5164
5165
5166static PyObject *
5167PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5168 const unsigned char *id;
5169 unsigned int len;
5170 id = SSL_SESSION_get_id(self->session, &len);
5171 return PyBytes_FromStringAndSize((const char *)id, len);
5172}
5173
5174PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5175"Session id");
5176
5177
5178static PyObject *
5179PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5180 if (SSL_SESSION_has_ticket(self->session)) {
5181 Py_RETURN_TRUE;
5182 } else {
5183 Py_RETURN_FALSE;
5184 }
5185}
5186
5187PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5188"Does the session contain a ticket?");
5189
5190
5191static PyGetSetDef PySSLSession_getsetlist[] = {
5192 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5193 PySSLSession_get_has_ticket_doc},
5194 {"id", (getter) PySSLSession_get_session_id, NULL,
5195 PySSLSession_get_session_id_doc},
5196 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5197 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5198 {"time", (getter) PySSLSession_get_time, NULL,
5199 PySSLSession_get_time_doc},
5200 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5201 PySSLSession_get_timeout_doc},
5202 {NULL}, /* sentinel */
5203};
5204
5205static PyTypeObject PySSLSession_Type = {
5206 PyVarObject_HEAD_INIT(NULL, 0)
5207 "_ssl.Session", /*tp_name*/
5208 sizeof(PySSLSession), /*tp_basicsize*/
5209 0, /*tp_itemsize*/
5210 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005211 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005212 0, /*tp_getattr*/
5213 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005214 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005215 0, /*tp_repr*/
5216 0, /*tp_as_number*/
5217 0, /*tp_as_sequence*/
5218 0, /*tp_as_mapping*/
5219 0, /*tp_hash*/
5220 0, /*tp_call*/
5221 0, /*tp_str*/
5222 0, /*tp_getattro*/
5223 0, /*tp_setattro*/
5224 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005225 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005226 0, /*tp_doc*/
5227 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5228 (inquiry)PySSLSession_clear, /*tp_clear*/
5229 PySSLSession_richcompare, /*tp_richcompare*/
5230 0, /*tp_weaklistoffset*/
5231 0, /*tp_iter*/
5232 0, /*tp_iternext*/
5233 0, /*tp_methods*/
5234 0, /*tp_members*/
5235 PySSLSession_getsetlist, /*tp_getset*/
5236};
5237
5238
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005239/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005240/*[clinic input]
5241_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005242 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005243 entropy: double
5244 /
5245
5246Mix string into the OpenSSL PRNG state.
5247
5248entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305249string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005250[clinic start generated code]*/
5251
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005252static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005253_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005254/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005255{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005256 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005257 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005258
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005259 buf = (const char *)view->buf;
5260 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005261 do {
5262 written = Py_MIN(len, INT_MAX);
5263 RAND_add(buf, (int)written, entropy);
5264 buf += written;
5265 len -= written;
5266 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005267 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005268}
5269
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005270static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005271PySSL_RAND(int len, int pseudo)
5272{
5273 int ok;
5274 PyObject *bytes;
5275 unsigned long err;
5276 const char *errstr;
5277 PyObject *v;
5278
Victor Stinner1e81a392013-12-19 16:47:04 +01005279 if (len < 0) {
5280 PyErr_SetString(PyExc_ValueError, "num must be positive");
5281 return NULL;
5282 }
5283
Victor Stinner99c8b162011-05-24 12:05:19 +02005284 bytes = PyBytes_FromStringAndSize(NULL, len);
5285 if (bytes == NULL)
5286 return NULL;
5287 if (pseudo) {
5288 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5289 if (ok == 0 || ok == 1)
5290 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5291 }
5292 else {
5293 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5294 if (ok == 1)
5295 return bytes;
5296 }
5297 Py_DECREF(bytes);
5298
5299 err = ERR_get_error();
5300 errstr = ERR_reason_error_string(err);
5301 v = Py_BuildValue("(ks)", err, errstr);
5302 if (v != NULL) {
5303 PyErr_SetObject(PySSLErrorObject, v);
5304 Py_DECREF(v);
5305 }
5306 return NULL;
5307}
5308
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005309/*[clinic input]
5310_ssl.RAND_bytes
5311 n: int
5312 /
5313
5314Generate n cryptographically strong pseudo-random bytes.
5315[clinic start generated code]*/
5316
Victor Stinner99c8b162011-05-24 12:05:19 +02005317static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005318_ssl_RAND_bytes_impl(PyObject *module, int n)
5319/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005320{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005321 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005322}
5323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005324/*[clinic input]
5325_ssl.RAND_pseudo_bytes
5326 n: int
5327 /
5328
5329Generate n pseudo-random bytes.
5330
5331Return a pair (bytes, is_cryptographic). is_cryptographic is True
5332if the bytes generated are cryptographically strong.
5333[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005334
5335static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005336_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5337/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005338{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005339 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005340}
5341
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005342/*[clinic input]
5343_ssl.RAND_status
5344
5345Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5346
5347It is necessary to seed the PRNG with RAND_add() on some platforms before
5348using the ssl() function.
5349[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005350
5351static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005352_ssl_RAND_status_impl(PyObject *module)
5353/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005354{
Christian Heimes217cfd12007-12-02 14:31:20 +00005355 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005356}
5357
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005358#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005359/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005360/*[clinic input]
5361_ssl.RAND_egd
5362 path: object(converter="PyUnicode_FSConverter")
5363 /
5364
5365Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5366
5367Returns number of bytes read. Raises SSLError if connection to EGD
5368fails or if it does not provide enough data to seed PRNG.
5369[clinic start generated code]*/
5370
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005371static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005372_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5373/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005374{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005375 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005376 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005377 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005378 PyErr_SetString(PySSLErrorObject,
5379 "EGD connection failed or EGD did not return "
5380 "enough data to seed the PRNG");
5381 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005382 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005383 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005384}
Christian Heimesa5d07652016-09-24 10:48:05 +02005385/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005386#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005387
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005388
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005389
5390/*[clinic input]
5391_ssl.get_default_verify_paths
5392
5393Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5394
5395The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5396[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005397
5398static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005399_ssl_get_default_verify_paths_impl(PyObject *module)
5400/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005401{
5402 PyObject *ofile_env = NULL;
5403 PyObject *ofile = NULL;
5404 PyObject *odir_env = NULL;
5405 PyObject *odir = NULL;
5406
Benjamin Petersond113c962015-07-18 10:59:13 -07005407#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005408 const char *tmp = (info); \
5409 target = NULL; \
5410 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5411 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5412 target = PyBytes_FromString(tmp); } \
5413 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005414 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005415
Benjamin Petersond113c962015-07-18 10:59:13 -07005416 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5417 CONVERT(X509_get_default_cert_file(), ofile);
5418 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5419 CONVERT(X509_get_default_cert_dir(), odir);
5420#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005421
Christian Heimes200bb1b2013-06-14 15:14:29 +02005422 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005423
5424 error:
5425 Py_XDECREF(ofile_env);
5426 Py_XDECREF(ofile);
5427 Py_XDECREF(odir_env);
5428 Py_XDECREF(odir);
5429 return NULL;
5430}
5431
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005432static PyObject*
5433asn1obj2py(ASN1_OBJECT *obj)
5434{
5435 int nid;
5436 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005437
5438 nid = OBJ_obj2nid(obj);
5439 if (nid == NID_undef) {
5440 PyErr_Format(PyExc_ValueError, "Unknown object");
5441 return NULL;
5442 }
5443 sn = OBJ_nid2sn(nid);
5444 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005445 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005446}
5447
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005448/*[clinic input]
5449_ssl.txt2obj
5450 txt: str
5451 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005452
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005453Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5454
5455By default objects are looked up by OID. With name=True short and
5456long name are also matched.
5457[clinic start generated code]*/
5458
5459static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005460_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5461/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005462{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005463 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005464 ASN1_OBJECT *obj;
5465
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005466 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5467 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005468 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005469 return NULL;
5470 }
5471 result = asn1obj2py(obj);
5472 ASN1_OBJECT_free(obj);
5473 return result;
5474}
5475
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005476/*[clinic input]
5477_ssl.nid2obj
5478 nid: int
5479 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005480
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005481Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5482[clinic start generated code]*/
5483
5484static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005485_ssl_nid2obj_impl(PyObject *module, int nid)
5486/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005487{
5488 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005489 ASN1_OBJECT *obj;
5490
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005491 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005492 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005493 return NULL;
5494 }
5495 obj = OBJ_nid2obj(nid);
5496 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005497 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005498 return NULL;
5499 }
5500 result = asn1obj2py(obj);
5501 ASN1_OBJECT_free(obj);
5502 return result;
5503}
5504
Christian Heimes46bebee2013-06-09 19:03:31 +02005505#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005506
5507static PyObject*
5508certEncodingType(DWORD encodingType)
5509{
5510 static PyObject *x509_asn = NULL;
5511 static PyObject *pkcs_7_asn = NULL;
5512
5513 if (x509_asn == NULL) {
5514 x509_asn = PyUnicode_InternFromString("x509_asn");
5515 if (x509_asn == NULL)
5516 return NULL;
5517 }
5518 if (pkcs_7_asn == NULL) {
5519 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5520 if (pkcs_7_asn == NULL)
5521 return NULL;
5522 }
5523 switch(encodingType) {
5524 case X509_ASN_ENCODING:
5525 Py_INCREF(x509_asn);
5526 return x509_asn;
5527 case PKCS_7_ASN_ENCODING:
5528 Py_INCREF(pkcs_7_asn);
5529 return pkcs_7_asn;
5530 default:
5531 return PyLong_FromLong(encodingType);
5532 }
5533}
5534
5535static PyObject*
5536parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5537{
5538 CERT_ENHKEY_USAGE *usage;
5539 DWORD size, error, i;
5540 PyObject *retval;
5541
5542 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5543 error = GetLastError();
5544 if (error == CRYPT_E_NOT_FOUND) {
5545 Py_RETURN_TRUE;
5546 }
5547 return PyErr_SetFromWindowsErr(error);
5548 }
5549
5550 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5551 if (usage == NULL) {
5552 return PyErr_NoMemory();
5553 }
5554
5555 /* Now get the actual enhanced usage property */
5556 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5557 PyMem_Free(usage);
5558 error = GetLastError();
5559 if (error == CRYPT_E_NOT_FOUND) {
5560 Py_RETURN_TRUE;
5561 }
5562 return PyErr_SetFromWindowsErr(error);
5563 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005564 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005565 if (retval == NULL) {
5566 goto error;
5567 }
5568 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5569 if (usage->rgpszUsageIdentifier[i]) {
5570 PyObject *oid;
5571 int err;
5572 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5573 if (oid == NULL) {
5574 Py_CLEAR(retval);
5575 goto error;
5576 }
5577 err = PySet_Add(retval, oid);
5578 Py_DECREF(oid);
5579 if (err == -1) {
5580 Py_CLEAR(retval);
5581 goto error;
5582 }
5583 }
5584 }
5585 error:
5586 PyMem_Free(usage);
5587 return retval;
5588}
5589
kctherookied93fbbf2019-03-29 00:59:06 +07005590static HCERTSTORE
5591ssl_collect_certificates(const char *store_name)
5592{
5593/* this function collects the system certificate stores listed in
5594 * system_stores into a collection certificate store for being
5595 * enumerated. The store must be readable to be added to the
5596 * store collection.
5597 */
5598
5599 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5600 static DWORD system_stores[] = {
5601 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5602 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5603 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5604 CERT_SYSTEM_STORE_CURRENT_USER,
5605 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5606 CERT_SYSTEM_STORE_SERVICES,
5607 CERT_SYSTEM_STORE_USERS};
5608 size_t i, storesAdded;
5609 BOOL result;
5610
5611 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5612 (HCRYPTPROV)NULL, 0, NULL);
5613 if (!hCollectionStore) {
5614 return NULL;
5615 }
5616 storesAdded = 0;
5617 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5618 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5619 (HCRYPTPROV)NULL,
5620 CERT_STORE_READONLY_FLAG |
5621 system_stores[i], store_name);
5622 if (hSystemStore) {
5623 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5624 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5625 if (result) {
5626 ++storesAdded;
5627 }
neoneneed701292019-09-09 21:33:43 +09005628 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005629 }
5630 }
5631 if (storesAdded == 0) {
5632 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5633 return NULL;
5634 }
5635
5636 return hCollectionStore;
5637}
5638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005639/*[clinic input]
5640_ssl.enum_certificates
5641 store_name: str
5642
5643Retrieve certificates from Windows' cert store.
5644
5645store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5646more cert storages, too. The function returns a list of (bytes,
5647encoding_type, trust) tuples. The encoding_type flag can be interpreted
5648with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5649a set of OIDs or the boolean True.
5650[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005651
Christian Heimes46bebee2013-06-09 19:03:31 +02005652static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005653_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5654/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005655{
kctherookied93fbbf2019-03-29 00:59:06 +07005656 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005657 PCCERT_CONTEXT pCertCtx = NULL;
5658 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005659 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005660
Christian Heimes915cd3f2019-09-09 18:06:55 +02005661 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005662 if (result == NULL) {
5663 return NULL;
5664 }
kctherookied93fbbf2019-03-29 00:59:06 +07005665 hCollectionStore = ssl_collect_certificates(store_name);
5666 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005667 Py_DECREF(result);
5668 return PyErr_SetFromWindowsErr(GetLastError());
5669 }
5670
kctherookied93fbbf2019-03-29 00:59:06 +07005671 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005672 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5673 pCertCtx->cbCertEncoded);
5674 if (!cert) {
5675 Py_CLEAR(result);
5676 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005677 }
Christian Heimes44109d72013-11-22 01:51:30 +01005678 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5679 Py_CLEAR(result);
5680 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005681 }
Christian Heimes44109d72013-11-22 01:51:30 +01005682 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5683 if (keyusage == Py_True) {
5684 Py_DECREF(keyusage);
5685 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005686 }
Christian Heimes44109d72013-11-22 01:51:30 +01005687 if (keyusage == NULL) {
5688 Py_CLEAR(result);
5689 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005690 }
Christian Heimes44109d72013-11-22 01:51:30 +01005691 if ((tup = PyTuple_New(3)) == NULL) {
5692 Py_CLEAR(result);
5693 break;
5694 }
5695 PyTuple_SET_ITEM(tup, 0, cert);
5696 cert = NULL;
5697 PyTuple_SET_ITEM(tup, 1, enc);
5698 enc = NULL;
5699 PyTuple_SET_ITEM(tup, 2, keyusage);
5700 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005701 if (PySet_Add(result, tup) == -1) {
5702 Py_CLEAR(result);
5703 Py_CLEAR(tup);
5704 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005705 }
5706 Py_CLEAR(tup);
5707 }
5708 if (pCertCtx) {
5709 /* loop ended with an error, need to clean up context manually */
5710 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005711 }
5712
5713 /* In error cases cert, enc and tup may not be NULL */
5714 Py_XDECREF(cert);
5715 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005716 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005717 Py_XDECREF(tup);
5718
kctherookied93fbbf2019-03-29 00:59:06 +07005719 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5720 associated with the store, in this case our collection store and the
5721 associated system stores. */
5722 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005723 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005724 Py_XDECREF(result);
5725 return PyErr_SetFromWindowsErr(GetLastError());
5726 }
kctherookied93fbbf2019-03-29 00:59:06 +07005727
Christian Heimes915cd3f2019-09-09 18:06:55 +02005728 /* convert set to list */
5729 if (result == NULL) {
5730 return NULL;
5731 } else {
5732 PyObject *lst = PySequence_List(result);
5733 Py_DECREF(result);
5734 return lst;
5735 }
Christian Heimes44109d72013-11-22 01:51:30 +01005736}
5737
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005738/*[clinic input]
5739_ssl.enum_crls
5740 store_name: str
5741
5742Retrieve CRLs from Windows' cert store.
5743
5744store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5745more cert storages, too. The function returns a list of (bytes,
5746encoding_type) tuples. The encoding_type flag can be interpreted with
5747X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5748[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005749
5750static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005751_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5752/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005753{
kctherookied93fbbf2019-03-29 00:59:06 +07005754 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005755 PCCRL_CONTEXT pCrlCtx = NULL;
5756 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5757 PyObject *result = NULL;
5758
Christian Heimes915cd3f2019-09-09 18:06:55 +02005759 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005760 if (result == NULL) {
5761 return NULL;
5762 }
kctherookied93fbbf2019-03-29 00:59:06 +07005763 hCollectionStore = ssl_collect_certificates(store_name);
5764 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005765 Py_DECREF(result);
5766 return PyErr_SetFromWindowsErr(GetLastError());
5767 }
Christian Heimes44109d72013-11-22 01:51:30 +01005768
kctherookied93fbbf2019-03-29 00:59:06 +07005769 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005770 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5771 pCrlCtx->cbCrlEncoded);
5772 if (!crl) {
5773 Py_CLEAR(result);
5774 break;
5775 }
5776 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5777 Py_CLEAR(result);
5778 break;
5779 }
5780 if ((tup = PyTuple_New(2)) == NULL) {
5781 Py_CLEAR(result);
5782 break;
5783 }
5784 PyTuple_SET_ITEM(tup, 0, crl);
5785 crl = NULL;
5786 PyTuple_SET_ITEM(tup, 1, enc);
5787 enc = NULL;
5788
Christian Heimes915cd3f2019-09-09 18:06:55 +02005789 if (PySet_Add(result, tup) == -1) {
5790 Py_CLEAR(result);
5791 Py_CLEAR(tup);
5792 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005793 }
5794 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005795 }
Christian Heimes44109d72013-11-22 01:51:30 +01005796 if (pCrlCtx) {
5797 /* loop ended with an error, need to clean up context manually */
5798 CertFreeCRLContext(pCrlCtx);
5799 }
5800
5801 /* In error cases cert, enc and tup may not be NULL */
5802 Py_XDECREF(crl);
5803 Py_XDECREF(enc);
5804 Py_XDECREF(tup);
5805
kctherookied93fbbf2019-03-29 00:59:06 +07005806 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5807 associated with the store, in this case our collection store and the
5808 associated system stores. */
5809 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005810 /* This error case might shadow another exception.*/
5811 Py_XDECREF(result);
5812 return PyErr_SetFromWindowsErr(GetLastError());
5813 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005814 /* convert set to list */
5815 if (result == NULL) {
5816 return NULL;
5817 } else {
5818 PyObject *lst = PySequence_List(result);
5819 Py_DECREF(result);
5820 return lst;
5821 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005822}
Christian Heimes44109d72013-11-22 01:51:30 +01005823
5824#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005825
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005826/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005827static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005828 _SSL__TEST_DECODE_CERT_METHODDEF
5829 _SSL_RAND_ADD_METHODDEF
5830 _SSL_RAND_BYTES_METHODDEF
5831 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5832 _SSL_RAND_EGD_METHODDEF
5833 _SSL_RAND_STATUS_METHODDEF
5834 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5835 _SSL_ENUM_CERTIFICATES_METHODDEF
5836 _SSL_ENUM_CRLS_METHODDEF
5837 _SSL_TXT2OBJ_METHODDEF
5838 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005839 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005840};
5841
5842
Christian Heimes598894f2016-09-05 23:19:05 +02005843#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005844
5845/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005846 * of the Python C thread library
5847 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5848 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005849
5850static PyThread_type_lock *_ssl_locks = NULL;
5851
Christian Heimes4d98ca92013-08-19 17:36:29 +02005852#if OPENSSL_VERSION_NUMBER >= 0x10000000
5853/* use new CRYPTO_THREADID API. */
5854static void
5855_ssl_threadid_callback(CRYPTO_THREADID *id)
5856{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005857 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005858}
5859#else
5860/* deprecated CRYPTO_set_id_callback() API. */
5861static unsigned long
5862_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005863 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005864}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005865#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005866
Bill Janssen6e027db2007-11-15 22:23:56 +00005867static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005868 (int mode, int n, const char *file, int line) {
5869 /* this function is needed to perform locking on shared data
5870 structures. (Note that OpenSSL uses a number of global data
5871 structures that will be implicitly shared whenever multiple
5872 threads use OpenSSL.) Multi-threaded applications will
5873 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005874
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005875 locking_function() must be able to handle up to
5876 CRYPTO_num_locks() different mutex locks. It sets the n-th
5877 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 file and line are the file number of the function setting the
5880 lock. They can be useful for debugging.
5881 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005883 if ((_ssl_locks == NULL) ||
5884 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5885 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005887 if (mode & CRYPTO_LOCK) {
5888 PyThread_acquire_lock(_ssl_locks[n], 1);
5889 } else {
5890 PyThread_release_lock(_ssl_locks[n]);
5891 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005892}
5893
5894static int _setup_ssl_threads(void) {
5895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005896 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005897
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005898 if (_ssl_locks == NULL) {
5899 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005900 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5901 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005902 if (_ssl_locks == NULL) {
5903 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005904 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005905 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005906 for (i = 0; i < _ssl_locks_count; i++) {
5907 _ssl_locks[i] = PyThread_allocate_lock();
5908 if (_ssl_locks[i] == NULL) {
5909 unsigned int j;
5910 for (j = 0; j < i; j++) {
5911 PyThread_free_lock(_ssl_locks[j]);
5912 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005913 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005914 return 0;
5915 }
5916 }
5917 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005918#if OPENSSL_VERSION_NUMBER >= 0x10000000
5919 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5920#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005921 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005922#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005923 }
5924 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005925}
5926
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005927#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005928
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005929PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005930"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005931for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005932
Martin v. Löwis1a214512008-06-11 05:26:20 +00005933
5934static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005935 PyModuleDef_HEAD_INIT,
5936 "_ssl",
5937 module_doc,
5938 -1,
5939 PySSL_methods,
5940 NULL,
5941 NULL,
5942 NULL,
5943 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005944};
5945
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005946
5947static void
5948parse_openssl_version(unsigned long libver,
5949 unsigned int *major, unsigned int *minor,
5950 unsigned int *fix, unsigned int *patch,
5951 unsigned int *status)
5952{
5953 *status = libver & 0xF;
5954 libver >>= 4;
5955 *patch = libver & 0xFF;
5956 libver >>= 8;
5957 *fix = libver & 0xFF;
5958 libver >>= 8;
5959 *minor = libver & 0xFF;
5960 libver >>= 8;
5961 *major = libver & 0xFF;
5962}
5963
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005964PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005965PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005966{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005967 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005968 unsigned long libver;
5969 unsigned int major, minor, fix, patch, status;
5970 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005971 struct py_ssl_error_code *errcode;
5972 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005973
Antoine Pitrou152efa22010-05-16 18:19:27 +00005974 if (PyType_Ready(&PySSLContext_Type) < 0)
5975 return NULL;
5976 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005977 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005978 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5979 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005980 if (PyType_Ready(&PySSLSession_Type) < 0)
5981 return NULL;
5982
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005984 m = PyModule_Create(&_sslmodule);
5985 if (m == NULL)
5986 return NULL;
5987 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005989 /* Load _socket module and its C API */
5990 socket_api = PySocketModule_ImportModuleAndAPI();
5991 if (!socket_api)
5992 return NULL;
5993 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005994
Christian Heimesc941e622017-09-05 15:47:11 +02005995#ifndef OPENSSL_VERSION_1_1
5996 /* Load all algorithms and initialize cpuid */
5997 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005998 /* Init OpenSSL */
5999 SSL_load_error_strings();
6000 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006001#endif
6002
Christian Heimes598894f2016-09-05 23:19:05 +02006003#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006004 /* note that this will start threading if not already started */
6005 if (!_setup_ssl_threads()) {
6006 return NULL;
6007 }
Christian Heimes598894f2016-09-05 23:19:05 +02006008#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
6009 /* OpenSSL 1.1.0 builtin thread support is enabled */
6010 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006011#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006013 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006014 sslerror_type_slots[0].pfunc = PyExc_OSError;
6015 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006016 if (PySSLErrorObject == NULL)
6017 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006018
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006019 /* ssl.CertificateError used to be a subclass of ValueError */
6020 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6021 if (bases == NULL)
6022 return NULL;
6023 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6024 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6025 bases, NULL);
6026 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006027 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6028 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6029 PySSLErrorObject, NULL);
6030 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6031 "ssl.SSLWantReadError", SSLWantReadError_doc,
6032 PySSLErrorObject, NULL);
6033 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6034 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6035 PySSLErrorObject, NULL);
6036 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6037 "ssl.SSLSyscallError", SSLSyscallError_doc,
6038 PySSLErrorObject, NULL);
6039 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6040 "ssl.SSLEOFError", SSLEOFError_doc,
6041 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006042 if (PySSLCertVerificationErrorObject == NULL
6043 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006044 || PySSLWantReadErrorObject == NULL
6045 || PySSLWantWriteErrorObject == NULL
6046 || PySSLSyscallErrorObject == NULL
6047 || PySSLEOFErrorObject == NULL)
6048 return NULL;
6049 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006050 || PyDict_SetItemString(d, "SSLCertVerificationError",
6051 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006052 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6053 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6054 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6055 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6056 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006057 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006058 if (PyDict_SetItemString(d, "_SSLContext",
6059 (PyObject *)&PySSLContext_Type) != 0)
6060 return NULL;
6061 if (PyDict_SetItemString(d, "_SSLSocket",
6062 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006063 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006064 if (PyDict_SetItemString(d, "MemoryBIO",
6065 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6066 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006067 if (PyDict_SetItemString(d, "SSLSession",
6068 (PyObject *)&PySSLSession_Type) != 0)
6069 return NULL;
6070
Christian Heimes892d66e2018-01-29 14:10:18 +01006071 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6072 PY_SSL_DEFAULT_CIPHER_STRING);
6073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006074 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6075 PY_SSL_ERROR_ZERO_RETURN);
6076 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6077 PY_SSL_ERROR_WANT_READ);
6078 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6079 PY_SSL_ERROR_WANT_WRITE);
6080 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6081 PY_SSL_ERROR_WANT_X509_LOOKUP);
6082 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6083 PY_SSL_ERROR_SYSCALL);
6084 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6085 PY_SSL_ERROR_SSL);
6086 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6087 PY_SSL_ERROR_WANT_CONNECT);
6088 /* non ssl.h errorcodes */
6089 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6090 PY_SSL_ERROR_EOF);
6091 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6092 PY_SSL_ERROR_INVALID_ERROR_CODE);
6093 /* cert requirements */
6094 PyModule_AddIntConstant(m, "CERT_NONE",
6095 PY_SSL_CERT_NONE);
6096 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6097 PY_SSL_CERT_OPTIONAL);
6098 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6099 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006100 /* CRL verification for verification_flags */
6101 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6102 0);
6103 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6104 X509_V_FLAG_CRL_CHECK);
6105 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6106 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6107 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6108 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006109#ifdef X509_V_FLAG_TRUSTED_FIRST
6110 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6111 X509_V_FLAG_TRUSTED_FIRST);
6112#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006113
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006114 /* Alert Descriptions from ssl.h */
6115 /* note RESERVED constants no longer intended for use have been removed */
6116 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6117
6118#define ADD_AD_CONSTANT(s) \
6119 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6120 SSL_AD_##s)
6121
6122 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6123 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6124 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6125 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6126 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6127 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6128 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6129 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6130 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6131 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6132 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6133 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6134 ADD_AD_CONSTANT(UNKNOWN_CA);
6135 ADD_AD_CONSTANT(ACCESS_DENIED);
6136 ADD_AD_CONSTANT(DECODE_ERROR);
6137 ADD_AD_CONSTANT(DECRYPT_ERROR);
6138 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6139 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6140 ADD_AD_CONSTANT(INTERNAL_ERROR);
6141 ADD_AD_CONSTANT(USER_CANCELLED);
6142 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006143 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006144#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6145 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6146#endif
6147#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6148 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6149#endif
6150#ifdef SSL_AD_UNRECOGNIZED_NAME
6151 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6152#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006153#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6154 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6155#endif
6156#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6157 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6158#endif
6159#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6160 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6161#endif
6162
6163#undef ADD_AD_CONSTANT
6164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006165 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006166#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006167 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6168 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006169#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006170#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006171 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6172 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006173#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006174 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006175 PY_SSL_VERSION_TLS);
6176 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6177 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006178 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6179 PY_SSL_VERSION_TLS_CLIENT);
6180 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6181 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006182 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6183 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006184#if HAVE_TLSv1_2
6185 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6186 PY_SSL_VERSION_TLS1_1);
6187 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6188 PY_SSL_VERSION_TLS1_2);
6189#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006190
Antoine Pitroub5218772010-05-21 09:56:06 +00006191 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006192 PyModule_AddIntConstant(m, "OP_ALL",
6193 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006194 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6195 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6196 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006197#if HAVE_TLSv1_2
6198 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6199 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6200#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006201#ifdef SSL_OP_NO_TLSv1_3
6202 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6203#else
6204 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6205#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006206 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6207 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006208 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006209 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006210#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006211 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006212#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006213#ifdef SSL_OP_NO_COMPRESSION
6214 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6215 SSL_OP_NO_COMPRESSION);
6216#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006217#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6218 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6219 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6220#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006221#ifdef SSL_OP_NO_RENEGOTIATION
6222 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6223 SSL_OP_NO_RENEGOTIATION);
6224#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006225
Christian Heimes61d478c2018-01-27 15:51:38 +01006226#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6227 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6228 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6229#endif
6230#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6231 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6232 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6233#endif
6234#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6235 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6236 X509_CHECK_FLAG_NO_WILDCARDS);
6237#endif
6238#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6239 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6240 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6241#endif
6242#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6243 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6244 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6245#endif
6246#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6247 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6248 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6249#endif
6250
Christian Heimes698dde12018-02-27 11:54:43 +01006251 /* protocol versions */
6252 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6253 PY_PROTO_MINIMUM_SUPPORTED);
6254 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6255 PY_PROTO_MAXIMUM_SUPPORTED);
6256 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6257 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6258 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6259 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6260 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006261
Victor Stinnerb37672d2018-11-22 03:37:50 +01006262#define addbool(m, key, value) \
6263 do { \
6264 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6265 Py_INCREF(bool_obj); \
6266 PyModule_AddObject((m), (key), bool_obj); \
6267 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006268
6269#if HAVE_SNI
6270 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006271#else
Christian Heimes698dde12018-02-27 11:54:43 +01006272 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006273#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006274
6275 addbool(m, "HAS_TLS_UNIQUE", 1);
6276
6277#ifndef OPENSSL_NO_ECDH
6278 addbool(m, "HAS_ECDH", 1);
6279#else
6280 addbool(m, "HAS_ECDH", 0);
6281#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006282
Christian Heimes29eab552018-02-25 12:31:33 +01006283#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006284 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006285#else
Christian Heimes698dde12018-02-27 11:54:43 +01006286 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006287#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006288
Christian Heimes29eab552018-02-25 12:31:33 +01006289#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006290 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006291#else
Christian Heimes698dde12018-02-27 11:54:43 +01006292 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006293#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006294
6295#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6296 addbool(m, "HAS_SSLv2", 1);
6297#else
6298 addbool(m, "HAS_SSLv2", 0);
6299#endif
6300
6301#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6302 addbool(m, "HAS_SSLv3", 1);
6303#else
6304 addbool(m, "HAS_SSLv3", 0);
6305#endif
6306
6307#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6308 addbool(m, "HAS_TLSv1", 1);
6309#else
6310 addbool(m, "HAS_TLSv1", 0);
6311#endif
6312
6313#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6314 addbool(m, "HAS_TLSv1_1", 1);
6315#else
6316 addbool(m, "HAS_TLSv1_1", 0);
6317#endif
6318
6319#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6320 addbool(m, "HAS_TLSv1_2", 1);
6321#else
6322 addbool(m, "HAS_TLSv1_2", 0);
6323#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006324
Christian Heimescb5b68a2017-09-07 18:07:00 -07006325#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006326 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006327#else
Christian Heimes698dde12018-02-27 11:54:43 +01006328 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006329#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006330
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006331 /* Mappings for error codes */
6332 err_codes_to_names = PyDict_New();
6333 err_names_to_codes = PyDict_New();
6334 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6335 return NULL;
6336 errcode = error_codes;
6337 while (errcode->mnemonic != NULL) {
6338 PyObject *mnemo, *key;
6339 mnemo = PyUnicode_FromString(errcode->mnemonic);
6340 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6341 if (mnemo == NULL || key == NULL)
6342 return NULL;
6343 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6344 return NULL;
6345 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6346 return NULL;
6347 Py_DECREF(key);
6348 Py_DECREF(mnemo);
6349 errcode++;
6350 }
6351 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6352 return NULL;
6353 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6354 return NULL;
6355
6356 lib_codes_to_names = PyDict_New();
6357 if (lib_codes_to_names == NULL)
6358 return NULL;
6359 libcode = library_codes;
6360 while (libcode->library != NULL) {
6361 PyObject *mnemo, *key;
6362 key = PyLong_FromLong(libcode->code);
6363 mnemo = PyUnicode_FromString(libcode->library);
6364 if (key == NULL || mnemo == NULL)
6365 return NULL;
6366 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6367 return NULL;
6368 Py_DECREF(key);
6369 Py_DECREF(mnemo);
6370 libcode++;
6371 }
6372 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6373 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006374
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006375 /* OpenSSL version */
6376 /* SSLeay() gives us the version of the library linked against,
6377 which could be different from the headers version.
6378 */
6379 libver = SSLeay();
6380 r = PyLong_FromUnsignedLong(libver);
6381 if (r == NULL)
6382 return NULL;
6383 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6384 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006385 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006386 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6387 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6388 return NULL;
6389 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6390 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6391 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006392
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006393 libver = OPENSSL_VERSION_NUMBER;
6394 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6395 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6396 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6397 return NULL;
6398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006399 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006400}