blob: 1da65eae7a8b4cf79077cd590bedf4388401e5ef [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Christian Heimes387c7442020-05-15 22:36:51 +020078#ifndef OPENSSL_THREADS
79# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
80#endif
81
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010082/* SSL error object */
83static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070084static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010085static PyObject *PySSLZeroReturnErrorObject;
86static PyObject *PySSLWantReadErrorObject;
87static PyObject *PySSLWantWriteErrorObject;
88static PyObject *PySSLSyscallErrorObject;
89static PyObject *PySSLEOFErrorObject;
90
91/* Error mappings */
92static PyObject *err_codes_to_names;
93static PyObject *err_names_to_codes;
94static PyObject *lib_codes_to_names;
95
96struct py_ssl_error_code {
97 const char *mnemonic;
98 int library, reason;
99};
100struct py_ssl_library_code {
101 const char *library;
102 int code;
103};
104
Steve Dower68d663c2017-07-17 11:15:48 +0200105#if defined(MS_WINDOWS) && defined(Py_DEBUG)
106/* Debug builds on Windows rely on getting errno directly from OpenSSL.
107 * However, because it uses a different CRT, we need to transfer the
108 * value of errno from OpenSSL into our debug CRT.
109 *
110 * Don't be fooled - this is horribly ugly code. The only reasonable
111 * alternative is to do both debug and release builds of OpenSSL, which
112 * requires much uglier code to transform their automatically generated
113 * makefile. This is the lesser of all the evils.
114 */
115
116static void _PySSLFixErrno(void) {
117 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
118 if (!ucrtbase) {
119 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
120 * have a catastrophic failure, but this function is not the
121 * place to raise it. */
122 return;
123 }
124
125 typedef int *(__stdcall *errno_func)(void);
126 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
127 if (ssl_errno) {
128 errno = *ssl_errno();
129 *ssl_errno() = 0;
130 } else {
131 errno = ENOTRECOVERABLE;
132 }
133}
134
135#undef _PySSL_FIX_ERRNO
136#define _PySSL_FIX_ERRNO _PySSLFixErrno()
137#endif
138
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100139/* Include generated data (error codes) */
140#include "_ssl_data.h"
141
Christian Heimes598894f2016-09-05 23:19:05 +0200142#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
143# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100144# define PY_OPENSSL_1_1_API 1
145#endif
146
147/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
148#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
149# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200150#endif
151
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100152/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
153 http://www.openssl.org/news/changelog.html
154 */
155#if OPENSSL_VERSION_NUMBER >= 0x10001000L
156# define HAVE_TLSv1_2 1
157#else
158# define HAVE_TLSv1_2 0
159#endif
160
Christian Heimes470fba12013-11-28 15:12:15 +0100161/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100162 * This includes the SSL_set_SSL_CTX() function.
163 */
164#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
165# define HAVE_SNI 1
166#else
167# define HAVE_SNI 0
168#endif
169
Benjamin Petersond3308222015-09-27 00:09:02 -0700170#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100171# define HAVE_ALPN 1
172#else
173# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500174#endif
175
Christian Heimes6cdb7952018-02-24 22:12:40 +0100176/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
177 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
178 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
179 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100180 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100181 */
182#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100183# define HAVE_NPN 0
184#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
185# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100186#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100187# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100188#else
Christian Heimes29eab552018-02-25 12:31:33 +0100189# define HAVE_NPN 0
190#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100191
Christian Heimesc7f70692019-05-31 11:44:05 +0200192#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
193#define HAVE_OPENSSL_KEYLOG 1
194#endif
195
Victor Stinner524714e2016-07-22 17:43:59 +0200196#ifndef INVALID_SOCKET /* MS defines this */
197#define INVALID_SOCKET (-1)
198#endif
199
Christian Heimes4ca07392018-03-24 15:41:37 +0100200/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
201#ifndef OPENSSL_VERSION_1_1
202#define HAVE_OPENSSL_CRYPTO_LOCK
203#endif
204
205#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200206#define OPENSSL_NO_SSL2
207#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100208
209#ifndef PY_OPENSSL_1_1_API
210/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200211
212#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200213#define TLS_client_method SSLv23_client_method
214#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200215
216static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
217{
218 return ne->set;
219}
220
221#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200222/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200223static int COMP_get_type(const COMP_METHOD *meth)
224{
225 return meth->type;
226}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200227/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200228#endif
229
230static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
231{
232 return ctx->default_passwd_callback;
233}
234
235static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
236{
237 return ctx->default_passwd_callback_userdata;
238}
239
240static int X509_OBJECT_get_type(X509_OBJECT *x)
241{
242 return x->type;
243}
244
245static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
246{
247 return x->data.x509;
248}
249
250static int BIO_up_ref(BIO *b)
251{
252 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
253 return 1;
254}
255
256static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
257 return store->objs;
258}
259
Christian Heimes99a65702016-09-10 23:44:53 +0200260static int
261SSL_SESSION_has_ticket(const SSL_SESSION *s)
262{
263 return (s->tlsext_ticklen > 0) ? 1 : 0;
264}
265
266static unsigned long
267SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
268{
269 return s->tlsext_tick_lifetime_hint;
270}
271
Christian Heimes4ca07392018-03-24 15:41:37 +0100272#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200273
Christian Heimes892d66e2018-01-29 14:10:18 +0100274/* Default cipher suites */
275#ifndef PY_SSL_DEFAULT_CIPHERS
276#define PY_SSL_DEFAULT_CIPHERS 1
277#endif
278
279#if PY_SSL_DEFAULT_CIPHERS == 0
280 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
281 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
282 #endif
283#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200284/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100285 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
286 * !aNULL:!eNULL: really no NULL ciphers
287 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
288 * !aDSS: no authentication with discrete logarithm DSA algorithm
289 * !SRP:!PSK: no secure remote password or pre-shared key authentication
290 */
291 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
292#elif PY_SSL_DEFAULT_CIPHERS == 2
293/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
294 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
295#else
296 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
297#endif
298
Christian Heimes598894f2016-09-05 23:19:05 +0200299
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000300enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000301 /* these mirror ssl.h */
302 PY_SSL_ERROR_NONE,
303 PY_SSL_ERROR_SSL,
304 PY_SSL_ERROR_WANT_READ,
305 PY_SSL_ERROR_WANT_WRITE,
306 PY_SSL_ERROR_WANT_X509_LOOKUP,
307 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
308 PY_SSL_ERROR_ZERO_RETURN,
309 PY_SSL_ERROR_WANT_CONNECT,
310 /* start of non ssl.h errorcodes */
311 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
312 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
313 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000314};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315
Thomas Woutersed03b412007-08-28 21:37:11 +0000316enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000317 PY_SSL_CLIENT,
318 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000319};
320
321enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000322 PY_SSL_CERT_NONE,
323 PY_SSL_CERT_OPTIONAL,
324 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000325};
326
327enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000328 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200329 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100331#if HAVE_TLSv1_2
332 PY_SSL_VERSION_TLS1,
333 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200334 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100335#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200336 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000337#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200338 PY_SSL_VERSION_TLS_CLIENT=0x10,
339 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100340};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200341
Christian Heimes698dde12018-02-27 11:54:43 +0100342enum py_proto_version {
343 PY_PROTO_MINIMUM_SUPPORTED = -2,
344 PY_PROTO_SSLv3 = SSL3_VERSION,
345 PY_PROTO_TLSv1 = TLS1_VERSION,
346 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
347 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
348#ifdef TLS1_3_VERSION
349 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
350#else
351 PY_PROTO_TLSv1_3 = 0x304,
352#endif
353 PY_PROTO_MAXIMUM_SUPPORTED = -1,
354
355/* OpenSSL has no dedicated API to set the minimum version to the maximum
356 * available version, and the other way around. We have to figure out the
357 * minimum and maximum available version on our own and hope for the best.
358 */
359#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
361#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
362 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
363#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
364 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
365#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
366 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
367#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
368 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
369#else
370 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
371#endif
372
373#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
375#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
376 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
377#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
378 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
379#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
380 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
381#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
382 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
383#else
384 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
385#endif
386};
387
388
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000389/* serves as a flag to see whether we've initialized the SSL thread support. */
390/* 0 means no, greater than 0 means yes */
391
392static unsigned int _ssl_locks_count = 0;
393
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000394/* SSL socket object */
395
396#define X509_NAME_MAXLEN 256
397
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000398/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
399 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
400 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
401#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000402# define HAVE_SSL_CTX_CLEAR_OPTIONS
403#else
404# undef HAVE_SSL_CTX_CLEAR_OPTIONS
405#endif
406
Antoine Pitroud6494802011-07-21 01:11:30 +0200407/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
408 * older SSL, but let's be safe */
409#define PySSL_CB_MAXLEN 128
410
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100411
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000412typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000413 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000414 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100415#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500416 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100417 int npn_protocols_len;
418#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100419#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500420 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300421 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500422#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100423#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100424 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100425#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100426 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100427 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
428 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
429 */
430 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100431 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200432#ifdef TLS1_3_VERSION
433 int post_handshake_auth;
434#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200435 PyObject *msg_cb;
436#ifdef HAVE_OPENSSL_KEYLOG
437 PyObject *keylog_filename;
438 BIO *keylog_bio;
439#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000440} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000441
Antoine Pitrou152efa22010-05-16 18:19:27 +0000442typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700443 int ssl; /* last seen error from SSL */
444 int c; /* last seen error from libc */
445#ifdef MS_WINDOWS
446 int ws; /* last seen error from winsock */
447#endif
448} _PySSLError;
449
450typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000451 PyObject_HEAD
452 PyObject *Socket; /* weakref to socket on which we're layered */
453 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100454 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200455 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200456 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200457 PyObject *owner; /* Python level "owner" passed to servername callback */
458 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700459 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200460 /* Some SSL callbacks don't have error reporting. Callback wrappers
461 * store exception information on the socket. The handshake, read, write,
462 * and shutdown methods check for chained exceptions.
463 */
464 PyObject *exc_type;
465 PyObject *exc_value;
466 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000467} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000468
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200469typedef struct {
470 PyObject_HEAD
471 BIO *bio;
472 int eof_written;
473} PySSLMemoryBIO;
474
Christian Heimes99a65702016-09-10 23:44:53 +0200475typedef struct {
476 PyObject_HEAD
477 SSL_SESSION *session;
478 PySSLContext *ctx;
479} PySSLSession;
480
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481static PyTypeObject PySSLContext_Type;
482static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200483static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200484static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000485
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700486static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
487{
488 _PySSLError err = { 0 };
489 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700490#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700491 err.ws = WSAGetLastError();
492 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700493#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700494 err.c = errno;
495 err.ssl = SSL_get_error(ssl, retcode);
496 }
497 return err;
498}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700499
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300500/*[clinic input]
501module _ssl
502class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
503class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
504class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200505class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300506[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200507/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300508
509#include "clinic/_ssl.c.h"
510
Victor Stinner14690702015-04-06 22:46:13 +0200511static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000512
Christian Heimes141c5e82018-02-24 21:10:57 +0100513static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
514static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000515#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200516#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200517#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000518
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000519typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000520 SOCKET_IS_NONBLOCKING,
521 SOCKET_IS_BLOCKING,
522 SOCKET_HAS_TIMED_OUT,
523 SOCKET_HAS_BEEN_CLOSED,
524 SOCKET_TOO_LARGE_FOR_SELECT,
525 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000526} timeout_state;
527
Thomas Woutersed03b412007-08-28 21:37:11 +0000528/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000529#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200530#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000531
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200532/* Get the socket from a PySSLSocket, if it has one */
533#define GET_SOCKET(obj) ((obj)->Socket ? \
534 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535
Victor Stinner14690702015-04-06 22:46:13 +0200536/* If sock is NULL, use a timeout of 0 second */
537#define GET_SOCKET_TIMEOUT(sock) \
538 ((sock != NULL) ? (sock)->sock_timeout : 0)
539
Christian Heimesc7f70692019-05-31 11:44:05 +0200540#include "_ssl/debughelpers.c"
541
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200542/*
543 * SSL errors.
544 */
545
546PyDoc_STRVAR(SSLError_doc,
547"An error occurred in the SSL implementation.");
548
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700549PyDoc_STRVAR(SSLCertVerificationError_doc,
550"A certificate could not be verified.");
551
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200552PyDoc_STRVAR(SSLZeroReturnError_doc,
553"SSL/TLS session closed cleanly.");
554
555PyDoc_STRVAR(SSLWantReadError_doc,
556"Non-blocking SSL socket needs to read more data\n"
557"before the requested operation can be completed.");
558
559PyDoc_STRVAR(SSLWantWriteError_doc,
560"Non-blocking SSL socket needs to write more data\n"
561"before the requested operation can be completed.");
562
563PyDoc_STRVAR(SSLSyscallError_doc,
564"System error when attempting SSL operation.");
565
566PyDoc_STRVAR(SSLEOFError_doc,
567"SSL/TLS connection terminated abruptly.");
568
569static PyObject *
570SSLError_str(PyOSErrorObject *self)
571{
572 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
573 Py_INCREF(self->strerror);
574 return self->strerror;
575 }
576 else
577 return PyObject_Str(self->args);
578}
579
580static PyType_Slot sslerror_type_slots[] = {
581 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900582 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200583 {Py_tp_str, SSLError_str},
584 {0, 0},
585};
586
587static PyType_Spec sslerror_type_spec = {
588 "ssl.SSLError",
589 sizeof(PyOSErrorObject),
590 0,
591 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
592 sslerror_type_slots
593};
594
595static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700596fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
597 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200598{
599 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700600 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200601 PyObject *init_value, *msg, *key;
602 _Py_IDENTIFIER(reason);
603 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700604 _Py_IDENTIFIER(verify_message);
605 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200606
607 if (errcode != 0) {
608 int lib, reason;
609
610 lib = ERR_GET_LIB(errcode);
611 reason = ERR_GET_REASON(errcode);
612 key = Py_BuildValue("ii", lib, reason);
613 if (key == NULL)
614 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300615 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200616 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300617 if (reason_obj == NULL && PyErr_Occurred()) {
618 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200619 }
620 key = PyLong_FromLong(lib);
621 if (key == NULL)
622 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300623 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200624 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300625 if (lib_obj == NULL && PyErr_Occurred()) {
626 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200627 }
628 if (errstr == NULL)
629 errstr = ERR_reason_error_string(errcode);
630 }
631 if (errstr == NULL)
632 errstr = "unknown error";
633
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700634 /* verify code for cert validation error */
635 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
636 const char *verify_str = NULL;
637 long verify_code;
638
639 verify_code = SSL_get_verify_result(sslsock->ssl);
640 verify_code_obj = PyLong_FromLong(verify_code);
641 if (verify_code_obj == NULL) {
642 goto fail;
643 }
644
645 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700646#ifdef X509_V_ERR_HOSTNAME_MISMATCH
647 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700648 case X509_V_ERR_HOSTNAME_MISMATCH:
649 verify_obj = PyUnicode_FromFormat(
650 "Hostname mismatch, certificate is not valid for '%S'.",
651 sslsock->server_hostname
652 );
653 break;
Christian Heimes09153602017-09-08 14:47:58 -0700654#endif
655#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700656 case X509_V_ERR_IP_ADDRESS_MISMATCH:
657 verify_obj = PyUnicode_FromFormat(
658 "IP address mismatch, certificate is not valid for '%S'.",
659 sslsock->server_hostname
660 );
661 break;
Christian Heimes09153602017-09-08 14:47:58 -0700662#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700663 default:
664 verify_str = X509_verify_cert_error_string(verify_code);
665 if (verify_str != NULL) {
666 verify_obj = PyUnicode_FromString(verify_str);
667 } else {
668 verify_obj = Py_None;
669 Py_INCREF(verify_obj);
670 }
671 break;
672 }
673 if (verify_obj == NULL) {
674 goto fail;
675 }
676 }
677
678 if (verify_obj && reason_obj && lib_obj)
679 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
680 lib_obj, reason_obj, errstr, verify_obj,
681 lineno);
682 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200683 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
684 lib_obj, reason_obj, errstr, lineno);
685 else if (lib_obj)
686 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
687 lib_obj, errstr, lineno);
688 else
689 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200690 if (msg == NULL)
691 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100692
Paul Monsonfb7e7502019-05-15 15:38:55 -0700693 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100694 if (init_value == NULL)
695 goto fail;
696
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200697 err_value = PyObject_CallObject(type, init_value);
698 Py_DECREF(init_value);
699 if (err_value == NULL)
700 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100701
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200702 if (reason_obj == NULL)
703 reason_obj = Py_None;
704 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
705 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700706
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200707 if (lib_obj == NULL)
708 lib_obj = Py_None;
709 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
710 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700711
712 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
713 /* Only set verify code / message for SSLCertVerificationError */
714 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
715 verify_code_obj))
716 goto fail;
717 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
718 goto fail;
719 }
720
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200721 PyErr_SetObject(type, err_value);
722fail:
723 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700724 Py_XDECREF(verify_code_obj);
725 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200726}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000727
Christian Heimesc7f70692019-05-31 11:44:05 +0200728static int
729PySSL_ChainExceptions(PySSLSocket *sslsock) {
730 if (sslsock->exc_type == NULL)
731 return 0;
732
733 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
734 sslsock->exc_type = NULL;
735 sslsock->exc_value = NULL;
736 sslsock->exc_tb = NULL;
737 return -1;
738}
739
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000740static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700741PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000742{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200743 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200744 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700745 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200747 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200750 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000751
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700752 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700753 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000754
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700755 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200757 errstr = "TLS/SSL connection has been closed (EOF)";
758 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 p = PY_SSL_ERROR_ZERO_RETURN;
760 break;
761 case SSL_ERROR_WANT_READ:
762 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200763 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 p = PY_SSL_ERROR_WANT_READ;
765 break;
766 case SSL_ERROR_WANT_WRITE:
767 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200768 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 errstr = "The operation did not complete (write)";
770 break;
771 case SSL_ERROR_WANT_X509_LOOKUP:
772 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000773 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 break;
775 case SSL_ERROR_WANT_CONNECT:
776 p = PY_SSL_ERROR_WANT_CONNECT;
777 errstr = "The operation did not complete (connect)";
778 break;
779 case SSL_ERROR_SYSCALL:
780 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700782 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200785 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000786 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200787 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000788 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000789 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700790#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700791 if (err.ws) {
792 return PyErr_SetFromWindowsErr(err.ws);
793 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700794#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700795 if (err.c) {
796 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700797 return PyErr_SetFromErrno(PyExc_OSError);
798 }
799 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200800 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000801 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200802 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000804 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200805 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000806 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 }
808 } else {
809 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 }
811 break;
812 }
813 case SSL_ERROR_SSL:
814 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700816 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200817 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000818 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700819 }
820 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
821 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
822 type = PySSLCertVerificationErrorObject;
823 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 break;
825 }
826 default:
827 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
828 errstr = "Invalid error code";
829 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700831 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000832 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200833 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000835}
836
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200838_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000839
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200840 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000841 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200842 else
843 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700844 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000845 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000847}
848
Christian Heimes61d478c2018-01-27 15:51:38 +0100849/*
850 * SSL objects
851 */
852
853static int
854_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
855{
856 int retval = -1;
857 ASN1_OCTET_STRING *ip;
858 PyObject *hostname;
859 size_t len;
860
861 assert(server_hostname);
862
863 /* Disable OpenSSL's special mode with leading dot in hostname:
864 * When name starts with a dot (e.g ".example.com"), it will be
865 * matched by a certificate valid for any sub-domain of name.
866 */
867 len = strlen(server_hostname);
868 if (len == 0 || *server_hostname == '.') {
869 PyErr_SetString(
870 PyExc_ValueError,
871 "server_hostname cannot be an empty string or start with a "
872 "leading dot.");
873 return retval;
874 }
875
876 /* inet_pton is not available on all platforms. */
877 ip = a2i_IPADDRESS(server_hostname);
878 if (ip == NULL) {
879 ERR_clear_error();
880 }
881
Christian Heimes11a14932018-02-24 02:35:08 +0100882 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100883 if (hostname == NULL) {
884 goto error;
885 }
886 self->server_hostname = hostname;
887
888 /* Only send SNI extension for non-IP hostnames */
889 if (ip == NULL) {
890 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
891 _setSSLError(NULL, 0, __FILE__, __LINE__);
892 }
893 }
894 if (self->ctx->check_hostname) {
895 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
896 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200897 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
898 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100899 _setSSLError(NULL, 0, __FILE__, __LINE__);
900 goto error;
901 }
902 } else {
903 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
904 ASN1_STRING_length(ip))) {
905 _setSSLError(NULL, 0, __FILE__, __LINE__);
906 goto error;
907 }
908 }
909 }
910 retval = 0;
911 error:
912 if (ip != NULL) {
913 ASN1_OCTET_STRING_free(ip);
914 }
915 return retval;
916}
917
Antoine Pitrou152efa22010-05-16 18:19:27 +0000918static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100919newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000920 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200921 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100922 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200923 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000924{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000925 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100926 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700927 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000928
Antoine Pitrou152efa22010-05-16 18:19:27 +0000929 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 if (self == NULL)
931 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100935 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700936 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200937 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200938 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700939 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700940 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200941 self->exc_type = NULL;
942 self->exc_value = NULL;
943 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000949 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700951 if (self->ssl == NULL) {
952 Py_DECREF(self);
953 _setSSLError(NULL, 0, __FILE__, __LINE__);
954 return NULL;
955 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200956 SSL_set_app_data(self->ssl, self);
957 if (sock) {
958 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
959 } else {
960 /* BIOs are reference counted and SSL_set_bio borrows our reference.
961 * To prevent a double free in memory_bio_dealloc() we need to take an
962 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200963 BIO_up_ref(inbio->bio);
964 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200965 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
966 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400967 SSL_set_mode(self->ssl,
968 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000969
Christian Heimesf22c4cf2019-07-01 09:25:48 +0200970#ifdef TLS1_3_VERSION
971 if (sslctx->post_handshake_auth == 1) {
972 if (socket_type == PY_SSL_SERVER) {
973 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
974 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
975 * only in combination with SSL_VERIFY_PEER flag. */
976 int mode = SSL_get_verify_mode(self->ssl);
977 if (mode & SSL_VERIFY_PEER) {
978 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
979 verify_cb = SSL_get_verify_callback(self->ssl);
980 mode |= SSL_VERIFY_POST_HANDSHAKE;
981 SSL_set_verify(self->ssl, mode, verify_cb);
982 }
983 } else {
984 /* client socket */
985 SSL_set_post_handshake_auth(self->ssl, 1);
986 }
987 }
988#endif
989
Christian Heimes61d478c2018-01-27 15:51:38 +0100990 if (server_hostname != NULL) {
991 if (_ssl_configure_hostname(self, server_hostname) < 0) {
992 Py_DECREF(self);
993 return NULL;
994 }
995 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 /* If the socket is in non-blocking mode or timeout mode, set the BIO
997 * to non-blocking mode (blocking is the default)
998 */
Victor Stinnere2452312015-03-28 03:00:46 +0100999 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
1001 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1002 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 PySSL_BEGIN_ALLOW_THREADS
1005 if (socket_type == PY_SSL_CLIENT)
1006 SSL_set_connect_state(self->ssl);
1007 else
1008 SSL_set_accept_state(self->ssl);
1009 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001010
Antoine Pitroud6494802011-07-21 01:11:30 +02001011 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001012 if (sock != NULL) {
1013 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1014 if (self->Socket == NULL) {
1015 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001016 return NULL;
1017 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001018 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001019 if (owner && owner != Py_None) {
1020 if (PySSL_set_owner(self, owner, NULL) == -1) {
1021 Py_DECREF(self);
1022 return NULL;
1023 }
1024 }
1025 if (session && session != Py_None) {
1026 if (PySSL_set_session(self, session, NULL) == -1) {
1027 Py_DECREF(self);
1028 return NULL;
1029 }
1030 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001032}
1033
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001034/* SSL object methods */
1035
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001036/*[clinic input]
1037_ssl._SSLSocket.do_handshake
1038[clinic start generated code]*/
1039
1040static PyObject *
1041_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1042/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001043{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001045 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001047 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001048 _PyTime_t timeout, deadline = 0;
1049 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001050
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001051 if (sock) {
1052 if (((PyObject*)sock) == Py_None) {
1053 _setSSLError("Underlying socket connection gone",
1054 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1055 return NULL;
1056 }
1057 Py_INCREF(sock);
1058
1059 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001060 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001061 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1062 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001064
Victor Stinner14690702015-04-06 22:46:13 +02001065 timeout = GET_SOCKET_TIMEOUT(sock);
1066 has_timeout = (timeout > 0);
1067 if (has_timeout)
1068 deadline = _PyTime_GetMonotonicClock() + timeout;
1069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 /* Actually negotiate SSL connection */
1071 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001073 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001075 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001077 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001078
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001079 if (PyErr_CheckSignals())
1080 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001081
Victor Stinner14690702015-04-06 22:46:13 +02001082 if (has_timeout)
1083 timeout = deadline - _PyTime_GetMonotonicClock();
1084
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001085 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001086 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001087 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001088 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 } else {
1090 sockstate = SOCKET_OPERATION_OK;
1091 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001094 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001095 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001096 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1098 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001099 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001100 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1102 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001103 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001104 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1106 break;
1107 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001108 } while (err.ssl == SSL_ERROR_WANT_READ ||
1109 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001110 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 if (ret < 1)
1112 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001113 if (PySSL_ChainExceptions(self) < 0)
1114 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001115 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001116error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001117 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001118 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001119 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001120}
1121
Thomas Woutersed03b412007-08-28 21:37:11 +00001122static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001123_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1124{
1125 char buf[X509_NAME_MAXLEN];
1126 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001128 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001129
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001130 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 if (buflen < 0) {
1132 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001133 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001135 /* initial buffer is too small for oid + terminating null byte */
1136 if (buflen > X509_NAME_MAXLEN - 1) {
1137 /* make OBJ_obj2txt() calculate the required buflen */
1138 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1139 /* allocate len + 1 for terminating NULL byte */
1140 namebuf = PyMem_Malloc(buflen + 1);
1141 if (namebuf == NULL) {
1142 PyErr_NoMemory();
1143 return NULL;
1144 }
1145 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1146 if (buflen < 0) {
1147 _setSSLError(NULL, 0, __FILE__, __LINE__);
1148 goto done;
1149 }
1150 }
1151 if (!buflen && no_name) {
1152 Py_INCREF(Py_None);
1153 name_obj = Py_None;
1154 }
1155 else {
1156 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1157 }
1158
1159 done:
1160 if (buf != namebuf) {
1161 PyMem_Free(namebuf);
1162 }
1163 return name_obj;
1164}
1165
1166static PyObject *
1167_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1168{
1169 Py_ssize_t buflen;
1170 unsigned char *valuebuf = NULL;
1171 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1174 if (buflen < 0) {
1175 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001176 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001178 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001180 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001181}
1182
1183static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001185{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001186 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1187 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1188 PyObject *rdnt;
1189 PyObject *attr = NULL; /* tuple to hold an attribute */
1190 int entry_count = X509_NAME_entry_count(xname);
1191 X509_NAME_ENTRY *entry;
1192 ASN1_OBJECT *name;
1193 ASN1_STRING *value;
1194 int index_counter;
1195 int rdn_level = -1;
1196 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 dn = PyList_New(0);
1199 if (dn == NULL)
1200 return NULL;
1201 /* now create another tuple to hold the top-level RDN */
1202 rdn = PyList_New(0);
1203 if (rdn == NULL)
1204 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 for (index_counter = 0;
1207 index_counter < entry_count;
1208 index_counter++)
1209 {
1210 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001212 /* check to see if we've gotten to a new RDN */
1213 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001214 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 /* yes, new RDN */
1216 /* add old RDN to DN */
1217 rdnt = PyList_AsTuple(rdn);
1218 Py_DECREF(rdn);
1219 if (rdnt == NULL)
1220 goto fail0;
1221 retcode = PyList_Append(dn, rdnt);
1222 Py_DECREF(rdnt);
1223 if (retcode < 0)
1224 goto fail0;
1225 /* create new RDN */
1226 rdn = PyList_New(0);
1227 if (rdn == NULL)
1228 goto fail0;
1229 }
1230 }
Christian Heimes598894f2016-09-05 23:19:05 +02001231 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 /* now add this attribute to the current RDN */
1234 name = X509_NAME_ENTRY_get_object(entry);
1235 value = X509_NAME_ENTRY_get_data(entry);
1236 attr = _create_tuple_for_attribute(name, value);
1237 /*
1238 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1239 entry->set,
1240 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1241 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1242 */
1243 if (attr == NULL)
1244 goto fail1;
1245 retcode = PyList_Append(rdn, attr);
1246 Py_DECREF(attr);
1247 if (retcode < 0)
1248 goto fail1;
1249 }
1250 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001251 if (rdn != NULL) {
1252 if (PyList_GET_SIZE(rdn) > 0) {
1253 rdnt = PyList_AsTuple(rdn);
1254 Py_DECREF(rdn);
1255 if (rdnt == NULL)
1256 goto fail0;
1257 retcode = PyList_Append(dn, rdnt);
1258 Py_DECREF(rdnt);
1259 if (retcode < 0)
1260 goto fail0;
1261 }
1262 else {
1263 Py_DECREF(rdn);
1264 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 /* convert list to tuple */
1268 rdnt = PyList_AsTuple(dn);
1269 Py_DECREF(dn);
1270 if (rdnt == NULL)
1271 return NULL;
1272 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273
1274 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276
1277 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001278 Py_XDECREF(dn);
1279 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001280}
1281
1282static PyObject *
1283_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001285 /* this code follows the procedure outlined in
1286 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1287 function to extract the STACK_OF(GENERAL_NAME),
1288 then iterates through the stack to add the
1289 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001290
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001291 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001293 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 GENERAL_NAMES *names = NULL;
1295 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 BIO *biobuf = NULL;
1297 char buf[2048];
1298 char *vptr;
1299 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 if (certificate == NULL)
1302 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001304 /* get a memory buffer */
1305 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001306 if (biobuf == NULL) {
1307 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1308 return NULL;
1309 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001310
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001311 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1312 certificate, NID_subject_alt_name, NULL, NULL);
1313 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 if (peer_alt_names == Py_None) {
1315 peer_alt_names = PyList_New(0);
1316 if (peer_alt_names == NULL)
1317 goto fail;
1318 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001322 int gntype;
1323 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001324
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001326 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001327 switch (gntype) {
1328 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 /* we special-case DirName as a tuple of
1330 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 t = PyTuple_New(2);
1333 if (t == NULL) {
1334 goto fail;
1335 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 v = PyUnicode_FromString("DirName");
1338 if (v == NULL) {
1339 Py_DECREF(t);
1340 goto fail;
1341 }
1342 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 v = _create_tuple_for_X509_NAME (name->d.dirn);
1345 if (v == NULL) {
1346 Py_DECREF(t);
1347 goto fail;
1348 }
1349 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001350 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001351
Christian Heimes824f7f32013-08-17 00:54:47 +02001352 case GEN_EMAIL:
1353 case GEN_DNS:
1354 case GEN_URI:
1355 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1356 correctly, CVE-2013-4238 */
1357 t = PyTuple_New(2);
1358 if (t == NULL)
1359 goto fail;
1360 switch (gntype) {
1361 case GEN_EMAIL:
1362 v = PyUnicode_FromString("email");
1363 as = name->d.rfc822Name;
1364 break;
1365 case GEN_DNS:
1366 v = PyUnicode_FromString("DNS");
1367 as = name->d.dNSName;
1368 break;
1369 case GEN_URI:
1370 v = PyUnicode_FromString("URI");
1371 as = name->d.uniformResourceIdentifier;
1372 break;
1373 }
1374 if (v == NULL) {
1375 Py_DECREF(t);
1376 goto fail;
1377 }
1378 PyTuple_SET_ITEM(t, 0, v);
1379 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1380 ASN1_STRING_length(as));
1381 if (v == NULL) {
1382 Py_DECREF(t);
1383 goto fail;
1384 }
1385 PyTuple_SET_ITEM(t, 1, v);
1386 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001387
Christian Heimes1c03abd2016-09-06 23:25:35 +02001388 case GEN_RID:
1389 t = PyTuple_New(2);
1390 if (t == NULL)
1391 goto fail;
1392
1393 v = PyUnicode_FromString("Registered ID");
1394 if (v == NULL) {
1395 Py_DECREF(t);
1396 goto fail;
1397 }
1398 PyTuple_SET_ITEM(t, 0, v);
1399
1400 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1401 if (len < 0) {
1402 Py_DECREF(t);
1403 _setSSLError(NULL, 0, __FILE__, __LINE__);
1404 goto fail;
1405 } else if (len >= (int)sizeof(buf)) {
1406 v = PyUnicode_FromString("<INVALID>");
1407 } else {
1408 v = PyUnicode_FromStringAndSize(buf, len);
1409 }
1410 if (v == NULL) {
1411 Py_DECREF(t);
1412 goto fail;
1413 }
1414 PyTuple_SET_ITEM(t, 1, v);
1415 break;
1416
Miss Islington (bot)9d3cacd2019-12-07 09:20:27 -08001417 case GEN_IPADD:
1418 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1419 * the trailing newline. Remove it in all versions
1420 */
1421 t = PyTuple_New(2);
1422 if (t == NULL)
1423 goto fail;
1424
1425 v = PyUnicode_FromString("IP Address");
1426 if (v == NULL) {
1427 Py_DECREF(t);
1428 goto fail;
1429 }
1430 PyTuple_SET_ITEM(t, 0, v);
1431
1432 if (name->d.ip->length == 4) {
1433 unsigned char *p = name->d.ip->data;
1434 v = PyUnicode_FromFormat(
1435 "%d.%d.%d.%d",
1436 p[0], p[1], p[2], p[3]
1437 );
1438 } else if (name->d.ip->length == 16) {
1439 /* PyUnicode_FromFormat() does not support %X */
1440 unsigned char *p = name->d.ip->data;
1441 len = sprintf(
1442 buf,
1443 "%X:%X:%X:%X:%X:%X:%X:%X",
1444 p[0] << 8 | p[1],
1445 p[2] << 8 | p[3],
1446 p[4] << 8 | p[5],
1447 p[6] << 8 | p[7],
1448 p[8] << 8 | p[9],
1449 p[10] << 8 | p[11],
1450 p[12] << 8 | p[13],
1451 p[14] << 8 | p[15]
1452 );
1453 v = PyUnicode_FromStringAndSize(buf, len);
1454 } else {
1455 v = PyUnicode_FromString("<invalid>");
1456 }
1457
1458 if (v == NULL) {
1459 Py_DECREF(t);
1460 goto fail;
1461 }
1462 PyTuple_SET_ITEM(t, 1, v);
1463 break;
1464
Christian Heimes824f7f32013-08-17 00:54:47 +02001465 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001467 switch (gntype) {
1468 /* check for new general name type */
1469 case GEN_OTHERNAME:
1470 case GEN_X400:
1471 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001472 case GEN_RID:
1473 break;
1474 default:
1475 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1476 "Unknown general name type %d",
1477 gntype) == -1) {
1478 goto fail;
1479 }
1480 break;
1481 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001482 (void) BIO_reset(biobuf);
1483 GENERAL_NAME_print(biobuf, name);
1484 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1485 if (len < 0) {
1486 _setSSLError(NULL, 0, __FILE__, __LINE__);
1487 goto fail;
1488 }
1489 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001490 if (vptr == NULL) {
1491 PyErr_Format(PyExc_ValueError,
1492 "Invalid value %.200s",
1493 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001495 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 t = PyTuple_New(2);
1497 if (t == NULL)
1498 goto fail;
1499 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1500 if (v == NULL) {
1501 Py_DECREF(t);
1502 goto fail;
1503 }
1504 PyTuple_SET_ITEM(t, 0, v);
1505 v = PyUnicode_FromStringAndSize((vptr + 1),
1506 (len - (vptr - buf + 1)));
1507 if (v == NULL) {
1508 Py_DECREF(t);
1509 goto fail;
1510 }
1511 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001512 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 if (PyList_Append(peer_alt_names, t) < 0) {
1518 Py_DECREF(t);
1519 goto fail;
1520 }
1521 Py_DECREF(t);
1522 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001523 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 }
1525 BIO_free(biobuf);
1526 if (peer_alt_names != Py_None) {
1527 v = PyList_AsTuple(peer_alt_names);
1528 Py_DECREF(peer_alt_names);
1529 return v;
1530 } else {
1531 return peer_alt_names;
1532 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001533
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001534
1535 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001536 if (biobuf != NULL)
1537 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 if (peer_alt_names != Py_None) {
1540 Py_XDECREF(peer_alt_names);
1541 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544}
1545
1546static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001547_get_aia_uri(X509 *certificate, int nid) {
1548 PyObject *lst = NULL, *ostr = NULL;
1549 int i, result;
1550 AUTHORITY_INFO_ACCESS *info;
1551
1552 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001553 if (info == NULL)
1554 return Py_None;
1555 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1556 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001557 return Py_None;
1558 }
1559
1560 if ((lst = PyList_New(0)) == NULL) {
1561 goto fail;
1562 }
1563
1564 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1565 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1566 ASN1_IA5STRING *uri;
1567
1568 if ((OBJ_obj2nid(ad->method) != nid) ||
1569 (ad->location->type != GEN_URI)) {
1570 continue;
1571 }
1572 uri = ad->location->d.uniformResourceIdentifier;
1573 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1574 uri->length);
1575 if (ostr == NULL) {
1576 goto fail;
1577 }
1578 result = PyList_Append(lst, ostr);
1579 Py_DECREF(ostr);
1580 if (result < 0) {
1581 goto fail;
1582 }
1583 }
1584 AUTHORITY_INFO_ACCESS_free(info);
1585
1586 /* convert to tuple or None */
1587 if (PyList_Size(lst) == 0) {
1588 Py_DECREF(lst);
1589 return Py_None;
1590 } else {
1591 PyObject *tup;
1592 tup = PyList_AsTuple(lst);
1593 Py_DECREF(lst);
1594 return tup;
1595 }
1596
1597 fail:
1598 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001599 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001600 return NULL;
1601}
1602
1603static PyObject *
1604_get_crl_dp(X509 *certificate) {
1605 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001606 int i, j;
1607 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001608
Christian Heimes598894f2016-09-05 23:19:05 +02001609 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001610
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001611 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001612 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001613
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001614 lst = PyList_New(0);
1615 if (lst == NULL)
1616 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001617
1618 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1619 DIST_POINT *dp;
1620 STACK_OF(GENERAL_NAME) *gns;
1621
1622 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001623 if (dp->distpoint == NULL) {
1624 /* Ignore empty DP value, CVE-2019-5010 */
1625 continue;
1626 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001627 gns = dp->distpoint->name.fullname;
1628
1629 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1630 GENERAL_NAME *gn;
1631 ASN1_IA5STRING *uri;
1632 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001633 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001634
1635 gn = sk_GENERAL_NAME_value(gns, j);
1636 if (gn->type != GEN_URI) {
1637 continue;
1638 }
1639 uri = gn->d.uniformResourceIdentifier;
1640 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1641 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001642 if (ouri == NULL)
1643 goto done;
1644
1645 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001646 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001647 if (err < 0)
1648 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001649 }
1650 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001651
1652 /* Convert to tuple. */
1653 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1654
1655 done:
1656 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001657 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001658 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001659}
1660
1661static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001662_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001663
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001664 PyObject *retval = NULL;
1665 BIO *biobuf = NULL;
1666 PyObject *peer;
1667 PyObject *peer_alt_names = NULL;
1668 PyObject *issuer;
1669 PyObject *version;
1670 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001671 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 ASN1_INTEGER *serialNumber;
1673 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001674 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 ASN1_TIME *notBefore, *notAfter;
1676 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001678 retval = PyDict_New();
1679 if (retval == NULL)
1680 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 peer = _create_tuple_for_X509_NAME(
1683 X509_get_subject_name(certificate));
1684 if (peer == NULL)
1685 goto fail0;
1686 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1687 Py_DECREF(peer);
1688 goto fail0;
1689 }
1690 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001691
Antoine Pitroufb046912010-11-09 20:21:19 +00001692 issuer = _create_tuple_for_X509_NAME(
1693 X509_get_issuer_name(certificate));
1694 if (issuer == NULL)
1695 goto fail0;
1696 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001698 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001700 Py_DECREF(issuer);
1701
1702 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001703 if (version == NULL)
1704 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001705 if (PyDict_SetItemString(retval, "version", version) < 0) {
1706 Py_DECREF(version);
1707 goto fail0;
1708 }
1709 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 /* get a memory buffer */
1712 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001713 if (biobuf == NULL) {
1714 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1715 goto fail0;
1716 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001717
Antoine Pitroufb046912010-11-09 20:21:19 +00001718 (void) BIO_reset(biobuf);
1719 serialNumber = X509_get_serialNumber(certificate);
1720 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1721 i2a_ASN1_INTEGER(biobuf, serialNumber);
1722 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1723 if (len < 0) {
1724 _setSSLError(NULL, 0, __FILE__, __LINE__);
1725 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001726 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001727 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1728 if (sn_obj == NULL)
1729 goto fail1;
1730 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1731 Py_DECREF(sn_obj);
1732 goto fail1;
1733 }
1734 Py_DECREF(sn_obj);
1735
1736 (void) BIO_reset(biobuf);
1737 notBefore = X509_get_notBefore(certificate);
1738 ASN1_TIME_print(biobuf, notBefore);
1739 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1740 if (len < 0) {
1741 _setSSLError(NULL, 0, __FILE__, __LINE__);
1742 goto fail1;
1743 }
1744 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1745 if (pnotBefore == NULL)
1746 goto fail1;
1747 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1748 Py_DECREF(pnotBefore);
1749 goto fail1;
1750 }
1751 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 (void) BIO_reset(biobuf);
1754 notAfter = X509_get_notAfter(certificate);
1755 ASN1_TIME_print(biobuf, notAfter);
1756 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1757 if (len < 0) {
1758 _setSSLError(NULL, 0, __FILE__, __LINE__);
1759 goto fail1;
1760 }
1761 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1762 if (pnotAfter == NULL)
1763 goto fail1;
1764 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1765 Py_DECREF(pnotAfter);
1766 goto fail1;
1767 }
1768 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001771
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 peer_alt_names = _get_peer_alt_names(certificate);
1773 if (peer_alt_names == NULL)
1774 goto fail1;
1775 else if (peer_alt_names != Py_None) {
1776 if (PyDict_SetItemString(retval, "subjectAltName",
1777 peer_alt_names) < 0) {
1778 Py_DECREF(peer_alt_names);
1779 goto fail1;
1780 }
1781 Py_DECREF(peer_alt_names);
1782 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001783
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001784 /* Authority Information Access: OCSP URIs */
1785 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1786 if (obj == NULL) {
1787 goto fail1;
1788 } else if (obj != Py_None) {
1789 result = PyDict_SetItemString(retval, "OCSP", obj);
1790 Py_DECREF(obj);
1791 if (result < 0) {
1792 goto fail1;
1793 }
1794 }
1795
1796 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1797 if (obj == NULL) {
1798 goto fail1;
1799 } else if (obj != Py_None) {
1800 result = PyDict_SetItemString(retval, "caIssuers", obj);
1801 Py_DECREF(obj);
1802 if (result < 0) {
1803 goto fail1;
1804 }
1805 }
1806
1807 /* CDP (CRL distribution points) */
1808 obj = _get_crl_dp(certificate);
1809 if (obj == NULL) {
1810 goto fail1;
1811 } else if (obj != Py_None) {
1812 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1813 Py_DECREF(obj);
1814 if (result < 0) {
1815 goto fail1;
1816 }
1817 }
1818
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 BIO_free(biobuf);
1820 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001821
1822 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if (biobuf != NULL)
1824 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001825 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 Py_XDECREF(retval);
1827 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001828}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001829
Christian Heimes9a5395a2013-06-17 15:44:12 +02001830static PyObject *
1831_certificate_to_der(X509 *certificate)
1832{
1833 unsigned char *bytes_buf = NULL;
1834 int len;
1835 PyObject *retval;
1836
1837 bytes_buf = NULL;
1838 len = i2d_X509(certificate, &bytes_buf);
1839 if (len < 0) {
1840 _setSSLError(NULL, 0, __FILE__, __LINE__);
1841 return NULL;
1842 }
1843 /* this is actually an immutable bytes sequence */
1844 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1845 OPENSSL_free(bytes_buf);
1846 return retval;
1847}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001848
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001849/*[clinic input]
1850_ssl._test_decode_cert
1851 path: object(converter="PyUnicode_FSConverter")
1852 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001853
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001854[clinic start generated code]*/
1855
1856static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001857_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1858/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001859{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001861 X509 *x=NULL;
1862 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1865 PyErr_SetString(PySSLErrorObject,
1866 "Can't malloc memory to read file");
1867 goto fail0;
1868 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001869
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001870 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001871 PyErr_SetString(PySSLErrorObject,
1872 "Can't open file");
1873 goto fail0;
1874 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001875
Miss Islington (bot)f7812832019-08-15 05:52:51 -07001876 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001877 if (x == NULL) {
1878 PyErr_SetString(PySSLErrorObject,
1879 "Error decoding PEM-encoded file");
1880 goto fail0;
1881 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001882
Antoine Pitroufb046912010-11-09 20:21:19 +00001883 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001884 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001885
1886 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001887 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001888 if (cert != NULL) BIO_free(cert);
1889 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001890}
1891
1892
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001893/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001894_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001895 der as binary_mode: bool = False
1896 /
1897
1898Returns the certificate for the peer.
1899
1900If no certificate was provided, returns None. If a certificate was
1901provided, but not validated, returns an empty dictionary. Otherwise
1902returns a dict containing information about the peer certificate.
1903
1904If the optional argument is True, returns a DER-encoded copy of the
1905peer certificate, or None if no certificate was provided. This will
1906return the certificate even if it wasn't validated.
1907[clinic start generated code]*/
1908
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001909static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001910_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1911/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001912{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001914 X509 *peer_cert;
1915 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001916
Christian Heimes66dc33b2017-05-23 16:02:02 -07001917 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001918 PyErr_SetString(PyExc_ValueError,
1919 "handshake not done yet");
1920 return NULL;
1921 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001922 peer_cert = SSL_get_peer_certificate(self->ssl);
1923 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001925
Antoine Pitrou721738f2012-08-15 23:20:39 +02001926 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001928 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001930 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001932 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001934 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001935 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001936 X509_free(peer_cert);
1937 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001938}
1939
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001940static PyObject *
1941cipher_to_tuple(const SSL_CIPHER *cipher)
1942{
1943 const char *cipher_name, *cipher_protocol;
1944 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 if (retval == NULL)
1946 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001947
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001948 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001950 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001951 PyTuple_SET_ITEM(retval, 0, Py_None);
1952 } else {
1953 v = PyUnicode_FromString(cipher_name);
1954 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001955 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 PyTuple_SET_ITEM(retval, 0, v);
1957 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001958
1959 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001961 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 PyTuple_SET_ITEM(retval, 1, Py_None);
1963 } else {
1964 v = PyUnicode_FromString(cipher_protocol);
1965 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, 1, v);
1968 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001969
1970 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001972 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001974
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001976
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001977 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 Py_DECREF(retval);
1979 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001980}
1981
Christian Heimes25bfcd52016-09-06 00:04:45 +02001982#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1983static PyObject *
1984cipher_to_dict(const SSL_CIPHER *cipher)
1985{
1986 const char *cipher_name, *cipher_protocol;
1987
1988 unsigned long cipher_id;
1989 int alg_bits, strength_bits, len;
1990 char buf[512] = {0};
1991#if OPENSSL_VERSION_1_1
1992 int aead, nid;
1993 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1994#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001995
1996 /* can be NULL */
1997 cipher_name = SSL_CIPHER_get_name(cipher);
1998 cipher_protocol = SSL_CIPHER_get_version(cipher);
1999 cipher_id = SSL_CIPHER_get_id(cipher);
2000 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03002001 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2002 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002003 if (len > 1 && buf[len-1] == '\n')
2004 buf[len-1] = '\0';
2005 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2006
2007#if OPENSSL_VERSION_1_1
2008 aead = SSL_CIPHER_is_aead(cipher);
2009 nid = SSL_CIPHER_get_cipher_nid(cipher);
2010 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2011 nid = SSL_CIPHER_get_digest_nid(cipher);
2012 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2013 nid = SSL_CIPHER_get_kx_nid(cipher);
2014 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2015 nid = SSL_CIPHER_get_auth_nid(cipher);
2016 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2017#endif
2018
Victor Stinner410b9882016-09-12 12:00:23 +02002019 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002020 "{sksssssssisi"
2021#if OPENSSL_VERSION_1_1
2022 "sOssssssss"
2023#endif
2024 "}",
2025 "id", cipher_id,
2026 "name", cipher_name,
2027 "protocol", cipher_protocol,
2028 "description", buf,
2029 "strength_bits", strength_bits,
2030 "alg_bits", alg_bits
2031#if OPENSSL_VERSION_1_1
2032 ,"aead", aead ? Py_True : Py_False,
2033 "symmetric", skcipher,
2034 "digest", digest,
2035 "kea", kx,
2036 "auth", auth
2037#endif
2038 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002039}
2040#endif
2041
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002042/*[clinic input]
2043_ssl._SSLSocket.shared_ciphers
2044[clinic start generated code]*/
2045
2046static PyObject *
2047_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2048/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002049{
2050 STACK_OF(SSL_CIPHER) *ciphers;
2051 int i;
2052 PyObject *res;
2053
Christian Heimes598894f2016-09-05 23:19:05 +02002054 ciphers = SSL_get_ciphers(self->ssl);
2055 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002056 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002057 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2058 if (!res)
2059 return NULL;
2060 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2061 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2062 if (!tup) {
2063 Py_DECREF(res);
2064 return NULL;
2065 }
2066 PyList_SET_ITEM(res, i, tup);
2067 }
2068 return res;
2069}
2070
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002071/*[clinic input]
2072_ssl._SSLSocket.cipher
2073[clinic start generated code]*/
2074
2075static PyObject *
2076_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2077/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002078{
2079 const SSL_CIPHER *current;
2080
2081 if (self->ssl == NULL)
2082 Py_RETURN_NONE;
2083 current = SSL_get_current_cipher(self->ssl);
2084 if (current == NULL)
2085 Py_RETURN_NONE;
2086 return cipher_to_tuple(current);
2087}
2088
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002089/*[clinic input]
2090_ssl._SSLSocket.version
2091[clinic start generated code]*/
2092
2093static PyObject *
2094_ssl__SSLSocket_version_impl(PySSLSocket *self)
2095/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002096{
2097 const char *version;
2098
2099 if (self->ssl == NULL)
2100 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002101 if (!SSL_is_init_finished(self->ssl)) {
2102 /* handshake not finished */
2103 Py_RETURN_NONE;
2104 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002105 version = SSL_get_version(self->ssl);
2106 if (!strcmp(version, "unknown"))
2107 Py_RETURN_NONE;
2108 return PyUnicode_FromString(version);
2109}
2110
Christian Heimes29eab552018-02-25 12:31:33 +01002111#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002112/*[clinic input]
2113_ssl._SSLSocket.selected_npn_protocol
2114[clinic start generated code]*/
2115
2116static PyObject *
2117_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2118/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2119{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002120 const unsigned char *out;
2121 unsigned int outlen;
2122
Victor Stinner4569cd52013-06-23 14:58:43 +02002123 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002124 &out, &outlen);
2125
2126 if (out == NULL)
2127 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002128 return PyUnicode_FromStringAndSize((char *)out, outlen);
2129}
2130#endif
2131
Christian Heimes29eab552018-02-25 12:31:33 +01002132#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002133/*[clinic input]
2134_ssl._SSLSocket.selected_alpn_protocol
2135[clinic start generated code]*/
2136
2137static PyObject *
2138_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2139/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2140{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002141 const unsigned char *out;
2142 unsigned int outlen;
2143
2144 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2145
2146 if (out == NULL)
2147 Py_RETURN_NONE;
2148 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002149}
2150#endif
2151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002152/*[clinic input]
2153_ssl._SSLSocket.compression
2154[clinic start generated code]*/
2155
2156static PyObject *
2157_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2158/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2159{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002160#ifdef OPENSSL_NO_COMP
2161 Py_RETURN_NONE;
2162#else
2163 const COMP_METHOD *comp_method;
2164 const char *short_name;
2165
2166 if (self->ssl == NULL)
2167 Py_RETURN_NONE;
2168 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002169 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002170 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002171 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002172 if (short_name == NULL)
2173 Py_RETURN_NONE;
2174 return PyUnicode_DecodeFSDefault(short_name);
2175#endif
2176}
2177
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002178static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2179 Py_INCREF(self->ctx);
2180 return self->ctx;
2181}
2182
2183static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2184 void *closure) {
2185
2186 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002187#if !HAVE_SNI
2188 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2189 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002190 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002191#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002192 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002193 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002194 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002195#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002196 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002197 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002198 return -1;
2199 }
2200
2201 return 0;
2202}
2203
2204PyDoc_STRVAR(PySSL_set_context_doc,
2205"_setter_context(ctx)\n\
2206\
2207This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002208used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002209on the SSLContext to change the certificate information associated with the\n\
2210SSLSocket before the cryptographic exchange handshake messages\n");
2211
2212
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213static PyObject *
2214PySSL_get_server_side(PySSLSocket *self, void *c)
2215{
2216 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2217}
2218
2219PyDoc_STRVAR(PySSL_get_server_side_doc,
2220"Whether this is a server-side socket.");
2221
2222static PyObject *
2223PySSL_get_server_hostname(PySSLSocket *self, void *c)
2224{
2225 if (self->server_hostname == NULL)
2226 Py_RETURN_NONE;
2227 Py_INCREF(self->server_hostname);
2228 return self->server_hostname;
2229}
2230
2231PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2232"The currently set server hostname (for SNI).");
2233
2234static PyObject *
2235PySSL_get_owner(PySSLSocket *self, void *c)
2236{
2237 PyObject *owner;
2238
2239 if (self->owner == NULL)
2240 Py_RETURN_NONE;
2241
2242 owner = PyWeakref_GetObject(self->owner);
2243 Py_INCREF(owner);
2244 return owner;
2245}
2246
2247static int
2248PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2249{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002250 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002251 if (self->owner == NULL)
2252 return -1;
2253 return 0;
2254}
2255
2256PyDoc_STRVAR(PySSL_get_owner_doc,
2257"The Python-level owner of this object.\
2258Passed as \"self\" in servername callback.");
2259
Christian Heimesc7f70692019-05-31 11:44:05 +02002260static int
2261PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2262{
2263 Py_VISIT(self->exc_type);
2264 Py_VISIT(self->exc_value);
2265 Py_VISIT(self->exc_tb);
2266 return 0;
2267}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002268
Christian Heimesc7f70692019-05-31 11:44:05 +02002269static int
2270PySSL_clear(PySSLSocket *self)
2271{
2272 Py_CLEAR(self->exc_type);
2273 Py_CLEAR(self->exc_value);
2274 Py_CLEAR(self->exc_tb);
2275 return 0;
2276}
2277
2278static void
2279PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002280{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 if (self->ssl)
2282 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002284 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002285 Py_XDECREF(self->server_hostname);
2286 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002288}
2289
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002290/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002291 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002292 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002293 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002294
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002295static int
Victor Stinner14690702015-04-06 22:46:13 +02002296PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002297{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002298 int rc;
2299#ifdef HAVE_POLL
2300 struct pollfd pollfd;
2301 _PyTime_t ms;
2302#else
2303 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 fd_set fds;
2305 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002306#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002307
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002309 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002310 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002311 else if (timeout < 0) {
2312 if (s->sock_timeout > 0)
2313 return SOCKET_HAS_TIMED_OUT;
2314 else
2315 return SOCKET_IS_BLOCKING;
2316 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002319 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002322 /* Prefer poll, if available, since you can poll() any fd
2323 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002324#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002325 pollfd.fd = s->sock_fd;
2326 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002327
Victor Stinner14690702015-04-06 22:46:13 +02002328 /* timeout is in seconds, poll() uses milliseconds */
2329 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002330 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002331
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002332 PySSL_BEGIN_ALLOW_THREADS
2333 rc = poll(&pollfd, 1, (int)ms);
2334 PySSL_END_ALLOW_THREADS
2335#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002337 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002339
Victor Stinner14690702015-04-06 22:46:13 +02002340 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 FD_ZERO(&fds);
2343 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002344
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002345 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002347 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002349 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002351 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002353#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2356 (when we are able to write or when there's something to read) */
2357 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002358}
2359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002360/*[clinic input]
2361_ssl._SSLSocket.write
2362 b: Py_buffer
2363 /
2364
2365Writes the bytes-like object b into the SSL object.
2366
2367Returns the number of bytes written.
2368[clinic start generated code]*/
2369
2370static PyObject *
2371_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2372/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002373{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 int len;
2375 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002376 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002378 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002379 _PyTime_t timeout, deadline = 0;
2380 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002381
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002382 if (sock != NULL) {
2383 if (((PyObject*)sock) == Py_None) {
2384 _setSSLError("Underlying socket connection gone",
2385 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2386 return NULL;
2387 }
2388 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002389 }
2390
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002391 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002392 PyErr_Format(PyExc_OverflowError,
2393 "string longer than %d bytes", INT_MAX);
2394 goto error;
2395 }
2396
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002397 if (sock != NULL) {
2398 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002399 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002400 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2401 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2402 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002403
Victor Stinner14690702015-04-06 22:46:13 +02002404 timeout = GET_SOCKET_TIMEOUT(sock);
2405 has_timeout = (timeout > 0);
2406 if (has_timeout)
2407 deadline = _PyTime_GetMonotonicClock() + timeout;
2408
2409 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002411 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002412 "The write operation timed out");
2413 goto error;
2414 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2415 PyErr_SetString(PySSLErrorObject,
2416 "Underlying socket has been closed.");
2417 goto error;
2418 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2419 PyErr_SetString(PySSLErrorObject,
2420 "Underlying socket too large for select().");
2421 goto error;
2422 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002426 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002427 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002429 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002430
2431 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002433
Victor Stinner14690702015-04-06 22:46:13 +02002434 if (has_timeout)
2435 timeout = deadline - _PyTime_GetMonotonicClock();
2436
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002437 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002438 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002439 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002440 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 } else {
2442 sockstate = SOCKET_OPERATION_OK;
2443 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002446 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 "The write operation timed out");
2448 goto error;
2449 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2450 PyErr_SetString(PySSLErrorObject,
2451 "Underlying socket has been closed.");
2452 goto error;
2453 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2454 break;
2455 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002456 } while (err.ssl == SSL_ERROR_WANT_READ ||
2457 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002458
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002459 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002460 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002462 if (PySSL_ChainExceptions(self) < 0)
2463 return NULL;
2464 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002465error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002466 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002467 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002468 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002469}
2470
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002471/*[clinic input]
2472_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002473
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002474Returns the number of already decrypted bytes available for read, pending on the connection.
2475[clinic start generated code]*/
2476
2477static PyObject *
2478_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2479/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002480{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002481 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002482 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484 PySSL_BEGIN_ALLOW_THREADS
2485 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002486 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002488 self->err = err;
2489
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 if (count < 0)
2491 return PySSL_SetError(self, count, __FILE__, __LINE__);
2492 else
2493 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002494}
2495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002496/*[clinic input]
2497_ssl._SSLSocket.read
2498 size as len: int
2499 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002500 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002501 ]
2502 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002503
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002504Read up to size bytes from the SSL socket.
2505[clinic start generated code]*/
2506
2507static PyObject *
2508_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2509 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002510/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002511{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002512 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002514 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002515 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002516 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002518 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002519 _PyTime_t timeout, deadline = 0;
2520 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002521
Martin Panter5503d472016-03-27 05:35:19 +00002522 if (!group_right_1 && len < 0) {
2523 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2524 return NULL;
2525 }
2526
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002527 if (sock != NULL) {
2528 if (((PyObject*)sock) == Py_None) {
2529 _setSSLError("Underlying socket connection gone",
2530 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2531 return NULL;
2532 }
2533 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 }
2535
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002536 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002537 dest = PyBytes_FromStringAndSize(NULL, len);
2538 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002539 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002540 if (len == 0) {
2541 Py_XDECREF(sock);
2542 return dest;
2543 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002544 mem = PyBytes_AS_STRING(dest);
2545 }
2546 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002547 mem = buffer->buf;
2548 if (len <= 0 || len > buffer->len) {
2549 len = (int) buffer->len;
2550 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002551 PyErr_SetString(PyExc_OverflowError,
2552 "maximum length can't fit in a C 'int'");
2553 goto error;
2554 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002555 if (len == 0) {
2556 count = 0;
2557 goto done;
2558 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002559 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 }
2561
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002562 if (sock != NULL) {
2563 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002564 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002565 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2566 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2567 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568
Victor Stinner14690702015-04-06 22:46:13 +02002569 timeout = GET_SOCKET_TIMEOUT(sock);
2570 has_timeout = (timeout > 0);
2571 if (has_timeout)
2572 deadline = _PyTime_GetMonotonicClock() + timeout;
2573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002574 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002575 PySSL_BEGIN_ALLOW_THREADS
2576 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002577 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002579 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 if (PyErr_CheckSignals())
2582 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002583
Victor Stinner14690702015-04-06 22:46:13 +02002584 if (has_timeout)
2585 timeout = deadline - _PyTime_GetMonotonicClock();
2586
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002587 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002588 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002589 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002590 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002591 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002592 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002593 {
2594 count = 0;
2595 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002597 else
2598 sockstate = SOCKET_OPERATION_OK;
2599
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002600 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002601 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002602 "The read operation timed out");
2603 goto error;
2604 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2605 break;
2606 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002607 } while (err.ssl == SSL_ERROR_WANT_READ ||
2608 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002610 if (count <= 0) {
2611 PySSL_SetError(self, count, __FILE__, __LINE__);
2612 goto error;
2613 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002614 if (self->exc_type != NULL)
2615 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002616
2617done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002618 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002619 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002620 _PyBytes_Resize(&dest, count);
2621 return dest;
2622 }
2623 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002624 return PyLong_FromLong(count);
2625 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002626
2627error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002628 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002629 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002630 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002631 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002632 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002633}
2634
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002635/*[clinic input]
2636_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002637
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002638Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002639[clinic start generated code]*/
2640
2641static PyObject *
2642_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002643/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002644{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002645 _PySSLError err;
2646 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002647 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002648 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002649 _PyTime_t timeout, deadline = 0;
2650 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002651
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002652 if (sock != NULL) {
2653 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002654 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002655 _setSSLError("Underlying socket connection gone",
2656 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2657 return NULL;
2658 }
2659 Py_INCREF(sock);
2660
2661 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002662 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002663 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2664 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002665 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002666
Victor Stinner14690702015-04-06 22:46:13 +02002667 timeout = GET_SOCKET_TIMEOUT(sock);
2668 has_timeout = (timeout > 0);
2669 if (has_timeout)
2670 deadline = _PyTime_GetMonotonicClock() + timeout;
2671
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002672 while (1) {
2673 PySSL_BEGIN_ALLOW_THREADS
2674 /* Disable read-ahead so that unwrap can work correctly.
2675 * Otherwise OpenSSL might read in too much data,
2676 * eating clear text data that happens to be
2677 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002678 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002679 * function is used and the shutdown_seen_zero != 0
2680 * condition is met.
2681 */
2682 if (self->shutdown_seen_zero)
2683 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002684 ret = SSL_shutdown(self->ssl);
2685 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002686 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002687 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002688
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002690 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002691 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002692 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002693 /* Don't loop endlessly; instead preserve legacy
2694 behaviour of trying SSL_shutdown() only twice.
2695 This looks necessary for OpenSSL < 0.9.8m */
2696 if (++zeros > 1)
2697 break;
2698 /* Shutdown was sent, now try receiving */
2699 self->shutdown_seen_zero = 1;
2700 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002701 }
2702
Victor Stinner14690702015-04-06 22:46:13 +02002703 if (has_timeout)
2704 timeout = deadline - _PyTime_GetMonotonicClock();
2705
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002706 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002707 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002708 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002709 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002710 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002711 else
2712 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002713
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002714 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002715 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002716 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002717 "The read operation timed out");
2718 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002719 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002720 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002721 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002722 }
2723 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2724 PyErr_SetString(PySSLErrorObject,
2725 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002726 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002727 }
2728 else if (sockstate != SOCKET_OPERATION_OK)
2729 /* Retain the SSL error code */
2730 break;
2731 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002732 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002733 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002734 PySSL_SetError(self, ret, __FILE__, __LINE__);
2735 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002736 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002737 if (self->exc_type != NULL)
2738 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002739 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002740 /* It's already INCREF'ed */
2741 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002742 else
2743 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002744
2745error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002746 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002747 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002748 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002749}
2750
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002751/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002752_ssl._SSLSocket.get_channel_binding
2753 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002754
Christian Heimes141c5e82018-02-24 21:10:57 +01002755Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002756
Christian Heimes141c5e82018-02-24 21:10:57 +01002757Raise ValueError if the requested `cb_type` is not supported. Return bytes
2758of the data or None if the data is not available (e.g. before the handshake).
2759Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002760[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002761
Antoine Pitroud6494802011-07-21 01:11:30 +02002762static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002763_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2764 const char *cb_type)
2765/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002766{
Antoine Pitroud6494802011-07-21 01:11:30 +02002767 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002768 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002769
Christian Heimes141c5e82018-02-24 21:10:57 +01002770 if (strcmp(cb_type, "tls-unique") == 0) {
2771 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2772 /* if session is resumed XOR we are the client */
2773 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2774 }
2775 else {
2776 /* if a new session XOR we are the server */
2777 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2778 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002779 }
2780 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002781 PyErr_Format(
2782 PyExc_ValueError,
2783 "'%s' channel binding type not implemented",
2784 cb_type
2785 );
2786 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002787 }
2788
2789 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002790 if (len == 0)
2791 Py_RETURN_NONE;
2792
Christian Heimes141c5e82018-02-24 21:10:57 +01002793 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002794}
2795
Christian Heimes9fb051f2018-09-23 08:32:31 +02002796/*[clinic input]
2797_ssl._SSLSocket.verify_client_post_handshake
2798
2799Initiate TLS 1.3 post-handshake authentication
2800[clinic start generated code]*/
2801
2802static PyObject *
2803_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2804/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2805{
2806#ifdef TLS1_3_VERSION
2807 int err = SSL_verify_client_post_handshake(self->ssl);
2808 if (err == 0)
2809 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2810 else
2811 Py_RETURN_NONE;
2812#else
2813 PyErr_SetString(PyExc_NotImplementedError,
2814 "Post-handshake auth is not supported by your "
2815 "OpenSSL version.");
2816 return NULL;
2817#endif
2818}
2819
Christian Heimes99a65702016-09-10 23:44:53 +02002820#ifdef OPENSSL_VERSION_1_1
2821
2822static SSL_SESSION*
2823_ssl_session_dup(SSL_SESSION *session) {
2824 SSL_SESSION *newsession = NULL;
2825 int slen;
2826 unsigned char *senc = NULL, *p;
2827 const unsigned char *const_p;
2828
2829 if (session == NULL) {
2830 PyErr_SetString(PyExc_ValueError, "Invalid session");
2831 goto error;
2832 }
2833
2834 /* get length */
2835 slen = i2d_SSL_SESSION(session, NULL);
2836 if (slen == 0 || slen > 0xFF00) {
2837 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2838 goto error;
2839 }
2840 if ((senc = PyMem_Malloc(slen)) == NULL) {
2841 PyErr_NoMemory();
2842 goto error;
2843 }
2844 p = senc;
2845 if (!i2d_SSL_SESSION(session, &p)) {
2846 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2847 goto error;
2848 }
2849 const_p = senc;
2850 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2851 if (session == NULL) {
2852 goto error;
2853 }
2854 PyMem_Free(senc);
2855 return newsession;
2856 error:
2857 if (senc != NULL) {
2858 PyMem_Free(senc);
2859 }
2860 return NULL;
2861}
2862#endif
2863
2864static PyObject *
2865PySSL_get_session(PySSLSocket *self, void *closure) {
2866 /* get_session can return sessions from a server-side connection,
2867 * it does not check for handshake done or client socket. */
2868 PySSLSession *pysess;
2869 SSL_SESSION *session;
2870
2871#ifdef OPENSSL_VERSION_1_1
2872 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2873 * https://github.com/openssl/openssl/issues/1550 */
2874 session = SSL_get0_session(self->ssl); /* borrowed reference */
2875 if (session == NULL) {
2876 Py_RETURN_NONE;
2877 }
2878 if ((session = _ssl_session_dup(session)) == NULL) {
2879 return NULL;
2880 }
2881#else
2882 session = SSL_get1_session(self->ssl);
2883 if (session == NULL) {
2884 Py_RETURN_NONE;
2885 }
2886#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002887 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002888 if (pysess == NULL) {
2889 SSL_SESSION_free(session);
2890 return NULL;
2891 }
2892
2893 assert(self->ctx);
2894 pysess->ctx = self->ctx;
2895 Py_INCREF(pysess->ctx);
2896 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002897 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002898 return (PyObject *)pysess;
2899}
2900
2901static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2902 void *closure)
2903 {
2904 PySSLSession *pysess;
2905#ifdef OPENSSL_VERSION_1_1
2906 SSL_SESSION *session;
2907#endif
2908 int result;
2909
2910 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002911 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002912 return -1;
2913 }
2914 pysess = (PySSLSession *)value;
2915
2916 if (self->ctx->ctx != pysess->ctx->ctx) {
2917 PyErr_SetString(PyExc_ValueError,
2918 "Session refers to a different SSLContext.");
2919 return -1;
2920 }
2921 if (self->socket_type != PY_SSL_CLIENT) {
2922 PyErr_SetString(PyExc_ValueError,
2923 "Cannot set session for server-side SSLSocket.");
2924 return -1;
2925 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002926 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002927 PyErr_SetString(PyExc_ValueError,
2928 "Cannot set session after handshake.");
2929 return -1;
2930 }
2931#ifdef OPENSSL_VERSION_1_1
2932 /* duplicate session */
2933 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2934 return -1;
2935 }
2936 result = SSL_set_session(self->ssl, session);
2937 /* free duplicate, SSL_set_session() bumps ref count */
2938 SSL_SESSION_free(session);
2939#else
2940 result = SSL_set_session(self->ssl, pysess->session);
2941#endif
2942 if (result == 0) {
2943 _setSSLError(NULL, 0, __FILE__, __LINE__);
2944 return -1;
2945 }
2946 return 0;
2947}
2948
2949PyDoc_STRVAR(PySSL_set_session_doc,
2950"_setter_session(session)\n\
2951\
2952Get / set SSLSession.");
2953
2954static PyObject *
2955PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2956 if (SSL_session_reused(self->ssl)) {
2957 Py_RETURN_TRUE;
2958 } else {
2959 Py_RETURN_FALSE;
2960 }
2961}
2962
2963PyDoc_STRVAR(PySSL_get_session_reused_doc,
2964"Was the client session reused during handshake?");
2965
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002966static PyGetSetDef ssl_getsetlist[] = {
2967 {"context", (getter) PySSL_get_context,
2968 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002969 {"server_side", (getter) PySSL_get_server_side, NULL,
2970 PySSL_get_server_side_doc},
2971 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2972 PySSL_get_server_hostname_doc},
2973 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2974 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002975 {"session", (getter) PySSL_get_session,
2976 (setter) PySSL_set_session, PySSL_set_session_doc},
2977 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2978 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002979 {NULL}, /* sentinel */
2980};
2981
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002982static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002983 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2984 _SSL__SSLSOCKET_WRITE_METHODDEF
2985 _SSL__SSLSOCKET_READ_METHODDEF
2986 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002987 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2988 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002989 _SSL__SSLSOCKET_CIPHER_METHODDEF
2990 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2991 _SSL__SSLSOCKET_VERSION_METHODDEF
2992 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2993 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2994 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2995 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002996 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002997 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002998};
2999
Antoine Pitrou152efa22010-05-16 18:19:27 +00003000static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003001 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00003002 "_ssl._SSLSocket", /*tp_name*/
3003 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003004 0, /*tp_itemsize*/
3005 /* methods */
3006 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003007 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003008 0, /*tp_getattr*/
3009 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003010 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003011 0, /*tp_repr*/
3012 0, /*tp_as_number*/
3013 0, /*tp_as_sequence*/
3014 0, /*tp_as_mapping*/
3015 0, /*tp_hash*/
3016 0, /*tp_call*/
3017 0, /*tp_str*/
3018 0, /*tp_getattro*/
3019 0, /*tp_setattro*/
3020 0, /*tp_as_buffer*/
3021 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3022 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003023 (traverseproc) PySSL_traverse, /*tp_traverse*/
3024 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003025 0, /*tp_richcompare*/
3026 0, /*tp_weaklistoffset*/
3027 0, /*tp_iter*/
3028 0, /*tp_iternext*/
3029 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003030 0, /*tp_members*/
3031 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003032};
3033
Antoine Pitrou152efa22010-05-16 18:19:27 +00003034
3035/*
3036 * _SSLContext objects
3037 */
3038
Christian Heimes5fe668c2016-09-12 00:01:11 +02003039static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003040_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003041{
3042 int mode;
3043 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3044
3045 switch(n) {
3046 case PY_SSL_CERT_NONE:
3047 mode = SSL_VERIFY_NONE;
3048 break;
3049 case PY_SSL_CERT_OPTIONAL:
3050 mode = SSL_VERIFY_PEER;
3051 break;
3052 case PY_SSL_CERT_REQUIRED:
3053 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3054 break;
3055 default:
3056 PyErr_SetString(PyExc_ValueError,
3057 "invalid value for verify_mode");
3058 return -1;
3059 }
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003060
3061 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3062 * server sockets and SSL_set_post_handshake_auth() for client. */
3063
Christian Heimes5fe668c2016-09-12 00:01:11 +02003064 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003065 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3066 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003067 return 0;
3068}
3069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003070/*[clinic input]
3071@classmethod
3072_ssl._SSLContext.__new__
3073 protocol as proto_version: int
3074 /
3075[clinic start generated code]*/
3076
Antoine Pitrou152efa22010-05-16 18:19:27 +00003077static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003078_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3079/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003080{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003081 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003082 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003083 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003084 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003085 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003086#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003087 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003088#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090 PySSL_BEGIN_ALLOW_THREADS
3091 if (proto_version == PY_SSL_VERSION_TLS1)
3092 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003093#if HAVE_TLSv1_2
3094 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3095 ctx = SSL_CTX_new(TLSv1_1_method());
3096 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3097 ctx = SSL_CTX_new(TLSv1_2_method());
3098#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003099#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100 else if (proto_version == PY_SSL_VERSION_SSL3)
3101 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003102#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003103#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003104 else if (proto_version == PY_SSL_VERSION_SSL2)
3105 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003106#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003107 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003108 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003109 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3110 ctx = SSL_CTX_new(TLS_client_method());
3111 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3112 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003113 else
3114 proto_version = -1;
3115 PySSL_END_ALLOW_THREADS
3116
3117 if (proto_version == -1) {
3118 PyErr_SetString(PyExc_ValueError,
3119 "invalid protocol version");
3120 return NULL;
3121 }
3122 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003123 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003124 return NULL;
3125 }
3126
3127 assert(type != NULL && type->tp_alloc != NULL);
3128 self = (PySSLContext *) type->tp_alloc(type, 0);
3129 if (self == NULL) {
3130 SSL_CTX_free(ctx);
3131 return NULL;
3132 }
3133 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003134 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003135 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003136 self->msg_cb = NULL;
3137#ifdef HAVE_OPENSSL_KEYLOG
3138 self->keylog_filename = NULL;
3139 self->keylog_bio = NULL;
3140#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003141#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003142 self->npn_protocols = NULL;
3143#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003144#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003145 self->alpn_protocols = NULL;
3146#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003147#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003148 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003149#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003150 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003151 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3152 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003153 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003154 Py_DECREF(self);
3155 return NULL;
3156 }
3157 } else {
3158 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003159 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003160 Py_DECREF(self);
3161 return NULL;
3162 }
3163 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003164 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003165 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3166 if (proto_version != PY_SSL_VERSION_SSL2)
3167 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003168 if (proto_version != PY_SSL_VERSION_SSL3)
3169 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003170 /* Minimal security flags for server and client side context.
3171 * Client sockets ignore server-side parameters. */
3172#ifdef SSL_OP_NO_COMPRESSION
3173 options |= SSL_OP_NO_COMPRESSION;
3174#endif
3175#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3176 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3177#endif
3178#ifdef SSL_OP_SINGLE_DH_USE
3179 options |= SSL_OP_SINGLE_DH_USE;
3180#endif
3181#ifdef SSL_OP_SINGLE_ECDH_USE
3182 options |= SSL_OP_SINGLE_ECDH_USE;
3183#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003184 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003185
Semen Zhydenko1295e112017-10-15 21:28:31 +02003186 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003187 * It's far from perfect but gives users a better head start. */
3188 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003189#if PY_SSL_DEFAULT_CIPHERS == 2
3190 /* stick to OpenSSL's default settings */
3191 result = 1;
3192#else
3193 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3194#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003195 } else {
3196 /* SSLv2 needs MD5 */
3197 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3198 }
3199 if (result == 0) {
3200 Py_DECREF(self);
3201 ERR_clear_error();
3202 PyErr_SetString(PySSLErrorObject,
3203 "No cipher can be selected.");
3204 return NULL;
3205 }
3206
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003207#if defined(SSL_MODE_RELEASE_BUFFERS)
3208 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3209 usage for no cost at all. However, don't do this for OpenSSL versions
3210 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3211 2014-0198. I can't find exactly which beta fixed this CVE, so be
3212 conservative and assume it wasn't fixed until release. We do this check
3213 at runtime to avoid problems from the dynamic linker.
3214 See #25672 for more on this. */
3215 libver = SSLeay();
3216 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3217 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3218 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3219 }
3220#endif
3221
3222
Donald Stufft8ae264c2017-03-02 11:45:29 -05003223#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003224 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3225 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003226 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3227 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003228#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003229 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3230#else
3231 {
3232 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3233 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3234 EC_KEY_free(key);
3235 }
3236#endif
3237#endif
3238
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003239#define SID_CTX "Python"
3240 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3241 sizeof(SID_CTX));
3242#undef SID_CTX
3243
Christian Heimes61d478c2018-01-27 15:51:38 +01003244 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003245#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003246 /* Improve trust chain building when cross-signed intermediate
3247 certificates are present. See https://bugs.python.org/issue23476. */
3248 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003249#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003250 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003251
Christian Heimes9fb051f2018-09-23 08:32:31 +02003252#ifdef TLS1_3_VERSION
3253 self->post_handshake_auth = 0;
3254 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3255#endif
3256
Antoine Pitrou152efa22010-05-16 18:19:27 +00003257 return (PyObject *)self;
3258}
3259
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003260static int
3261context_traverse(PySSLContext *self, visitproc visit, void *arg)
3262{
3263#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003264 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003265#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003266 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003267 return 0;
3268}
3269
3270static int
3271context_clear(PySSLContext *self)
3272{
3273#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003274 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003275#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003276 Py_CLEAR(self->msg_cb);
3277#ifdef HAVE_OPENSSL_KEYLOG
3278 Py_CLEAR(self->keylog_filename);
3279 if (self->keylog_bio != NULL) {
3280 PySSL_BEGIN_ALLOW_THREADS
3281 BIO_free_all(self->keylog_bio);
3282 PySSL_END_ALLOW_THREADS
3283 self->keylog_bio = NULL;
3284 }
3285#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003286 return 0;
3287}
3288
Antoine Pitrou152efa22010-05-16 18:19:27 +00003289static void
3290context_dealloc(PySSLContext *self)
3291{
INADA Naokia6296d32017-08-24 14:55:17 +09003292 /* bpo-31095: UnTrack is needed before calling any callbacks */
3293 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003294 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003295 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003296#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003297 PyMem_FREE(self->npn_protocols);
3298#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003299#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003300 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003301#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003302 Py_TYPE(self)->tp_free(self);
3303}
3304
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003305/*[clinic input]
3306_ssl._SSLContext.set_ciphers
3307 cipherlist: str
3308 /
3309[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003311static PyObject *
3312_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3313/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3314{
3315 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003317 /* Clearing the error queue is necessary on some OpenSSL versions,
3318 otherwise the error will be reported again when another SSL call
3319 is done. */
3320 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003321 PyErr_SetString(PySSLErrorObject,
3322 "No cipher can be selected.");
3323 return NULL;
3324 }
3325 Py_RETURN_NONE;
3326}
3327
Christian Heimes25bfcd52016-09-06 00:04:45 +02003328#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3329/*[clinic input]
3330_ssl._SSLContext.get_ciphers
3331[clinic start generated code]*/
3332
3333static PyObject *
3334_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3335/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3336{
3337 SSL *ssl = NULL;
3338 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003339 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003340 int i=0;
3341 PyObject *result = NULL, *dct;
3342
3343 ssl = SSL_new(self->ctx);
3344 if (ssl == NULL) {
3345 _setSSLError(NULL, 0, __FILE__, __LINE__);
3346 goto exit;
3347 }
3348 sk = SSL_get_ciphers(ssl);
3349
3350 result = PyList_New(sk_SSL_CIPHER_num(sk));
3351 if (result == NULL) {
3352 goto exit;
3353 }
3354
3355 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3356 cipher = sk_SSL_CIPHER_value(sk, i);
3357 dct = cipher_to_dict(cipher);
3358 if (dct == NULL) {
3359 Py_CLEAR(result);
3360 goto exit;
3361 }
3362 PyList_SET_ITEM(result, i, dct);
3363 }
3364
3365 exit:
3366 if (ssl != NULL)
3367 SSL_free(ssl);
3368 return result;
3369
3370}
3371#endif
3372
3373
Christian Heimes29eab552018-02-25 12:31:33 +01003374#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003375static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003376do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3377 const unsigned char *server_protocols, unsigned int server_protocols_len,
3378 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003379{
Benjamin Peterson88615022015-01-23 17:30:26 -05003380 int ret;
3381 if (client_protocols == NULL) {
3382 client_protocols = (unsigned char *)"";
3383 client_protocols_len = 0;
3384 }
3385 if (server_protocols == NULL) {
3386 server_protocols = (unsigned char *)"";
3387 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003388 }
3389
Benjamin Peterson88615022015-01-23 17:30:26 -05003390 ret = SSL_select_next_proto(out, outlen,
3391 server_protocols, server_protocols_len,
3392 client_protocols, client_protocols_len);
3393 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3394 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003395
3396 return SSL_TLSEXT_ERR_OK;
3397}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003398#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003399
Christian Heimes29eab552018-02-25 12:31:33 +01003400#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003401/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3402static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003403_advertiseNPN_cb(SSL *s,
3404 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003405 void *args)
3406{
3407 PySSLContext *ssl_ctx = (PySSLContext *) args;
3408
3409 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003410 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003411 *len = 0;
3412 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003413 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003414 *len = ssl_ctx->npn_protocols_len;
3415 }
3416
3417 return SSL_TLSEXT_ERR_OK;
3418}
3419/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3420static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003421_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003422 unsigned char **out, unsigned char *outlen,
3423 const unsigned char *server, unsigned int server_len,
3424 void *args)
3425{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003426 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003427 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003428 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003429}
3430#endif
3431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003432/*[clinic input]
3433_ssl._SSLContext._set_npn_protocols
3434 protos: Py_buffer
3435 /
3436[clinic start generated code]*/
3437
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003438static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003439_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3440 Py_buffer *protos)
3441/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003442{
Christian Heimes29eab552018-02-25 12:31:33 +01003443#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003444 PyMem_Free(self->npn_protocols);
3445 self->npn_protocols = PyMem_Malloc(protos->len);
3446 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003447 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003448 memcpy(self->npn_protocols, protos->buf, protos->len);
3449 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003450
3451 /* set both server and client callbacks, because the context can
3452 * be used to create both types of sockets */
3453 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3454 _advertiseNPN_cb,
3455 self);
3456 SSL_CTX_set_next_proto_select_cb(self->ctx,
3457 _selectNPN_cb,
3458 self);
3459
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003460 Py_RETURN_NONE;
3461#else
3462 PyErr_SetString(PyExc_NotImplementedError,
3463 "The NPN extension requires OpenSSL 1.0.1 or later.");
3464 return NULL;
3465#endif
3466}
3467
Christian Heimes29eab552018-02-25 12:31:33 +01003468#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003469static int
3470_selectALPN_cb(SSL *s,
3471 const unsigned char **out, unsigned char *outlen,
3472 const unsigned char *client_protocols, unsigned int client_protocols_len,
3473 void *args)
3474{
3475 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003476 return do_protocol_selection(1, (unsigned char **)out, outlen,
3477 ctx->alpn_protocols, ctx->alpn_protocols_len,
3478 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003479}
3480#endif
3481
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003482/*[clinic input]
3483_ssl._SSLContext._set_alpn_protocols
3484 protos: Py_buffer
3485 /
3486[clinic start generated code]*/
3487
Benjamin Petersoncca27322015-01-23 16:35:37 -05003488static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003489_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3490 Py_buffer *protos)
3491/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003492{
Christian Heimes29eab552018-02-25 12:31:33 +01003493#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003494 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003495 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003496 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003497 return NULL;
3498 }
3499
Benjamin Petersoncca27322015-01-23 16:35:37 -05003500 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003501 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003502 if (!self->alpn_protocols)
3503 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003504 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003505 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003506
3507 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3508 return PyErr_NoMemory();
3509 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3510
Benjamin Petersoncca27322015-01-23 16:35:37 -05003511 Py_RETURN_NONE;
3512#else
3513 PyErr_SetString(PyExc_NotImplementedError,
3514 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3515 return NULL;
3516#endif
3517}
3518
Antoine Pitrou152efa22010-05-16 18:19:27 +00003519static PyObject *
3520get_verify_mode(PySSLContext *self, void *c)
3521{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003522 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3523 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3524 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3525 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003526 case SSL_VERIFY_NONE:
3527 return PyLong_FromLong(PY_SSL_CERT_NONE);
3528 case SSL_VERIFY_PEER:
3529 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3530 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3531 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3532 }
3533 PyErr_SetString(PySSLErrorObject,
3534 "invalid return value from SSL_CTX_get_verify_mode");
3535 return NULL;
3536}
3537
3538static int
3539set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3540{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003541 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003542 if (!PyArg_Parse(arg, "i", &n))
3543 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003544 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003545 PyErr_SetString(PyExc_ValueError,
3546 "Cannot set verify_mode to CERT_NONE when "
3547 "check_hostname is enabled.");
3548 return -1;
3549 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003550 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003551}
3552
3553static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003554get_verify_flags(PySSLContext *self, void *c)
3555{
Christian Heimes598894f2016-09-05 23:19:05 +02003556 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003557 unsigned long flags;
3558
Christian Heimes61d478c2018-01-27 15:51:38 +01003559 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003560 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003561 return PyLong_FromUnsignedLong(flags);
3562}
3563
3564static int
3565set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3566{
Christian Heimes598894f2016-09-05 23:19:05 +02003567 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003568 unsigned long new_flags, flags, set, clear;
3569
3570 if (!PyArg_Parse(arg, "k", &new_flags))
3571 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003572 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003573 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003574 clear = flags & ~new_flags;
3575 set = ~flags & new_flags;
3576 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003577 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003578 _setSSLError(NULL, 0, __FILE__, __LINE__);
3579 return -1;
3580 }
3581 }
3582 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003583 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003584 _setSSLError(NULL, 0, __FILE__, __LINE__);
3585 return -1;
3586 }
3587 }
3588 return 0;
3589}
3590
Christian Heimes698dde12018-02-27 11:54:43 +01003591/* Getter and setter for protocol version */
3592#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3593
3594
3595static int
3596set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3597{
3598 long v;
3599 int result;
3600
3601 if (!PyArg_Parse(arg, "l", &v))
3602 return -1;
3603 if (v > INT_MAX) {
3604 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3605 return -1;
3606 }
3607
3608 switch(self->protocol) {
3609 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3610 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3611 case PY_SSL_VERSION_TLS:
3612 break;
3613 default:
3614 PyErr_SetString(
3615 PyExc_ValueError,
3616 "The context's protocol doesn't support modification of "
3617 "highest and lowest version."
3618 );
3619 return -1;
3620 }
3621
3622 if (what == 0) {
3623 switch(v) {
3624 case PY_PROTO_MINIMUM_SUPPORTED:
3625 v = 0;
3626 break;
3627 case PY_PROTO_MAXIMUM_SUPPORTED:
3628 /* Emulate max for set_min_proto_version */
3629 v = PY_PROTO_MAXIMUM_AVAILABLE;
3630 break;
3631 default:
3632 break;
3633 }
3634 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3635 }
3636 else {
3637 switch(v) {
3638 case PY_PROTO_MAXIMUM_SUPPORTED:
3639 v = 0;
3640 break;
3641 case PY_PROTO_MINIMUM_SUPPORTED:
3642 /* Emulate max for set_min_proto_version */
3643 v = PY_PROTO_MINIMUM_AVAILABLE;
3644 break;
3645 default:
3646 break;
3647 }
3648 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3649 }
3650 if (result == 0) {
3651 PyErr_Format(PyExc_ValueError,
3652 "Unsupported protocol version 0x%x", v);
3653 return -1;
3654 }
3655 return 0;
3656}
3657
3658static PyObject *
3659get_minimum_version(PySSLContext *self, void *c)
3660{
3661 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3662 if (v == 0) {
3663 v = PY_PROTO_MINIMUM_SUPPORTED;
3664 }
3665 return PyLong_FromLong(v);
3666}
3667
3668static int
3669set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3670{
3671 return set_min_max_proto_version(self, arg, 0);
3672}
3673
3674static PyObject *
3675get_maximum_version(PySSLContext *self, void *c)
3676{
3677 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3678 if (v == 0) {
3679 v = PY_PROTO_MAXIMUM_SUPPORTED;
3680 }
3681 return PyLong_FromLong(v);
3682}
3683
3684static int
3685set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3686{
3687 return set_min_max_proto_version(self, arg, 1);
3688}
3689#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3690
Christian Heimes78c7d522019-06-03 21:00:10 +02003691#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3692static PyObject *
3693get_num_tickets(PySSLContext *self, void *c)
3694{
Miss Islington (bot)bbad6952019-07-09 05:42:49 -07003695 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003696}
3697
3698static int
3699set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3700{
3701 long num;
3702 if (!PyArg_Parse(arg, "l", &num))
3703 return -1;
3704 if (num < 0) {
3705 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3706 return -1;
3707 }
3708 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3709 PyErr_SetString(PyExc_ValueError,
3710 "SSLContext is not a server context.");
3711 return -1;
3712 }
3713 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3714 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3715 return -1;
3716 }
3717 return 0;
3718}
3719
3720PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3721"Control the number of TLSv1.3 session tickets");
3722#endif /* OpenSSL 1.1.1 */
3723
Christian Heimes22587792013-11-21 23:56:13 +01003724static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003725get_options(PySSLContext *self, void *c)
3726{
3727 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3728}
3729
3730static int
3731set_options(PySSLContext *self, PyObject *arg, void *c)
3732{
3733 long new_opts, opts, set, clear;
3734 if (!PyArg_Parse(arg, "l", &new_opts))
3735 return -1;
3736 opts = SSL_CTX_get_options(self->ctx);
3737 clear = opts & ~new_opts;
3738 set = ~opts & new_opts;
3739 if (clear) {
3740#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3741 SSL_CTX_clear_options(self->ctx, clear);
3742#else
3743 PyErr_SetString(PyExc_ValueError,
3744 "can't clear options before OpenSSL 0.9.8m");
3745 return -1;
3746#endif
3747 }
3748 if (set)
3749 SSL_CTX_set_options(self->ctx, set);
3750 return 0;
3751}
3752
Christian Heimes1aa9a752013-12-02 02:41:19 +01003753static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003754get_host_flags(PySSLContext *self, void *c)
3755{
3756 return PyLong_FromUnsignedLong(self->hostflags);
3757}
3758
3759static int
3760set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3761{
3762 X509_VERIFY_PARAM *param;
3763 unsigned int new_flags = 0;
3764
3765 if (!PyArg_Parse(arg, "I", &new_flags))
3766 return -1;
3767
3768 param = SSL_CTX_get0_param(self->ctx);
3769 self->hostflags = new_flags;
3770 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3771 return 0;
3772}
3773
3774static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003775get_check_hostname(PySSLContext *self, void *c)
3776{
3777 return PyBool_FromLong(self->check_hostname);
3778}
3779
3780static int
3781set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3782{
3783 int check_hostname;
3784 if (!PyArg_Parse(arg, "p", &check_hostname))
3785 return -1;
3786 if (check_hostname &&
3787 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003788 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003789 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003790 return -1;
3791 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003792 }
3793 self->check_hostname = check_hostname;
3794 return 0;
3795}
3796
Christian Heimes11a14932018-02-24 02:35:08 +01003797static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003798get_post_handshake_auth(PySSLContext *self, void *c) {
3799#if TLS1_3_VERSION
3800 return PyBool_FromLong(self->post_handshake_auth);
3801#else
3802 Py_RETURN_NONE;
3803#endif
3804}
3805
3806#if TLS1_3_VERSION
3807static int
3808set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003809 if (arg == NULL) {
3810 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3811 return -1;
3812 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003813 int pha = PyObject_IsTrue(arg);
3814
3815 if (pha == -1) {
3816 return -1;
3817 }
3818 self->post_handshake_auth = pha;
3819
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003820 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3821 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003822
3823 return 0;
3824}
3825#endif
3826
3827static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003828get_protocol(PySSLContext *self, void *c) {
3829 return PyLong_FromLong(self->protocol);
3830}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003831
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003832typedef struct {
3833 PyThreadState *thread_state;
3834 PyObject *callable;
3835 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003836 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003837 int error;
3838} _PySSLPasswordInfo;
3839
3840static int
3841_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3842 const char *bad_type_error)
3843{
3844 /* Set the password and size fields of a _PySSLPasswordInfo struct
3845 from a unicode, bytes, or byte array object.
3846 The password field will be dynamically allocated and must be freed
3847 by the caller */
3848 PyObject *password_bytes = NULL;
3849 const char *data = NULL;
3850 Py_ssize_t size;
3851
3852 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003853 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003854 if (!password_bytes) {
3855 goto error;
3856 }
3857 data = PyBytes_AS_STRING(password_bytes);
3858 size = PyBytes_GET_SIZE(password_bytes);
3859 } else if (PyBytes_Check(password)) {
3860 data = PyBytes_AS_STRING(password);
3861 size = PyBytes_GET_SIZE(password);
3862 } else if (PyByteArray_Check(password)) {
3863 data = PyByteArray_AS_STRING(password);
3864 size = PyByteArray_GET_SIZE(password);
3865 } else {
3866 PyErr_SetString(PyExc_TypeError, bad_type_error);
3867 goto error;
3868 }
3869
Victor Stinner9ee02032013-06-23 15:08:23 +02003870 if (size > (Py_ssize_t)INT_MAX) {
3871 PyErr_Format(PyExc_ValueError,
3872 "password cannot be longer than %d bytes", INT_MAX);
3873 goto error;
3874 }
3875
Victor Stinner11ebff22013-07-07 17:07:52 +02003876 PyMem_Free(pw_info->password);
3877 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003878 if (!pw_info->password) {
3879 PyErr_SetString(PyExc_MemoryError,
3880 "unable to allocate password buffer");
3881 goto error;
3882 }
3883 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003884 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003885
3886 Py_XDECREF(password_bytes);
3887 return 1;
3888
3889error:
3890 Py_XDECREF(password_bytes);
3891 return 0;
3892}
3893
3894static int
3895_password_callback(char *buf, int size, int rwflag, void *userdata)
3896{
3897 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3898 PyObject *fn_ret = NULL;
3899
3900 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3901
3902 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003903 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003904 if (!fn_ret) {
3905 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3906 core python API, so we could use it to add a frame here */
3907 goto error;
3908 }
3909
3910 if (!_pwinfo_set(pw_info, fn_ret,
3911 "password callback must return a string")) {
3912 goto error;
3913 }
3914 Py_CLEAR(fn_ret);
3915 }
3916
3917 if (pw_info->size > size) {
3918 PyErr_Format(PyExc_ValueError,
3919 "password cannot be longer than %d bytes", size);
3920 goto error;
3921 }
3922
3923 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3924 memcpy(buf, pw_info->password, pw_info->size);
3925 return pw_info->size;
3926
3927error:
3928 Py_XDECREF(fn_ret);
3929 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3930 pw_info->error = 1;
3931 return -1;
3932}
3933
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003934/*[clinic input]
3935_ssl._SSLContext.load_cert_chain
3936 certfile: object
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003937 keyfile: object = None
3938 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003939
3940[clinic start generated code]*/
3941
Antoine Pitroub5218772010-05-21 09:56:06 +00003942static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003943_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3944 PyObject *keyfile, PyObject *password)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003945/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003946{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003947 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003948 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3949 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003950 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003951 int r;
3952
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003953 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003954 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003955 if (keyfile == Py_None)
3956 keyfile = NULL;
3957 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003958 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3959 PyErr_SetString(PyExc_TypeError,
3960 "certfile should be a valid filesystem path");
3961 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003962 return NULL;
3963 }
3964 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003965 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3966 PyErr_SetString(PyExc_TypeError,
3967 "keyfile should be a valid filesystem path");
3968 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003969 goto error;
3970 }
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003971 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003972 if (PyCallable_Check(password)) {
3973 pw_info.callable = password;
3974 } else if (!_pwinfo_set(&pw_info, password,
3975 "password should be a string or callable")) {
3976 goto error;
3977 }
3978 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3979 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3980 }
3981 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003982 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3983 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003984 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003985 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003986 if (pw_info.error) {
3987 ERR_clear_error();
3988 /* the password callback has already set the error information */
3989 }
3990 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003991 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003992 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003993 }
3994 else {
3995 _setSSLError(NULL, 0, __FILE__, __LINE__);
3996 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997 goto error;
3998 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003999 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02004000 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00004001 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4002 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004003 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4004 Py_CLEAR(keyfile_bytes);
4005 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004006 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004007 if (pw_info.error) {
4008 ERR_clear_error();
4009 /* the password callback has already set the error information */
4010 }
4011 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004012 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004013 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004014 }
4015 else {
4016 _setSSLError(NULL, 0, __FILE__, __LINE__);
4017 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004018 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004019 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004020 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004022 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023 if (r != 1) {
4024 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004025 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004026 }
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_RETURN_NONE;
4031
4032error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004033 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4034 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004035 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004036 Py_XDECREF(keyfile_bytes);
4037 Py_XDECREF(certfile_bytes);
4038 return NULL;
4039}
4040
Christian Heimesefff7062013-11-21 03:35:02 +01004041/* internal helper function, returns -1 on error
4042 */
4043static int
4044_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
4045 int filetype)
4046{
4047 BIO *biobuf = NULL;
4048 X509_STORE *store;
4049 int retval = 0, err, loaded = 0;
4050
4051 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4052
4053 if (len <= 0) {
4054 PyErr_SetString(PyExc_ValueError,
4055 "Empty certificate data");
4056 return -1;
4057 } else if (len > INT_MAX) {
4058 PyErr_SetString(PyExc_OverflowError,
4059 "Certificate data is too long.");
4060 return -1;
4061 }
4062
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004063 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004064 if (biobuf == NULL) {
4065 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4066 return -1;
4067 }
4068
4069 store = SSL_CTX_get_cert_store(self->ctx);
4070 assert(store != NULL);
4071
4072 while (1) {
4073 X509 *cert = NULL;
4074 int r;
4075
4076 if (filetype == SSL_FILETYPE_ASN1) {
4077 cert = d2i_X509_bio(biobuf, NULL);
4078 } else {
4079 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004080 SSL_CTX_get_default_passwd_cb(self->ctx),
4081 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4082 );
Christian Heimesefff7062013-11-21 03:35:02 +01004083 }
4084 if (cert == NULL) {
4085 break;
4086 }
4087 r = X509_STORE_add_cert(store, cert);
4088 X509_free(cert);
4089 if (!r) {
4090 err = ERR_peek_last_error();
4091 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4092 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4093 /* cert already in hash table, not an error */
4094 ERR_clear_error();
4095 } else {
4096 break;
4097 }
4098 }
4099 loaded++;
4100 }
4101
4102 err = ERR_peek_last_error();
4103 if ((filetype == SSL_FILETYPE_ASN1) &&
4104 (loaded > 0) &&
4105 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4106 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4107 /* EOF ASN1 file, not an error */
4108 ERR_clear_error();
4109 retval = 0;
4110 } else if ((filetype == SSL_FILETYPE_PEM) &&
4111 (loaded > 0) &&
4112 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4113 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4114 /* EOF PEM file, not an error */
4115 ERR_clear_error();
4116 retval = 0;
4117 } else {
4118 _setSSLError(NULL, 0, __FILE__, __LINE__);
4119 retval = -1;
4120 }
4121
4122 BIO_free(biobuf);
4123 return retval;
4124}
4125
4126
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004127/*[clinic input]
4128_ssl._SSLContext.load_verify_locations
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004129 cafile: object = None
4130 capath: object = None
4131 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004132
4133[clinic start generated code]*/
4134
Antoine Pitrou152efa22010-05-16 18:19:27 +00004135static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004136_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4137 PyObject *cafile,
4138 PyObject *capath,
4139 PyObject *cadata)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004140/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004141{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004142 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4143 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004144 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004145
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004146 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004147 if (cafile == Py_None)
4148 cafile = NULL;
4149 if (capath == Py_None)
4150 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004151 if (cadata == Py_None)
4152 cadata = NULL;
4153
4154 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004155 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004156 "cafile, capath and cadata cannot be all omitted");
4157 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004158 }
4159 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004160 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4161 PyErr_SetString(PyExc_TypeError,
4162 "cafile should be a valid filesystem path");
4163 }
Christian Heimesefff7062013-11-21 03:35:02 +01004164 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004165 }
4166 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004167 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4168 PyErr_SetString(PyExc_TypeError,
4169 "capath should be a valid filesystem path");
4170 }
Christian Heimesefff7062013-11-21 03:35:02 +01004171 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004172 }
Christian Heimesefff7062013-11-21 03:35:02 +01004173
4174 /* validata cadata type and load cadata */
4175 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004176 if (PyUnicode_Check(cadata)) {
4177 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4178 if (cadata_ascii == NULL) {
4179 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4180 goto invalid_cadata;
4181 }
4182 goto error;
4183 }
4184 r = _add_ca_certs(self,
4185 PyBytes_AS_STRING(cadata_ascii),
4186 PyBytes_GET_SIZE(cadata_ascii),
4187 SSL_FILETYPE_PEM);
4188 Py_DECREF(cadata_ascii);
4189 if (r == -1) {
4190 goto error;
4191 }
4192 }
4193 else if (PyObject_CheckBuffer(cadata)) {
4194 Py_buffer buf;
4195 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4196 goto error;
4197 }
Christian Heimesefff7062013-11-21 03:35:02 +01004198 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4199 PyBuffer_Release(&buf);
4200 PyErr_SetString(PyExc_TypeError,
4201 "cadata should be a contiguous buffer with "
4202 "a single dimension");
4203 goto error;
4204 }
4205 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4206 PyBuffer_Release(&buf);
4207 if (r == -1) {
4208 goto error;
4209 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004210 }
4211 else {
4212 invalid_cadata:
4213 PyErr_SetString(PyExc_TypeError,
4214 "cadata should be an ASCII string or a "
4215 "bytes-like object");
4216 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004217 }
4218 }
4219
4220 /* load cafile or capath */
4221 if (cafile || capath) {
4222 if (cafile)
4223 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4224 if (capath)
4225 capath_buf = PyBytes_AS_STRING(capath_bytes);
4226 PySSL_BEGIN_ALLOW_THREADS
4227 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4228 PySSL_END_ALLOW_THREADS
4229 if (r != 1) {
4230 ok = 0;
4231 if (errno != 0) {
4232 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004233 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004234 }
4235 else {
4236 _setSSLError(NULL, 0, __FILE__, __LINE__);
4237 }
4238 goto error;
4239 }
4240 }
4241 goto end;
4242
4243 error:
4244 ok = 0;
4245 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004246 Py_XDECREF(cafile_bytes);
4247 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004248 if (ok) {
4249 Py_RETURN_NONE;
4250 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004251 return NULL;
4252 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004253}
4254
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004255/*[clinic input]
4256_ssl._SSLContext.load_dh_params
4257 path as filepath: object
4258 /
4259
4260[clinic start generated code]*/
4261
Antoine Pitrou152efa22010-05-16 18:19:27 +00004262static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004263_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4264/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004265{
4266 FILE *f;
4267 DH *dh;
4268
Victor Stinnerdaf45552013-08-28 00:53:59 +02004269 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004270 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004271 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004272
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004273 errno = 0;
4274 PySSL_BEGIN_ALLOW_THREADS
4275 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004276 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004277 PySSL_END_ALLOW_THREADS
4278 if (dh == NULL) {
4279 if (errno != 0) {
4280 ERR_clear_error();
4281 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4282 }
4283 else {
4284 _setSSLError(NULL, 0, __FILE__, __LINE__);
4285 }
4286 return NULL;
4287 }
4288 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4289 _setSSLError(NULL, 0, __FILE__, __LINE__);
4290 DH_free(dh);
4291 Py_RETURN_NONE;
4292}
4293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004294/*[clinic input]
4295_ssl._SSLContext._wrap_socket
4296 sock: object(subclass_of="PySocketModule.Sock_Type")
4297 server_side: int
4298 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004299 *
4300 owner: object = None
4301 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004302
4303[clinic start generated code]*/
4304
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004305static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004306_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004307 int server_side, PyObject *hostname_obj,
4308 PyObject *owner, PyObject *session)
4309/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004310{
Antoine Pitroud5323212010-10-22 18:19:07 +00004311 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004312 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004313
Antoine Pitroud5323212010-10-22 18:19:07 +00004314 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004315 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004316 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004317 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004318 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004319 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004320
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004321 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4322 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004323 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004324 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004325 if (hostname != NULL)
4326 PyMem_Free(hostname);
4327 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004328}
4329
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004330/*[clinic input]
4331_ssl._SSLContext._wrap_bio
4332 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4333 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4334 server_side: int
4335 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004336 *
4337 owner: object = None
4338 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004339
4340[clinic start generated code]*/
4341
Antoine Pitroub0182c82010-10-12 20:09:02 +00004342static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004343_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4344 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004345 PyObject *hostname_obj, PyObject *owner,
4346 PyObject *session)
4347/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004348{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004349 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004350 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004351
4352 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004353 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004354 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004355 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004356 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004357 }
4358
4359 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004360 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004361 incoming, outgoing);
4362
4363 PyMem_Free(hostname);
4364 return res;
4365}
4366
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004367/*[clinic input]
4368_ssl._SSLContext.session_stats
4369[clinic start generated code]*/
4370
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004371static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004372_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4373/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004374{
4375 int r;
4376 PyObject *value, *stats = PyDict_New();
4377 if (!stats)
4378 return NULL;
4379
4380#define ADD_STATS(SSL_NAME, KEY_NAME) \
4381 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4382 if (value == NULL) \
4383 goto error; \
4384 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4385 Py_DECREF(value); \
4386 if (r < 0) \
4387 goto error;
4388
4389 ADD_STATS(number, "number");
4390 ADD_STATS(connect, "connect");
4391 ADD_STATS(connect_good, "connect_good");
4392 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4393 ADD_STATS(accept, "accept");
4394 ADD_STATS(accept_good, "accept_good");
4395 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4396 ADD_STATS(accept, "accept");
4397 ADD_STATS(hits, "hits");
4398 ADD_STATS(misses, "misses");
4399 ADD_STATS(timeouts, "timeouts");
4400 ADD_STATS(cache_full, "cache_full");
4401
4402#undef ADD_STATS
4403
4404 return stats;
4405
4406error:
4407 Py_DECREF(stats);
4408 return NULL;
4409}
4410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004411/*[clinic input]
4412_ssl._SSLContext.set_default_verify_paths
4413[clinic start generated code]*/
4414
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004415static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004416_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4417/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004418{
4419 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4420 _setSSLError(NULL, 0, __FILE__, __LINE__);
4421 return NULL;
4422 }
4423 Py_RETURN_NONE;
4424}
4425
Antoine Pitrou501da612011-12-21 09:27:41 +01004426#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004427/*[clinic input]
4428_ssl._SSLContext.set_ecdh_curve
4429 name: object
4430 /
4431
4432[clinic start generated code]*/
4433
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004434static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004435_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4436/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004437{
4438 PyObject *name_bytes;
4439 int nid;
4440 EC_KEY *key;
4441
4442 if (!PyUnicode_FSConverter(name, &name_bytes))
4443 return NULL;
4444 assert(PyBytes_Check(name_bytes));
4445 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4446 Py_DECREF(name_bytes);
4447 if (nid == 0) {
4448 PyErr_Format(PyExc_ValueError,
4449 "unknown elliptic curve name %R", name);
4450 return NULL;
4451 }
4452 key = EC_KEY_new_by_curve_name(nid);
4453 if (key == NULL) {
4454 _setSSLError(NULL, 0, __FILE__, __LINE__);
4455 return NULL;
4456 }
4457 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4458 EC_KEY_free(key);
4459 Py_RETURN_NONE;
4460}
Antoine Pitrou501da612011-12-21 09:27:41 +01004461#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004462
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004463#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004464static int
4465_servername_callback(SSL *s, int *al, void *args)
4466{
4467 int ret;
4468 PySSLContext *ssl_ctx = (PySSLContext *) args;
4469 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004470 PyObject *result;
4471 /* The high-level ssl.SSLSocket object */
4472 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004473 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004474 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004475
Christian Heimes11a14932018-02-24 02:35:08 +01004476 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004477 /* remove race condition in this the call back while if removing the
4478 * callback is in progress */
4479 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004480 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004481 }
4482
4483 ssl = SSL_get_app_data(s);
4484 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004485
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004486 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004487 * SSL connection and that has a .context attribute that can be changed to
4488 * identify the requested hostname. Since the official API is the Python
4489 * level API we want to pass the callback a Python level object rather than
4490 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4491 * SSLObject) that will be passed. Otherwise if there's a socket then that
4492 * will be passed. If both do not exist only then the C-level object is
4493 * passed. */
4494 if (ssl->owner)
4495 ssl_socket = PyWeakref_GetObject(ssl->owner);
4496 else if (ssl->Socket)
4497 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4498 else
4499 ssl_socket = (PyObject *) ssl;
4500
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004501 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004502 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004503 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004504
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004505 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004506 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004507 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004509 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004510 PyObject *servername_bytes;
4511 PyObject *servername_str;
4512
4513 servername_bytes = PyBytes_FromString(servername);
4514 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004515 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4516 goto error;
4517 }
Christian Heimes11a14932018-02-24 02:35:08 +01004518 /* server_hostname was encoded to an A-label by our caller; put it
4519 * back into a str object, but still as an A-label (bpo-28414)
4520 */
4521 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4522 Py_DECREF(servername_bytes);
4523 if (servername_str == NULL) {
4524 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004525 goto error;
4526 }
Christian Heimes11a14932018-02-24 02:35:08 +01004527 result = PyObject_CallFunctionObjArgs(
4528 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4529 ssl_ctx, NULL);
4530 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004531 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004532 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004533
4534 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004535 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004536 *al = SSL_AD_HANDSHAKE_FAILURE;
4537 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4538 }
4539 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004540 /* Result may be None, a SSLContext or an integer
4541 * None and SSLContext are OK, integer or other values are an error.
4542 */
4543 if (result == Py_None) {
4544 ret = SSL_TLSEXT_ERR_OK;
4545 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004546 *al = (int) PyLong_AsLong(result);
4547 if (PyErr_Occurred()) {
4548 PyErr_WriteUnraisable(result);
4549 *al = SSL_AD_INTERNAL_ERROR;
4550 }
4551 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4552 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004553 Py_DECREF(result);
4554 }
4555
4556 PyGILState_Release(gstate);
4557 return ret;
4558
4559error:
4560 Py_DECREF(ssl_socket);
4561 *al = SSL_AD_INTERNAL_ERROR;
4562 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4563 PyGILState_Release(gstate);
4564 return ret;
4565}
Antoine Pitroua5963382013-03-30 16:39:00 +01004566#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004567
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004568static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004569get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004570{
Christian Heimes11a14932018-02-24 02:35:08 +01004571 PyObject *cb = self->set_sni_cb;
4572 if (cb == NULL) {
4573 Py_RETURN_NONE;
4574 }
4575 Py_INCREF(cb);
4576 return cb;
4577}
4578
4579static int
4580set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4581{
4582 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4583 PyErr_SetString(PyExc_ValueError,
4584 "sni_callback cannot be set on TLS_CLIENT context");
4585 return -1;
4586 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004587#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004588 Py_CLEAR(self->set_sni_cb);
4589 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004590 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4591 }
4592 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004593 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004594 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4595 PyErr_SetString(PyExc_TypeError,
4596 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004597 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004598 }
Christian Heimes11a14932018-02-24 02:35:08 +01004599 Py_INCREF(arg);
4600 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004601 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4602 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4603 }
Christian Heimes11a14932018-02-24 02:35:08 +01004604 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004605#else
4606 PyErr_SetString(PyExc_NotImplementedError,
4607 "The TLS extension servername callback, "
4608 "SSL_CTX_set_tlsext_servername_callback, "
4609 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004610 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004611#endif
4612}
4613
Christian Heimes11a14932018-02-24 02:35:08 +01004614PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4615"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4616\n\
4617If the argument is None then the callback is disabled. The method is called\n\
4618with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4619See RFC 6066 for details of the SNI extension.");
4620
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004621/*[clinic input]
4622_ssl._SSLContext.cert_store_stats
4623
4624Returns quantities of loaded X.509 certificates.
4625
4626X.509 certificates with a CA extension and certificate revocation lists
4627inside the context's cert store.
4628
4629NOTE: Certificates in a capath directory aren't loaded unless they have
4630been used at least once.
4631[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004632
4633static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004634_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4635/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004636{
4637 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004638 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004639 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004640 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004641
4642 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004643 objs = X509_STORE_get0_objects(store);
4644 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4645 obj = sk_X509_OBJECT_value(objs, i);
4646 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004647 case X509_LU_X509:
4648 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004649 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004650 ca++;
4651 }
4652 break;
4653 case X509_LU_CRL:
4654 crl++;
4655 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004656 default:
4657 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4658 * As far as I can tell they are internal states and never
4659 * stored in a cert store */
4660 break;
4661 }
4662 }
4663 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4664 "x509_ca", ca);
4665}
4666
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004667/*[clinic input]
4668_ssl._SSLContext.get_ca_certs
4669 binary_form: bool = False
4670
4671Returns a list of dicts with information of loaded CA certs.
4672
4673If the optional argument is True, returns a DER-encoded copy of the CA
4674certificate.
4675
4676NOTE: Certificates in a capath directory aren't loaded unless they have
4677been used at least once.
4678[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004679
4680static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004681_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4682/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683{
4684 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004685 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004686 PyObject *ci = NULL, *rlist = NULL;
4687 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004688
4689 if ((rlist = PyList_New(0)) == NULL) {
4690 return NULL;
4691 }
4692
4693 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004694 objs = X509_STORE_get0_objects(store);
4695 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004696 X509_OBJECT *obj;
4697 X509 *cert;
4698
Christian Heimes598894f2016-09-05 23:19:05 +02004699 obj = sk_X509_OBJECT_value(objs, i);
4700 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004701 /* not a x509 cert */
4702 continue;
4703 }
4704 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004705 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004706 if (!X509_check_ca(cert)) {
4707 continue;
4708 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004709 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004710 ci = _certificate_to_der(cert);
4711 } else {
4712 ci = _decode_certificate(cert);
4713 }
4714 if (ci == NULL) {
4715 goto error;
4716 }
4717 if (PyList_Append(rlist, ci) == -1) {
4718 goto error;
4719 }
4720 Py_CLEAR(ci);
4721 }
4722 return rlist;
4723
4724 error:
4725 Py_XDECREF(ci);
4726 Py_XDECREF(rlist);
4727 return NULL;
4728}
4729
4730
Antoine Pitrou152efa22010-05-16 18:19:27 +00004731static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004732 {"check_hostname", (getter) get_check_hostname,
4733 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004734 {"_host_flags", (getter) get_host_flags,
4735 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004736#if SSL_CTRL_GET_MAX_PROTO_VERSION
4737 {"minimum_version", (getter) get_minimum_version,
4738 (setter) set_minimum_version, NULL},
4739 {"maximum_version", (getter) get_maximum_version,
4740 (setter) set_maximum_version, NULL},
4741#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004742#ifdef HAVE_OPENSSL_KEYLOG
4743 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4744 (setter) _PySSLContext_set_keylog_filename, NULL},
4745#endif
4746 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4747 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004748 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004749 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004750#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4751 {"num_tickets", (getter) get_num_tickets,
4752 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4753#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004754 {"options", (getter) get_options,
4755 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004756 {"post_handshake_auth", (getter) get_post_handshake_auth,
4757#ifdef TLS1_3_VERSION
4758 (setter) set_post_handshake_auth,
4759#else
4760 NULL,
4761#endif
4762 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004763 {"protocol", (getter) get_protocol,
4764 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004765 {"verify_flags", (getter) get_verify_flags,
4766 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004767 {"verify_mode", (getter) get_verify_mode,
4768 (setter) set_verify_mode, NULL},
4769 {NULL}, /* sentinel */
4770};
4771
4772static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004773 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4774 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4775 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4776 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4777 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4778 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4779 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4780 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4781 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4782 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4783 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004784 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4785 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004786 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004787 {NULL, NULL} /* sentinel */
4788};
4789
4790static PyTypeObject PySSLContext_Type = {
4791 PyVarObject_HEAD_INIT(NULL, 0)
4792 "_ssl._SSLContext", /*tp_name*/
4793 sizeof(PySSLContext), /*tp_basicsize*/
4794 0, /*tp_itemsize*/
4795 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004796 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004797 0, /*tp_getattr*/
4798 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004799 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004800 0, /*tp_repr*/
4801 0, /*tp_as_number*/
4802 0, /*tp_as_sequence*/
4803 0, /*tp_as_mapping*/
4804 0, /*tp_hash*/
4805 0, /*tp_call*/
4806 0, /*tp_str*/
4807 0, /*tp_getattro*/
4808 0, /*tp_setattro*/
4809 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004810 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004811 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004812 (traverseproc) context_traverse, /*tp_traverse*/
4813 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004814 0, /*tp_richcompare*/
4815 0, /*tp_weaklistoffset*/
4816 0, /*tp_iter*/
4817 0, /*tp_iternext*/
4818 context_methods, /*tp_methods*/
4819 0, /*tp_members*/
4820 context_getsetlist, /*tp_getset*/
4821 0, /*tp_base*/
4822 0, /*tp_dict*/
4823 0, /*tp_descr_get*/
4824 0, /*tp_descr_set*/
4825 0, /*tp_dictoffset*/
4826 0, /*tp_init*/
4827 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004828 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004829};
4830
4831
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004832/*
4833 * MemoryBIO objects
4834 */
4835
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004836/*[clinic input]
4837@classmethod
4838_ssl.MemoryBIO.__new__
4839
4840[clinic start generated code]*/
4841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004842static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004843_ssl_MemoryBIO_impl(PyTypeObject *type)
4844/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004845{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004846 BIO *bio;
4847 PySSLMemoryBIO *self;
4848
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004849 bio = BIO_new(BIO_s_mem());
4850 if (bio == NULL) {
4851 PyErr_SetString(PySSLErrorObject,
4852 "failed to allocate BIO");
4853 return NULL;
4854 }
4855 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4856 * just that no data is currently available. The SSL routines should retry
4857 * the read, which we can achieve by calling BIO_set_retry_read(). */
4858 BIO_set_retry_read(bio);
4859 BIO_set_mem_eof_return(bio, -1);
4860
4861 assert(type != NULL && type->tp_alloc != NULL);
4862 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4863 if (self == NULL) {
4864 BIO_free(bio);
4865 return NULL;
4866 }
4867 self->bio = bio;
4868 self->eof_written = 0;
4869
4870 return (PyObject *) self;
4871}
4872
4873static void
4874memory_bio_dealloc(PySSLMemoryBIO *self)
4875{
4876 BIO_free(self->bio);
4877 Py_TYPE(self)->tp_free(self);
4878}
4879
4880static PyObject *
4881memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4882{
Segev Finer5cff6372017-07-27 01:19:17 +03004883 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004884}
4885
4886PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4887"The number of bytes pending in the memory BIO.");
4888
4889static PyObject *
4890memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4891{
4892 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4893 && self->eof_written);
4894}
4895
4896PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4897"Whether the memory BIO is at EOF.");
4898
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004899/*[clinic input]
4900_ssl.MemoryBIO.read
4901 size as len: int = -1
4902 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004903
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004904Read up to size bytes from the memory BIO.
4905
4906If size is not specified, read the entire buffer.
4907If the return value is an empty bytes instance, this means either
4908EOF or that no data is available. Use the "eof" property to
4909distinguish between the two.
4910[clinic start generated code]*/
4911
4912static PyObject *
4913_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4914/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4915{
4916 int avail, nbytes;
4917 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004918
Segev Finer5cff6372017-07-27 01:19:17 +03004919 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004920 if ((len < 0) || (len > avail))
4921 len = avail;
4922
4923 result = PyBytes_FromStringAndSize(NULL, len);
4924 if ((result == NULL) || (len == 0))
4925 return result;
4926
4927 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004928 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004929 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004930 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004931 return NULL;
4932 }
4933
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004934 /* There should never be any short reads but check anyway. */
4935 if (nbytes < len) {
4936 _PyBytes_Resize(&result, nbytes);
4937 }
4938
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004939 return result;
4940}
4941
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004942/*[clinic input]
4943_ssl.MemoryBIO.write
4944 b: Py_buffer
4945 /
4946
4947Writes the bytes b into the memory BIO.
4948
4949Returns the number of bytes written.
4950[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004951
4952static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004953_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4954/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004955{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004956 int nbytes;
4957
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004958 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004959 PyErr_Format(PyExc_OverflowError,
4960 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004961 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004962 }
4963
4964 if (self->eof_written) {
4965 PyErr_SetString(PySSLErrorObject,
4966 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004967 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004968 }
4969
Segev Finer5cff6372017-07-27 01:19:17 +03004970 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971 if (nbytes < 0) {
4972 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004973 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004974 }
4975
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004976 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004977}
4978
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004979/*[clinic input]
4980_ssl.MemoryBIO.write_eof
4981
4982Write an EOF marker to the memory BIO.
4983
4984When all data has been read, the "eof" property will be True.
4985[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004986
4987static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004988_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4989/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004990{
4991 self->eof_written = 1;
4992 /* After an EOF is written, a zero return from read() should be a real EOF
4993 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4994 BIO_clear_retry_flags(self->bio);
4995 BIO_set_mem_eof_return(self->bio, 0);
4996
4997 Py_RETURN_NONE;
4998}
4999
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005000static PyGetSetDef memory_bio_getsetlist[] = {
5001 {"pending", (getter) memory_bio_get_pending, NULL,
5002 PySSL_memory_bio_pending_doc},
5003 {"eof", (getter) memory_bio_get_eof, NULL,
5004 PySSL_memory_bio_eof_doc},
5005 {NULL}, /* sentinel */
5006};
5007
5008static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005009 _SSL_MEMORYBIO_READ_METHODDEF
5010 _SSL_MEMORYBIO_WRITE_METHODDEF
5011 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005012 {NULL, NULL} /* sentinel */
5013};
5014
5015static PyTypeObject PySSLMemoryBIO_Type = {
5016 PyVarObject_HEAD_INIT(NULL, 0)
5017 "_ssl.MemoryBIO", /*tp_name*/
5018 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5019 0, /*tp_itemsize*/
5020 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005021 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005022 0, /*tp_getattr*/
5023 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005024 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005025 0, /*tp_repr*/
5026 0, /*tp_as_number*/
5027 0, /*tp_as_sequence*/
5028 0, /*tp_as_mapping*/
5029 0, /*tp_hash*/
5030 0, /*tp_call*/
5031 0, /*tp_str*/
5032 0, /*tp_getattro*/
5033 0, /*tp_setattro*/
5034 0, /*tp_as_buffer*/
5035 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5036 0, /*tp_doc*/
5037 0, /*tp_traverse*/
5038 0, /*tp_clear*/
5039 0, /*tp_richcompare*/
5040 0, /*tp_weaklistoffset*/
5041 0, /*tp_iter*/
5042 0, /*tp_iternext*/
5043 memory_bio_methods, /*tp_methods*/
5044 0, /*tp_members*/
5045 memory_bio_getsetlist, /*tp_getset*/
5046 0, /*tp_base*/
5047 0, /*tp_dict*/
5048 0, /*tp_descr_get*/
5049 0, /*tp_descr_set*/
5050 0, /*tp_dictoffset*/
5051 0, /*tp_init*/
5052 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005053 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005054};
5055
Antoine Pitrou152efa22010-05-16 18:19:27 +00005056
Christian Heimes99a65702016-09-10 23:44:53 +02005057/*
5058 * SSL Session object
5059 */
5060
5061static void
5062PySSLSession_dealloc(PySSLSession *self)
5063{
INADA Naokia6296d32017-08-24 14:55:17 +09005064 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005065 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005066 Py_XDECREF(self->ctx);
5067 if (self->session != NULL) {
5068 SSL_SESSION_free(self->session);
5069 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005070 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005071}
5072
5073static PyObject *
5074PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5075{
5076 int result;
5077
5078 if (left == NULL || right == NULL) {
5079 PyErr_BadInternalCall();
5080 return NULL;
5081 }
5082
5083 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5084 Py_RETURN_NOTIMPLEMENTED;
5085 }
5086
5087 if (left == right) {
5088 result = 0;
5089 } else {
5090 const unsigned char *left_id, *right_id;
5091 unsigned int left_len, right_len;
5092 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5093 &left_len);
5094 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5095 &right_len);
5096 if (left_len == right_len) {
5097 result = memcmp(left_id, right_id, left_len);
5098 } else {
5099 result = 1;
5100 }
5101 }
5102
5103 switch (op) {
5104 case Py_EQ:
5105 if (result == 0) {
5106 Py_RETURN_TRUE;
5107 } else {
5108 Py_RETURN_FALSE;
5109 }
5110 break;
5111 case Py_NE:
5112 if (result != 0) {
5113 Py_RETURN_TRUE;
5114 } else {
5115 Py_RETURN_FALSE;
5116 }
5117 break;
5118 case Py_LT:
5119 case Py_LE:
5120 case Py_GT:
5121 case Py_GE:
5122 Py_RETURN_NOTIMPLEMENTED;
5123 break;
5124 default:
5125 PyErr_BadArgument();
5126 return NULL;
5127 }
5128}
5129
5130static int
5131PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5132{
5133 Py_VISIT(self->ctx);
5134 return 0;
5135}
5136
5137static int
5138PySSLSession_clear(PySSLSession *self)
5139{
5140 Py_CLEAR(self->ctx);
5141 return 0;
5142}
5143
5144
5145static PyObject *
5146PySSLSession_get_time(PySSLSession *self, void *closure) {
5147 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5148}
5149
5150PyDoc_STRVAR(PySSLSession_get_time_doc,
5151"Session creation time (seconds since epoch).");
5152
5153
5154static PyObject *
5155PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5156 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5157}
5158
5159PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5160"Session timeout (delta in seconds).");
5161
5162
5163static PyObject *
5164PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5165 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5166 return PyLong_FromUnsignedLong(hint);
5167}
5168
5169PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5170"Ticket life time hint.");
5171
5172
5173static PyObject *
5174PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5175 const unsigned char *id;
5176 unsigned int len;
5177 id = SSL_SESSION_get_id(self->session, &len);
5178 return PyBytes_FromStringAndSize((const char *)id, len);
5179}
5180
5181PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5182"Session id");
5183
5184
5185static PyObject *
5186PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5187 if (SSL_SESSION_has_ticket(self->session)) {
5188 Py_RETURN_TRUE;
5189 } else {
5190 Py_RETURN_FALSE;
5191 }
5192}
5193
5194PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5195"Does the session contain a ticket?");
5196
5197
5198static PyGetSetDef PySSLSession_getsetlist[] = {
5199 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5200 PySSLSession_get_has_ticket_doc},
5201 {"id", (getter) PySSLSession_get_session_id, NULL,
5202 PySSLSession_get_session_id_doc},
5203 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5204 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5205 {"time", (getter) PySSLSession_get_time, NULL,
5206 PySSLSession_get_time_doc},
5207 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5208 PySSLSession_get_timeout_doc},
5209 {NULL}, /* sentinel */
5210};
5211
5212static PyTypeObject PySSLSession_Type = {
5213 PyVarObject_HEAD_INIT(NULL, 0)
5214 "_ssl.Session", /*tp_name*/
5215 sizeof(PySSLSession), /*tp_basicsize*/
5216 0, /*tp_itemsize*/
5217 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005218 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005219 0, /*tp_getattr*/
5220 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005221 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005222 0, /*tp_repr*/
5223 0, /*tp_as_number*/
5224 0, /*tp_as_sequence*/
5225 0, /*tp_as_mapping*/
5226 0, /*tp_hash*/
5227 0, /*tp_call*/
5228 0, /*tp_str*/
5229 0, /*tp_getattro*/
5230 0, /*tp_setattro*/
5231 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005232 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005233 0, /*tp_doc*/
5234 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5235 (inquiry)PySSLSession_clear, /*tp_clear*/
5236 PySSLSession_richcompare, /*tp_richcompare*/
5237 0, /*tp_weaklistoffset*/
5238 0, /*tp_iter*/
5239 0, /*tp_iternext*/
5240 0, /*tp_methods*/
5241 0, /*tp_members*/
5242 PySSLSession_getsetlist, /*tp_getset*/
5243};
5244
5245
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005246/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005247/*[clinic input]
5248_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005249 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005250 entropy: double
5251 /
5252
5253Mix string into the OpenSSL PRNG state.
5254
5255entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305256string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005257[clinic start generated code]*/
5258
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005259static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005260_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005261/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005262{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005263 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005264 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005265
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005266 buf = (const char *)view->buf;
5267 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005268 do {
5269 written = Py_MIN(len, INT_MAX);
5270 RAND_add(buf, (int)written, entropy);
5271 buf += written;
5272 len -= written;
5273 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005274 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005275}
5276
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005277static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005278PySSL_RAND(int len, int pseudo)
5279{
5280 int ok;
5281 PyObject *bytes;
5282 unsigned long err;
5283 const char *errstr;
5284 PyObject *v;
5285
Victor Stinner1e81a392013-12-19 16:47:04 +01005286 if (len < 0) {
5287 PyErr_SetString(PyExc_ValueError, "num must be positive");
5288 return NULL;
5289 }
5290
Victor Stinner99c8b162011-05-24 12:05:19 +02005291 bytes = PyBytes_FromStringAndSize(NULL, len);
5292 if (bytes == NULL)
5293 return NULL;
5294 if (pseudo) {
5295 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5296 if (ok == 0 || ok == 1)
5297 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5298 }
5299 else {
5300 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5301 if (ok == 1)
5302 return bytes;
5303 }
5304 Py_DECREF(bytes);
5305
5306 err = ERR_get_error();
5307 errstr = ERR_reason_error_string(err);
5308 v = Py_BuildValue("(ks)", err, errstr);
5309 if (v != NULL) {
5310 PyErr_SetObject(PySSLErrorObject, v);
5311 Py_DECREF(v);
5312 }
5313 return NULL;
5314}
5315
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005316/*[clinic input]
5317_ssl.RAND_bytes
5318 n: int
5319 /
5320
5321Generate n cryptographically strong pseudo-random bytes.
5322[clinic start generated code]*/
5323
Victor Stinner99c8b162011-05-24 12:05:19 +02005324static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005325_ssl_RAND_bytes_impl(PyObject *module, int n)
5326/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005327{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005328 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005329}
5330
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005331/*[clinic input]
5332_ssl.RAND_pseudo_bytes
5333 n: int
5334 /
5335
5336Generate n pseudo-random bytes.
5337
5338Return a pair (bytes, is_cryptographic). is_cryptographic is True
5339if the bytes generated are cryptographically strong.
5340[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005341
5342static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005343_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5344/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005345{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005346 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005347}
5348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005349/*[clinic input]
5350_ssl.RAND_status
5351
5352Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5353
5354It is necessary to seed the PRNG with RAND_add() on some platforms before
5355using the ssl() function.
5356[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005357
5358static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005359_ssl_RAND_status_impl(PyObject *module)
5360/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005361{
Christian Heimes217cfd12007-12-02 14:31:20 +00005362 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005363}
5364
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005365#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005366/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005367/*[clinic input]
5368_ssl.RAND_egd
5369 path: object(converter="PyUnicode_FSConverter")
5370 /
5371
5372Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5373
5374Returns number of bytes read. Raises SSLError if connection to EGD
5375fails or if it does not provide enough data to seed PRNG.
5376[clinic start generated code]*/
5377
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005378static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005379_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5380/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005381{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005382 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005383 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005384 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005385 PyErr_SetString(PySSLErrorObject,
5386 "EGD connection failed or EGD did not return "
5387 "enough data to seed the PRNG");
5388 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005389 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005390 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005391}
Christian Heimesa5d07652016-09-24 10:48:05 +02005392/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005393#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005394
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005395
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005396
5397/*[clinic input]
5398_ssl.get_default_verify_paths
5399
5400Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5401
5402The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5403[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005404
5405static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005406_ssl_get_default_verify_paths_impl(PyObject *module)
5407/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005408{
5409 PyObject *ofile_env = NULL;
5410 PyObject *ofile = NULL;
5411 PyObject *odir_env = NULL;
5412 PyObject *odir = NULL;
5413
Benjamin Petersond113c962015-07-18 10:59:13 -07005414#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005415 const char *tmp = (info); \
5416 target = NULL; \
5417 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5418 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5419 target = PyBytes_FromString(tmp); } \
5420 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005421 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005422
Benjamin Petersond113c962015-07-18 10:59:13 -07005423 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5424 CONVERT(X509_get_default_cert_file(), ofile);
5425 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5426 CONVERT(X509_get_default_cert_dir(), odir);
5427#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005428
Christian Heimes200bb1b2013-06-14 15:14:29 +02005429 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005430
5431 error:
5432 Py_XDECREF(ofile_env);
5433 Py_XDECREF(ofile);
5434 Py_XDECREF(odir_env);
5435 Py_XDECREF(odir);
5436 return NULL;
5437}
5438
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005439static PyObject*
5440asn1obj2py(ASN1_OBJECT *obj)
5441{
5442 int nid;
5443 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005444
5445 nid = OBJ_obj2nid(obj);
5446 if (nid == NID_undef) {
5447 PyErr_Format(PyExc_ValueError, "Unknown object");
5448 return NULL;
5449 }
5450 sn = OBJ_nid2sn(nid);
5451 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005452 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005453}
5454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005455/*[clinic input]
5456_ssl.txt2obj
5457 txt: str
5458 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005459
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005460Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5461
5462By default objects are looked up by OID. With name=True short and
5463long name are also matched.
5464[clinic start generated code]*/
5465
5466static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005467_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5468/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005469{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005470 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005471 ASN1_OBJECT *obj;
5472
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005473 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5474 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005475 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005476 return NULL;
5477 }
5478 result = asn1obj2py(obj);
5479 ASN1_OBJECT_free(obj);
5480 return result;
5481}
5482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005483/*[clinic input]
5484_ssl.nid2obj
5485 nid: int
5486 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005488Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5489[clinic start generated code]*/
5490
5491static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005492_ssl_nid2obj_impl(PyObject *module, int nid)
5493/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005494{
5495 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005496 ASN1_OBJECT *obj;
5497
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005498 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005499 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005500 return NULL;
5501 }
5502 obj = OBJ_nid2obj(nid);
5503 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005504 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005505 return NULL;
5506 }
5507 result = asn1obj2py(obj);
5508 ASN1_OBJECT_free(obj);
5509 return result;
5510}
5511
Christian Heimes46bebee2013-06-09 19:03:31 +02005512#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005513
5514static PyObject*
5515certEncodingType(DWORD encodingType)
5516{
5517 static PyObject *x509_asn = NULL;
5518 static PyObject *pkcs_7_asn = NULL;
5519
5520 if (x509_asn == NULL) {
5521 x509_asn = PyUnicode_InternFromString("x509_asn");
5522 if (x509_asn == NULL)
5523 return NULL;
5524 }
5525 if (pkcs_7_asn == NULL) {
5526 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5527 if (pkcs_7_asn == NULL)
5528 return NULL;
5529 }
5530 switch(encodingType) {
5531 case X509_ASN_ENCODING:
5532 Py_INCREF(x509_asn);
5533 return x509_asn;
5534 case PKCS_7_ASN_ENCODING:
5535 Py_INCREF(pkcs_7_asn);
5536 return pkcs_7_asn;
5537 default:
5538 return PyLong_FromLong(encodingType);
5539 }
5540}
5541
5542static PyObject*
5543parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5544{
5545 CERT_ENHKEY_USAGE *usage;
5546 DWORD size, error, i;
5547 PyObject *retval;
5548
5549 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5550 error = GetLastError();
5551 if (error == CRYPT_E_NOT_FOUND) {
5552 Py_RETURN_TRUE;
5553 }
5554 return PyErr_SetFromWindowsErr(error);
5555 }
5556
5557 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5558 if (usage == NULL) {
5559 return PyErr_NoMemory();
5560 }
5561
5562 /* Now get the actual enhanced usage property */
5563 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5564 PyMem_Free(usage);
5565 error = GetLastError();
5566 if (error == CRYPT_E_NOT_FOUND) {
5567 Py_RETURN_TRUE;
5568 }
5569 return PyErr_SetFromWindowsErr(error);
5570 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005571 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005572 if (retval == NULL) {
5573 goto error;
5574 }
5575 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5576 if (usage->rgpszUsageIdentifier[i]) {
5577 PyObject *oid;
5578 int err;
5579 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5580 if (oid == NULL) {
5581 Py_CLEAR(retval);
5582 goto error;
5583 }
5584 err = PySet_Add(retval, oid);
5585 Py_DECREF(oid);
5586 if (err == -1) {
5587 Py_CLEAR(retval);
5588 goto error;
5589 }
5590 }
5591 }
5592 error:
5593 PyMem_Free(usage);
5594 return retval;
5595}
5596
kctherookied93fbbf2019-03-29 00:59:06 +07005597static HCERTSTORE
5598ssl_collect_certificates(const char *store_name)
5599{
5600/* this function collects the system certificate stores listed in
5601 * system_stores into a collection certificate store for being
5602 * enumerated. The store must be readable to be added to the
5603 * store collection.
5604 */
5605
5606 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5607 static DWORD system_stores[] = {
5608 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5609 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5610 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5611 CERT_SYSTEM_STORE_CURRENT_USER,
5612 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5613 CERT_SYSTEM_STORE_SERVICES,
5614 CERT_SYSTEM_STORE_USERS};
5615 size_t i, storesAdded;
5616 BOOL result;
5617
5618 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5619 (HCRYPTPROV)NULL, 0, NULL);
5620 if (!hCollectionStore) {
5621 return NULL;
5622 }
5623 storesAdded = 0;
5624 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5625 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5626 (HCRYPTPROV)NULL,
5627 CERT_STORE_READONLY_FLAG |
5628 system_stores[i], store_name);
5629 if (hSystemStore) {
5630 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5631 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5632 if (result) {
5633 ++storesAdded;
5634 }
Steve Dower5d695b62019-09-09 06:48:22 -07005635 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005636 }
5637 }
5638 if (storesAdded == 0) {
5639 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5640 return NULL;
5641 }
5642
5643 return hCollectionStore;
5644}
5645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005646/*[clinic input]
5647_ssl.enum_certificates
5648 store_name: str
5649
5650Retrieve certificates from Windows' cert store.
5651
5652store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5653more cert storages, too. The function returns a list of (bytes,
5654encoding_type, trust) tuples. The encoding_type flag can be interpreted
5655with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5656a set of OIDs or the boolean True.
5657[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005658
Christian Heimes46bebee2013-06-09 19:03:31 +02005659static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005660_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5661/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005662{
kctherookied93fbbf2019-03-29 00:59:06 +07005663 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005664 PCCERT_CONTEXT pCertCtx = NULL;
5665 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005666 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005667
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005668 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005669 if (result == NULL) {
5670 return NULL;
5671 }
kctherookied93fbbf2019-03-29 00:59:06 +07005672 hCollectionStore = ssl_collect_certificates(store_name);
5673 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005674 Py_DECREF(result);
5675 return PyErr_SetFromWindowsErr(GetLastError());
5676 }
5677
kctherookied93fbbf2019-03-29 00:59:06 +07005678 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005679 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5680 pCertCtx->cbCertEncoded);
5681 if (!cert) {
5682 Py_CLEAR(result);
5683 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005684 }
Christian Heimes44109d72013-11-22 01:51:30 +01005685 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5686 Py_CLEAR(result);
5687 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005688 }
Christian Heimes44109d72013-11-22 01:51:30 +01005689 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5690 if (keyusage == Py_True) {
5691 Py_DECREF(keyusage);
5692 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005693 }
Christian Heimes44109d72013-11-22 01:51:30 +01005694 if (keyusage == NULL) {
5695 Py_CLEAR(result);
5696 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005697 }
Christian Heimes44109d72013-11-22 01:51:30 +01005698 if ((tup = PyTuple_New(3)) == NULL) {
5699 Py_CLEAR(result);
5700 break;
5701 }
5702 PyTuple_SET_ITEM(tup, 0, cert);
5703 cert = NULL;
5704 PyTuple_SET_ITEM(tup, 1, enc);
5705 enc = NULL;
5706 PyTuple_SET_ITEM(tup, 2, keyusage);
5707 keyusage = NULL;
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005708 if (PySet_Add(result, tup) == -1) {
5709 Py_CLEAR(result);
5710 Py_CLEAR(tup);
5711 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005712 }
5713 Py_CLEAR(tup);
5714 }
5715 if (pCertCtx) {
5716 /* loop ended with an error, need to clean up context manually */
5717 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005718 }
5719
5720 /* In error cases cert, enc and tup may not be NULL */
5721 Py_XDECREF(cert);
5722 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005723 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005724 Py_XDECREF(tup);
5725
kctherookied93fbbf2019-03-29 00:59:06 +07005726 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5727 associated with the store, in this case our collection store and the
5728 associated system stores. */
5729 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005730 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005731 Py_XDECREF(result);
5732 return PyErr_SetFromWindowsErr(GetLastError());
5733 }
kctherookied93fbbf2019-03-29 00:59:06 +07005734
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005735 /* convert set to list */
5736 if (result == NULL) {
5737 return NULL;
5738 } else {
5739 PyObject *lst = PySequence_List(result);
5740 Py_DECREF(result);
5741 return lst;
5742 }
Christian Heimes44109d72013-11-22 01:51:30 +01005743}
5744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005745/*[clinic input]
5746_ssl.enum_crls
5747 store_name: str
5748
5749Retrieve CRLs from Windows' cert store.
5750
5751store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5752more cert storages, too. The function returns a list of (bytes,
5753encoding_type) tuples. The encoding_type flag can be interpreted with
5754X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5755[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005756
5757static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005758_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5759/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005760{
kctherookied93fbbf2019-03-29 00:59:06 +07005761 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005762 PCCRL_CONTEXT pCrlCtx = NULL;
5763 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5764 PyObject *result = NULL;
5765
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005766 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005767 if (result == NULL) {
5768 return NULL;
5769 }
kctherookied93fbbf2019-03-29 00:59:06 +07005770 hCollectionStore = ssl_collect_certificates(store_name);
5771 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005772 Py_DECREF(result);
5773 return PyErr_SetFromWindowsErr(GetLastError());
5774 }
Christian Heimes44109d72013-11-22 01:51:30 +01005775
kctherookied93fbbf2019-03-29 00:59:06 +07005776 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005777 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5778 pCrlCtx->cbCrlEncoded);
5779 if (!crl) {
5780 Py_CLEAR(result);
5781 break;
5782 }
5783 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5784 Py_CLEAR(result);
5785 break;
5786 }
5787 if ((tup = PyTuple_New(2)) == NULL) {
5788 Py_CLEAR(result);
5789 break;
5790 }
5791 PyTuple_SET_ITEM(tup, 0, crl);
5792 crl = NULL;
5793 PyTuple_SET_ITEM(tup, 1, enc);
5794 enc = NULL;
5795
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005796 if (PySet_Add(result, tup) == -1) {
5797 Py_CLEAR(result);
5798 Py_CLEAR(tup);
5799 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005800 }
5801 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005802 }
Christian Heimes44109d72013-11-22 01:51:30 +01005803 if (pCrlCtx) {
5804 /* loop ended with an error, need to clean up context manually */
5805 CertFreeCRLContext(pCrlCtx);
5806 }
5807
5808 /* In error cases cert, enc and tup may not be NULL */
5809 Py_XDECREF(crl);
5810 Py_XDECREF(enc);
5811 Py_XDECREF(tup);
5812
kctherookied93fbbf2019-03-29 00:59:06 +07005813 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5814 associated with the store, in this case our collection store and the
5815 associated system stores. */
5816 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005817 /* This error case might shadow another exception.*/
5818 Py_XDECREF(result);
5819 return PyErr_SetFromWindowsErr(GetLastError());
5820 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005821 /* convert set to list */
5822 if (result == NULL) {
5823 return NULL;
5824 } else {
5825 PyObject *lst = PySequence_List(result);
5826 Py_DECREF(result);
5827 return lst;
5828 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005829}
Christian Heimes44109d72013-11-22 01:51:30 +01005830
5831#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005832
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005833/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005834static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005835 _SSL__TEST_DECODE_CERT_METHODDEF
5836 _SSL_RAND_ADD_METHODDEF
5837 _SSL_RAND_BYTES_METHODDEF
5838 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5839 _SSL_RAND_EGD_METHODDEF
5840 _SSL_RAND_STATUS_METHODDEF
5841 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5842 _SSL_ENUM_CERTIFICATES_METHODDEF
5843 _SSL_ENUM_CRLS_METHODDEF
5844 _SSL_TXT2OBJ_METHODDEF
5845 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005846 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005847};
5848
5849
Christian Heimes598894f2016-09-05 23:19:05 +02005850#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005851
5852/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005853 * of the Python C thread library
5854 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5855 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005856
5857static PyThread_type_lock *_ssl_locks = NULL;
5858
Christian Heimes4d98ca92013-08-19 17:36:29 +02005859#if OPENSSL_VERSION_NUMBER >= 0x10000000
5860/* use new CRYPTO_THREADID API. */
5861static void
5862_ssl_threadid_callback(CRYPTO_THREADID *id)
5863{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005864 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005865}
5866#else
5867/* deprecated CRYPTO_set_id_callback() API. */
5868static unsigned long
5869_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005870 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005871}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005872#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005873
Bill Janssen6e027db2007-11-15 22:23:56 +00005874static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005875 (int mode, int n, const char *file, int line) {
5876 /* this function is needed to perform locking on shared data
5877 structures. (Note that OpenSSL uses a number of global data
5878 structures that will be implicitly shared whenever multiple
5879 threads use OpenSSL.) Multi-threaded applications will
5880 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005882 locking_function() must be able to handle up to
5883 CRYPTO_num_locks() different mutex locks. It sets the n-th
5884 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005885
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005886 file and line are the file number of the function setting the
5887 lock. They can be useful for debugging.
5888 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005890 if ((_ssl_locks == NULL) ||
5891 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5892 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005894 if (mode & CRYPTO_LOCK) {
5895 PyThread_acquire_lock(_ssl_locks[n], 1);
5896 } else {
5897 PyThread_release_lock(_ssl_locks[n]);
5898 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005899}
5900
5901static int _setup_ssl_threads(void) {
5902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005903 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005905 if (_ssl_locks == NULL) {
5906 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005907 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5908 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005909 if (_ssl_locks == NULL) {
5910 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005911 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005912 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005913 for (i = 0; i < _ssl_locks_count; i++) {
5914 _ssl_locks[i] = PyThread_allocate_lock();
5915 if (_ssl_locks[i] == NULL) {
5916 unsigned int j;
5917 for (j = 0; j < i; j++) {
5918 PyThread_free_lock(_ssl_locks[j]);
5919 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005920 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005921 return 0;
5922 }
5923 }
5924 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005925#if OPENSSL_VERSION_NUMBER >= 0x10000000
5926 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5927#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005928 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005929#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005930 }
5931 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005932}
5933
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005934#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005935
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005936PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005937"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005938for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005939
Martin v. Löwis1a214512008-06-11 05:26:20 +00005940
5941static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005942 PyModuleDef_HEAD_INIT,
5943 "_ssl",
5944 module_doc,
5945 -1,
5946 PySSL_methods,
5947 NULL,
5948 NULL,
5949 NULL,
5950 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005951};
5952
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005953
5954static void
5955parse_openssl_version(unsigned long libver,
5956 unsigned int *major, unsigned int *minor,
5957 unsigned int *fix, unsigned int *patch,
5958 unsigned int *status)
5959{
5960 *status = libver & 0xF;
5961 libver >>= 4;
5962 *patch = libver & 0xFF;
5963 libver >>= 8;
5964 *fix = libver & 0xFF;
5965 libver >>= 8;
5966 *minor = libver & 0xFF;
5967 libver >>= 8;
5968 *major = libver & 0xFF;
5969}
5970
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005971PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005972PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005973{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005974 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005975 unsigned long libver;
5976 unsigned int major, minor, fix, patch, status;
5977 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005978 struct py_ssl_error_code *errcode;
5979 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005980
Antoine Pitrou152efa22010-05-16 18:19:27 +00005981 if (PyType_Ready(&PySSLContext_Type) < 0)
5982 return NULL;
5983 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005984 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005985 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5986 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005987 if (PyType_Ready(&PySSLSession_Type) < 0)
5988 return NULL;
5989
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005991 m = PyModule_Create(&_sslmodule);
5992 if (m == NULL)
5993 return NULL;
5994 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005996 /* Load _socket module and its C API */
5997 socket_api = PySocketModule_ImportModuleAndAPI();
5998 if (!socket_api)
5999 return NULL;
6000 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006001
Christian Heimesc941e622017-09-05 15:47:11 +02006002#ifndef OPENSSL_VERSION_1_1
6003 /* Load all algorithms and initialize cpuid */
6004 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006005 /* Init OpenSSL */
6006 SSL_load_error_strings();
6007 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006008#endif
6009
Christian Heimes598894f2016-09-05 23:19:05 +02006010#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006011 /* note that this will start threading if not already started */
6012 if (!_setup_ssl_threads()) {
6013 return NULL;
6014 }
Christian Heimes387c7442020-05-15 22:36:51 +02006015#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006016 /* OpenSSL 1.1.0 builtin thread support is enabled */
6017 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006018#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006020 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006021 sslerror_type_slots[0].pfunc = PyExc_OSError;
6022 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006023 if (PySSLErrorObject == NULL)
6024 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006025
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006026 /* ssl.CertificateError used to be a subclass of ValueError */
6027 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6028 if (bases == NULL)
6029 return NULL;
6030 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6031 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6032 bases, NULL);
6033 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006034 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6035 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6036 PySSLErrorObject, NULL);
6037 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6038 "ssl.SSLWantReadError", SSLWantReadError_doc,
6039 PySSLErrorObject, NULL);
6040 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6041 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6042 PySSLErrorObject, NULL);
6043 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6044 "ssl.SSLSyscallError", SSLSyscallError_doc,
6045 PySSLErrorObject, NULL);
6046 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6047 "ssl.SSLEOFError", SSLEOFError_doc,
6048 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006049 if (PySSLCertVerificationErrorObject == NULL
6050 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006051 || PySSLWantReadErrorObject == NULL
6052 || PySSLWantWriteErrorObject == NULL
6053 || PySSLSyscallErrorObject == NULL
6054 || PySSLEOFErrorObject == NULL)
6055 return NULL;
6056 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006057 || PyDict_SetItemString(d, "SSLCertVerificationError",
6058 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006059 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6060 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6061 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6062 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6063 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006064 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006065 if (PyDict_SetItemString(d, "_SSLContext",
6066 (PyObject *)&PySSLContext_Type) != 0)
6067 return NULL;
6068 if (PyDict_SetItemString(d, "_SSLSocket",
6069 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006070 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006071 if (PyDict_SetItemString(d, "MemoryBIO",
6072 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6073 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006074 if (PyDict_SetItemString(d, "SSLSession",
6075 (PyObject *)&PySSLSession_Type) != 0)
6076 return NULL;
6077
Christian Heimes892d66e2018-01-29 14:10:18 +01006078 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6079 PY_SSL_DEFAULT_CIPHER_STRING);
6080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006081 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6082 PY_SSL_ERROR_ZERO_RETURN);
6083 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6084 PY_SSL_ERROR_WANT_READ);
6085 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6086 PY_SSL_ERROR_WANT_WRITE);
6087 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6088 PY_SSL_ERROR_WANT_X509_LOOKUP);
6089 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6090 PY_SSL_ERROR_SYSCALL);
6091 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6092 PY_SSL_ERROR_SSL);
6093 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6094 PY_SSL_ERROR_WANT_CONNECT);
6095 /* non ssl.h errorcodes */
6096 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6097 PY_SSL_ERROR_EOF);
6098 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6099 PY_SSL_ERROR_INVALID_ERROR_CODE);
6100 /* cert requirements */
6101 PyModule_AddIntConstant(m, "CERT_NONE",
6102 PY_SSL_CERT_NONE);
6103 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6104 PY_SSL_CERT_OPTIONAL);
6105 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6106 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006107 /* CRL verification for verification_flags */
6108 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6109 0);
6110 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6111 X509_V_FLAG_CRL_CHECK);
6112 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6113 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6114 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6115 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006116#ifdef X509_V_FLAG_TRUSTED_FIRST
6117 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6118 X509_V_FLAG_TRUSTED_FIRST);
6119#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006120
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006121 /* Alert Descriptions from ssl.h */
6122 /* note RESERVED constants no longer intended for use have been removed */
6123 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6124
6125#define ADD_AD_CONSTANT(s) \
6126 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6127 SSL_AD_##s)
6128
6129 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6130 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6131 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6132 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6133 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6134 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6135 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6136 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6137 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6138 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6139 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6140 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6141 ADD_AD_CONSTANT(UNKNOWN_CA);
6142 ADD_AD_CONSTANT(ACCESS_DENIED);
6143 ADD_AD_CONSTANT(DECODE_ERROR);
6144 ADD_AD_CONSTANT(DECRYPT_ERROR);
6145 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6146 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6147 ADD_AD_CONSTANT(INTERNAL_ERROR);
6148 ADD_AD_CONSTANT(USER_CANCELLED);
6149 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006150 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006151#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6152 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6153#endif
6154#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6155 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6156#endif
6157#ifdef SSL_AD_UNRECOGNIZED_NAME
6158 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6159#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006160#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6161 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6162#endif
6163#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6164 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6165#endif
6166#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6167 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6168#endif
6169
6170#undef ADD_AD_CONSTANT
6171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006172 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006173#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006174 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6175 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006176#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006177#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006178 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6179 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006180#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006181 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006182 PY_SSL_VERSION_TLS);
6183 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6184 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006185 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6186 PY_SSL_VERSION_TLS_CLIENT);
6187 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6188 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006189 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6190 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006191#if HAVE_TLSv1_2
6192 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6193 PY_SSL_VERSION_TLS1_1);
6194 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6195 PY_SSL_VERSION_TLS1_2);
6196#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006197
Antoine Pitroub5218772010-05-21 09:56:06 +00006198 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006199 PyModule_AddIntConstant(m, "OP_ALL",
6200 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006201 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6202 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6203 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006204#if HAVE_TLSv1_2
6205 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6206 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6207#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006208#ifdef SSL_OP_NO_TLSv1_3
6209 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6210#else
6211 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6212#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006213 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6214 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006215 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006216 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006217#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006218 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006219#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006220#ifdef SSL_OP_NO_COMPRESSION
6221 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6222 SSL_OP_NO_COMPRESSION);
6223#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006224#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6225 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6226 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6227#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006228#ifdef SSL_OP_NO_RENEGOTIATION
6229 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6230 SSL_OP_NO_RENEGOTIATION);
6231#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006232
Christian Heimes61d478c2018-01-27 15:51:38 +01006233#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6234 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6235 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6236#endif
6237#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6238 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6239 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6240#endif
6241#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6242 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6243 X509_CHECK_FLAG_NO_WILDCARDS);
6244#endif
6245#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6246 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6247 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6248#endif
6249#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6250 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6251 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6252#endif
6253#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6254 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6255 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6256#endif
6257
Christian Heimes698dde12018-02-27 11:54:43 +01006258 /* protocol versions */
6259 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6260 PY_PROTO_MINIMUM_SUPPORTED);
6261 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6262 PY_PROTO_MAXIMUM_SUPPORTED);
6263 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6264 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6265 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6266 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6267 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006268
Victor Stinnerb37672d2018-11-22 03:37:50 +01006269#define addbool(m, key, value) \
6270 do { \
6271 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6272 Py_INCREF(bool_obj); \
6273 PyModule_AddObject((m), (key), bool_obj); \
6274 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006275
6276#if HAVE_SNI
6277 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006278#else
Christian Heimes698dde12018-02-27 11:54:43 +01006279 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006280#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006281
6282 addbool(m, "HAS_TLS_UNIQUE", 1);
6283
6284#ifndef OPENSSL_NO_ECDH
6285 addbool(m, "HAS_ECDH", 1);
6286#else
6287 addbool(m, "HAS_ECDH", 0);
6288#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006289
Christian Heimes29eab552018-02-25 12:31:33 +01006290#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006291 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006292#else
Christian Heimes698dde12018-02-27 11:54:43 +01006293 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006294#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006295
Christian Heimes29eab552018-02-25 12:31:33 +01006296#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006297 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006298#else
Christian Heimes698dde12018-02-27 11:54:43 +01006299 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006300#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006301
6302#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6303 addbool(m, "HAS_SSLv2", 1);
6304#else
6305 addbool(m, "HAS_SSLv2", 0);
6306#endif
6307
6308#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6309 addbool(m, "HAS_SSLv3", 1);
6310#else
6311 addbool(m, "HAS_SSLv3", 0);
6312#endif
6313
6314#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6315 addbool(m, "HAS_TLSv1", 1);
6316#else
6317 addbool(m, "HAS_TLSv1", 0);
6318#endif
6319
6320#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6321 addbool(m, "HAS_TLSv1_1", 1);
6322#else
6323 addbool(m, "HAS_TLSv1_1", 0);
6324#endif
6325
6326#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6327 addbool(m, "HAS_TLSv1_2", 1);
6328#else
6329 addbool(m, "HAS_TLSv1_2", 0);
6330#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006331
Christian Heimescb5b68a2017-09-07 18:07:00 -07006332#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006333 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006334#else
Christian Heimes698dde12018-02-27 11:54:43 +01006335 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006336#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006337
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006338 /* Mappings for error codes */
6339 err_codes_to_names = PyDict_New();
6340 err_names_to_codes = PyDict_New();
6341 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6342 return NULL;
6343 errcode = error_codes;
6344 while (errcode->mnemonic != NULL) {
6345 PyObject *mnemo, *key;
6346 mnemo = PyUnicode_FromString(errcode->mnemonic);
6347 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6348 if (mnemo == NULL || key == NULL)
6349 return NULL;
6350 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6351 return NULL;
6352 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6353 return NULL;
6354 Py_DECREF(key);
6355 Py_DECREF(mnemo);
6356 errcode++;
6357 }
6358 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6359 return NULL;
6360 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6361 return NULL;
6362
6363 lib_codes_to_names = PyDict_New();
6364 if (lib_codes_to_names == NULL)
6365 return NULL;
6366 libcode = library_codes;
6367 while (libcode->library != NULL) {
6368 PyObject *mnemo, *key;
6369 key = PyLong_FromLong(libcode->code);
6370 mnemo = PyUnicode_FromString(libcode->library);
6371 if (key == NULL || mnemo == NULL)
6372 return NULL;
6373 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6374 return NULL;
6375 Py_DECREF(key);
6376 Py_DECREF(mnemo);
6377 libcode++;
6378 }
6379 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6380 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006381
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006382 /* OpenSSL version */
6383 /* SSLeay() gives us the version of the library linked against,
6384 which could be different from the headers version.
6385 */
6386 libver = SSLeay();
6387 r = PyLong_FromUnsignedLong(libver);
6388 if (r == NULL)
6389 return NULL;
6390 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6391 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006392 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006393 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6394 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6395 return NULL;
6396 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6397 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6398 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006399
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006400 libver = OPENSSL_VERSION_NUMBER;
6401 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6402 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6403 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6404 return NULL;
6405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006406 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006407}