blob: 987a99178775dbb01e10dd070f6cb3f0154f75c1 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Steve Dower68d663c2017-07-17 11:15:48 +020021/* Redefined below for Windows debug builds after important #includes */
22#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020024#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
25 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
26#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020027 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000028#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000029 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020030 PySSL_BEGIN_ALLOW_THREADS_S(_save);
31#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
32#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000034
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010035/* Include symbols from _socket module */
36#include "socketmodule.h"
37
38static PySocketModule_APIObject PySocketModule;
39
40#if defined(HAVE_POLL_H)
41#include <poll.h>
42#elif defined(HAVE_SYS_POLL_H)
43#include <sys/poll.h>
44#endif
45
Christian Heimes598894f2016-09-05 23:19:05 +020046/* Don't warn about deprecated functions */
47#ifdef __GNUC__
48#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
49#endif
50#ifdef __clang__
51#pragma clang diagnostic ignored "-Wdeprecated-declarations"
52#endif
53
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010054/* Include OpenSSL header files */
55#include "openssl/rsa.h"
56#include "openssl/crypto.h"
57#include "openssl/x509.h"
58#include "openssl/x509v3.h"
59#include "openssl/pem.h"
60#include "openssl/ssl.h"
61#include "openssl/err.h"
62#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020063#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030064#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010065
Christian Heimesff5be6e2018-01-20 13:19:21 +010066#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010067# ifdef LIBRESSL_VERSION_NUMBER
68# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
69# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010070# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010071# else
72# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010073# endif
74#endif
75
Christian Heimesc087a262020-05-15 20:55:25 +020076#ifndef OPENSSL_THREADS
77# error "OPENSSL_THREADS is not defined, Python requires thread-safe OpenSSL"
78#endif
79
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080/* SSL error object */
81static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070082static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010083static PyObject *PySSLZeroReturnErrorObject;
84static PyObject *PySSLWantReadErrorObject;
85static PyObject *PySSLWantWriteErrorObject;
86static PyObject *PySSLSyscallErrorObject;
87static PyObject *PySSLEOFErrorObject;
88
89/* Error mappings */
90static PyObject *err_codes_to_names;
91static PyObject *err_names_to_codes;
92static PyObject *lib_codes_to_names;
93
94struct py_ssl_error_code {
95 const char *mnemonic;
96 int library, reason;
97};
98struct py_ssl_library_code {
99 const char *library;
100 int code;
101};
102
Steve Dower68d663c2017-07-17 11:15:48 +0200103#if defined(MS_WINDOWS) && defined(Py_DEBUG)
104/* Debug builds on Windows rely on getting errno directly from OpenSSL.
105 * However, because it uses a different CRT, we need to transfer the
106 * value of errno from OpenSSL into our debug CRT.
107 *
108 * Don't be fooled - this is horribly ugly code. The only reasonable
109 * alternative is to do both debug and release builds of OpenSSL, which
110 * requires much uglier code to transform their automatically generated
111 * makefile. This is the lesser of all the evils.
112 */
113
114static void _PySSLFixErrno(void) {
115 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
116 if (!ucrtbase) {
117 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
118 * have a catastrophic failure, but this function is not the
119 * place to raise it. */
120 return;
121 }
122
123 typedef int *(__stdcall *errno_func)(void);
124 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
125 if (ssl_errno) {
126 errno = *ssl_errno();
127 *ssl_errno() = 0;
128 } else {
129 errno = ENOTRECOVERABLE;
130 }
131}
132
133#undef _PySSL_FIX_ERRNO
134#define _PySSL_FIX_ERRNO _PySSLFixErrno()
135#endif
136
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100137/* Include generated data (error codes) */
138#include "_ssl_data.h"
139
Christian Heimes598894f2016-09-05 23:19:05 +0200140#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
141# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100142# define PY_OPENSSL_1_1_API 1
143#endif
144
145/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
146#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
147# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200148#endif
149
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100150/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
151 http://www.openssl.org/news/changelog.html
152 */
153#if OPENSSL_VERSION_NUMBER >= 0x10001000L
154# define HAVE_TLSv1_2 1
155#else
156# define HAVE_TLSv1_2 0
157#endif
158
Christian Heimes470fba12013-11-28 15:12:15 +0100159/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100160 * This includes the SSL_set_SSL_CTX() function.
161 */
162#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
163# define HAVE_SNI 1
164#else
165# define HAVE_SNI 0
166#endif
167
Benjamin Petersond3308222015-09-27 00:09:02 -0700168#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100169# define HAVE_ALPN 1
170#else
171# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500172#endif
173
Christian Heimes6cdb7952018-02-24 22:12:40 +0100174/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
175 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
176 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
177 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100178 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100179 */
180#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100181# define HAVE_NPN 0
182#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
183# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100184#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100185# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100186#else
Christian Heimes29eab552018-02-25 12:31:33 +0100187# define HAVE_NPN 0
188#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100189
Christian Heimesc7f70692019-05-31 11:44:05 +0200190#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
191#define HAVE_OPENSSL_KEYLOG 1
192#endif
193
Victor Stinner524714e2016-07-22 17:43:59 +0200194#ifndef INVALID_SOCKET /* MS defines this */
195#define INVALID_SOCKET (-1)
196#endif
197
Christian Heimes4ca07392018-03-24 15:41:37 +0100198/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
199#ifndef OPENSSL_VERSION_1_1
200#define HAVE_OPENSSL_CRYPTO_LOCK
201#endif
202
203#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200204#define OPENSSL_NO_SSL2
205#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100206
207#ifndef PY_OPENSSL_1_1_API
208/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200209
210#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200211#define TLS_client_method SSLv23_client_method
212#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200213
214static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
215{
216 return ne->set;
217}
218
219#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200220/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200221static int COMP_get_type(const COMP_METHOD *meth)
222{
223 return meth->type;
224}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200225/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200226#endif
227
228static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
229{
230 return ctx->default_passwd_callback;
231}
232
233static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
234{
235 return ctx->default_passwd_callback_userdata;
236}
237
238static int X509_OBJECT_get_type(X509_OBJECT *x)
239{
240 return x->type;
241}
242
243static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
244{
245 return x->data.x509;
246}
247
248static int BIO_up_ref(BIO *b)
249{
250 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
251 return 1;
252}
253
254static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
255 return store->objs;
256}
257
Christian Heimes99a65702016-09-10 23:44:53 +0200258static int
259SSL_SESSION_has_ticket(const SSL_SESSION *s)
260{
261 return (s->tlsext_ticklen > 0) ? 1 : 0;
262}
263
264static unsigned long
265SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
266{
267 return s->tlsext_tick_lifetime_hint;
268}
269
Christian Heimes4ca07392018-03-24 15:41:37 +0100270#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200271
Christian Heimes892d66e2018-01-29 14:10:18 +0100272/* Default cipher suites */
273#ifndef PY_SSL_DEFAULT_CIPHERS
274#define PY_SSL_DEFAULT_CIPHERS 1
275#endif
276
277#if PY_SSL_DEFAULT_CIPHERS == 0
278 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
279 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
280 #endif
281#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200282/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100283 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
284 * !aNULL:!eNULL: really no NULL ciphers
285 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
286 * !aDSS: no authentication with discrete logarithm DSA algorithm
287 * !SRP:!PSK: no secure remote password or pre-shared key authentication
288 */
289 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
290#elif PY_SSL_DEFAULT_CIPHERS == 2
291/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
292 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
293#else
294 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
295#endif
296
Christian Heimes598894f2016-09-05 23:19:05 +0200297
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000298enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000299 /* these mirror ssl.h */
300 PY_SSL_ERROR_NONE,
301 PY_SSL_ERROR_SSL,
302 PY_SSL_ERROR_WANT_READ,
303 PY_SSL_ERROR_WANT_WRITE,
304 PY_SSL_ERROR_WANT_X509_LOOKUP,
305 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
306 PY_SSL_ERROR_ZERO_RETURN,
307 PY_SSL_ERROR_WANT_CONNECT,
308 /* start of non ssl.h errorcodes */
309 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
310 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
311 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000312};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000313
Thomas Woutersed03b412007-08-28 21:37:11 +0000314enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000315 PY_SSL_CLIENT,
316 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000317};
318
319enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 PY_SSL_CERT_NONE,
321 PY_SSL_CERT_OPTIONAL,
322 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000323};
324
325enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000326 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200327 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200328 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100329#if HAVE_TLSv1_2
330 PY_SSL_VERSION_TLS1,
331 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200332 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100333#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200334 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000335#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200336 PY_SSL_VERSION_TLS_CLIENT=0x10,
337 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100338};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200339
Christian Heimes698dde12018-02-27 11:54:43 +0100340enum py_proto_version {
341 PY_PROTO_MINIMUM_SUPPORTED = -2,
342 PY_PROTO_SSLv3 = SSL3_VERSION,
343 PY_PROTO_TLSv1 = TLS1_VERSION,
344 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
345 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
346#ifdef TLS1_3_VERSION
347 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
348#else
349 PY_PROTO_TLSv1_3 = 0x304,
350#endif
351 PY_PROTO_MAXIMUM_SUPPORTED = -1,
352
353/* OpenSSL has no dedicated API to set the minimum version to the maximum
354 * available version, and the other way around. We have to figure out the
355 * minimum and maximum available version on our own and hope for the best.
356 */
357#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
359#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
361#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
362 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
363#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
364 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
365#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
366 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
367#else
368 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
369#endif
370
371#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
373#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
375#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
376 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
377#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
378 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
379#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
380 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
381#else
382 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
383#endif
384};
385
386
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000387/* serves as a flag to see whether we've initialized the SSL thread support. */
388/* 0 means no, greater than 0 means yes */
389
390static unsigned int _ssl_locks_count = 0;
391
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000392/* SSL socket object */
393
394#define X509_NAME_MAXLEN 256
395
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000396/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
397 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
398 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
399#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000400# define HAVE_SSL_CTX_CLEAR_OPTIONS
401#else
402# undef HAVE_SSL_CTX_CLEAR_OPTIONS
403#endif
404
Antoine Pitroud6494802011-07-21 01:11:30 +0200405/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
406 * older SSL, but let's be safe */
407#define PySSL_CB_MAXLEN 128
408
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100409
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000410typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000411 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000412 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100413#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500414 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100415 int npn_protocols_len;
416#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100417#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500418 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300419 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500420#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100421#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100422 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100423#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100424 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100425 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
426 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
427 */
428 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100429 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200430#ifdef TLS1_3_VERSION
431 int post_handshake_auth;
432#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200433 PyObject *msg_cb;
434#ifdef HAVE_OPENSSL_KEYLOG
435 PyObject *keylog_filename;
436 BIO *keylog_bio;
437#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000439
Antoine Pitrou152efa22010-05-16 18:19:27 +0000440typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700441 int ssl; /* last seen error from SSL */
442 int c; /* last seen error from libc */
443#ifdef MS_WINDOWS
444 int ws; /* last seen error from winsock */
445#endif
446} _PySSLError;
447
448typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000449 PyObject_HEAD
450 PyObject *Socket; /* weakref to socket on which we're layered */
451 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100452 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200453 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200454 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200455 PyObject *owner; /* Python level "owner" passed to servername callback */
456 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700457 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200458 /* Some SSL callbacks don't have error reporting. Callback wrappers
459 * store exception information on the socket. The handshake, read, write,
460 * and shutdown methods check for chained exceptions.
461 */
462 PyObject *exc_type;
463 PyObject *exc_value;
464 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000465} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000466
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200467typedef struct {
468 PyObject_HEAD
469 BIO *bio;
470 int eof_written;
471} PySSLMemoryBIO;
472
Christian Heimes99a65702016-09-10 23:44:53 +0200473typedef struct {
474 PyObject_HEAD
475 SSL_SESSION *session;
476 PySSLContext *ctx;
477} PySSLSession;
478
Antoine Pitrou152efa22010-05-16 18:19:27 +0000479static PyTypeObject PySSLContext_Type;
480static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200481static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200482static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000483
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700484static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
485{
486 _PySSLError err = { 0 };
487 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700488#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700489 err.ws = WSAGetLastError();
490 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700491#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700492 err.c = errno;
493 err.ssl = SSL_get_error(ssl, retcode);
494 }
495 return err;
496}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700497
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300498/*[clinic input]
499module _ssl
500class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
501class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
502class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200503class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300504[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200505/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300506
507#include "clinic/_ssl.c.h"
508
Victor Stinner14690702015-04-06 22:46:13 +0200509static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000510
Christian Heimes141c5e82018-02-24 21:10:57 +0100511static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
512static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Dong-hee Na1b55b652020-02-17 19:09:15 +0900513#define PySSLSocket_Check(v) Py_IS_TYPE(v, &PySSLSocket_Type)
514#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, &PySSLMemoryBIO_Type)
515#define PySSLSession_Check(v) Py_IS_TYPE(v, &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000516
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000517typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000518 SOCKET_IS_NONBLOCKING,
519 SOCKET_IS_BLOCKING,
520 SOCKET_HAS_TIMED_OUT,
521 SOCKET_HAS_BEEN_CLOSED,
522 SOCKET_TOO_LARGE_FOR_SELECT,
523 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000524} timeout_state;
525
Thomas Woutersed03b412007-08-28 21:37:11 +0000526/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000527#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200528#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000529
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200530/* Get the socket from a PySSLSocket, if it has one */
531#define GET_SOCKET(obj) ((obj)->Socket ? \
532 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200533
Victor Stinner14690702015-04-06 22:46:13 +0200534/* If sock is NULL, use a timeout of 0 second */
535#define GET_SOCKET_TIMEOUT(sock) \
536 ((sock != NULL) ? (sock)->sock_timeout : 0)
537
Christian Heimesc7f70692019-05-31 11:44:05 +0200538#include "_ssl/debughelpers.c"
539
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200540/*
541 * SSL errors.
542 */
543
544PyDoc_STRVAR(SSLError_doc,
545"An error occurred in the SSL implementation.");
546
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700547PyDoc_STRVAR(SSLCertVerificationError_doc,
548"A certificate could not be verified.");
549
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200550PyDoc_STRVAR(SSLZeroReturnError_doc,
551"SSL/TLS session closed cleanly.");
552
553PyDoc_STRVAR(SSLWantReadError_doc,
554"Non-blocking SSL socket needs to read more data\n"
555"before the requested operation can be completed.");
556
557PyDoc_STRVAR(SSLWantWriteError_doc,
558"Non-blocking SSL socket needs to write more data\n"
559"before the requested operation can be completed.");
560
561PyDoc_STRVAR(SSLSyscallError_doc,
562"System error when attempting SSL operation.");
563
564PyDoc_STRVAR(SSLEOFError_doc,
565"SSL/TLS connection terminated abruptly.");
566
567static PyObject *
568SSLError_str(PyOSErrorObject *self)
569{
570 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
571 Py_INCREF(self->strerror);
572 return self->strerror;
573 }
574 else
575 return PyObject_Str(self->args);
576}
577
578static PyType_Slot sslerror_type_slots[] = {
579 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900580 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200581 {Py_tp_str, SSLError_str},
582 {0, 0},
583};
584
585static PyType_Spec sslerror_type_spec = {
586 "ssl.SSLError",
587 sizeof(PyOSErrorObject),
588 0,
589 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
590 sslerror_type_slots
591};
592
593static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700594fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
595 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200596{
597 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700598 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200599 PyObject *init_value, *msg, *key;
600 _Py_IDENTIFIER(reason);
601 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700602 _Py_IDENTIFIER(verify_message);
603 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200604
605 if (errcode != 0) {
606 int lib, reason;
607
608 lib = ERR_GET_LIB(errcode);
609 reason = ERR_GET_REASON(errcode);
610 key = Py_BuildValue("ii", lib, reason);
611 if (key == NULL)
612 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300613 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200614 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300615 if (reason_obj == NULL && PyErr_Occurred()) {
616 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200617 }
618 key = PyLong_FromLong(lib);
619 if (key == NULL)
620 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300621 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200622 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300623 if (lib_obj == NULL && PyErr_Occurred()) {
624 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200625 }
626 if (errstr == NULL)
627 errstr = ERR_reason_error_string(errcode);
628 }
629 if (errstr == NULL)
630 errstr = "unknown error";
631
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700632 /* verify code for cert validation error */
633 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
634 const char *verify_str = NULL;
635 long verify_code;
636
637 verify_code = SSL_get_verify_result(sslsock->ssl);
638 verify_code_obj = PyLong_FromLong(verify_code);
639 if (verify_code_obj == NULL) {
640 goto fail;
641 }
642
643 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700644#ifdef X509_V_ERR_HOSTNAME_MISMATCH
645 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700646 case X509_V_ERR_HOSTNAME_MISMATCH:
647 verify_obj = PyUnicode_FromFormat(
648 "Hostname mismatch, certificate is not valid for '%S'.",
649 sslsock->server_hostname
650 );
651 break;
Christian Heimes09153602017-09-08 14:47:58 -0700652#endif
653#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700654 case X509_V_ERR_IP_ADDRESS_MISMATCH:
655 verify_obj = PyUnicode_FromFormat(
656 "IP address mismatch, certificate is not valid for '%S'.",
657 sslsock->server_hostname
658 );
659 break;
Christian Heimes09153602017-09-08 14:47:58 -0700660#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700661 default:
662 verify_str = X509_verify_cert_error_string(verify_code);
663 if (verify_str != NULL) {
664 verify_obj = PyUnicode_FromString(verify_str);
665 } else {
666 verify_obj = Py_None;
667 Py_INCREF(verify_obj);
668 }
669 break;
670 }
671 if (verify_obj == NULL) {
672 goto fail;
673 }
674 }
675
676 if (verify_obj && reason_obj && lib_obj)
677 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
678 lib_obj, reason_obj, errstr, verify_obj,
679 lineno);
680 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200681 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
682 lib_obj, reason_obj, errstr, lineno);
683 else if (lib_obj)
684 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
685 lib_obj, errstr, lineno);
686 else
687 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200688 if (msg == NULL)
689 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100690
Paul Monsonfb7e7502019-05-15 15:38:55 -0700691 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100692 if (init_value == NULL)
693 goto fail;
694
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200695 err_value = PyObject_CallObject(type, init_value);
696 Py_DECREF(init_value);
697 if (err_value == NULL)
698 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100699
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200700 if (reason_obj == NULL)
701 reason_obj = Py_None;
702 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
703 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700704
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200705 if (lib_obj == NULL)
706 lib_obj = Py_None;
707 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
708 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700709
710 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
711 /* Only set verify code / message for SSLCertVerificationError */
712 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
713 verify_code_obj))
714 goto fail;
715 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
716 goto fail;
717 }
718
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200719 PyErr_SetObject(type, err_value);
720fail:
721 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700722 Py_XDECREF(verify_code_obj);
723 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200724}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000725
Christian Heimesc7f70692019-05-31 11:44:05 +0200726static int
727PySSL_ChainExceptions(PySSLSocket *sslsock) {
728 if (sslsock->exc_type == NULL)
729 return 0;
730
731 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
732 sslsock->exc_type = NULL;
733 sslsock->exc_value = NULL;
734 sslsock->exc_tb = NULL;
735 return -1;
736}
737
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000738static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700739PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000740{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200741 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200742 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700743 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200745 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200748 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000749
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700750 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700751 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000752
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700753 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200755 errstr = "TLS/SSL connection has been closed (EOF)";
756 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000757 p = PY_SSL_ERROR_ZERO_RETURN;
758 break;
759 case SSL_ERROR_WANT_READ:
760 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200761 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000762 p = PY_SSL_ERROR_WANT_READ;
763 break;
764 case SSL_ERROR_WANT_WRITE:
765 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200766 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 errstr = "The operation did not complete (write)";
768 break;
769 case SSL_ERROR_WANT_X509_LOOKUP:
770 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000771 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 break;
773 case SSL_ERROR_WANT_CONNECT:
774 p = PY_SSL_ERROR_WANT_CONNECT;
775 errstr = "The operation did not complete (connect)";
776 break;
777 case SSL_ERROR_SYSCALL:
778 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700780 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000781 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200783 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200785 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000786 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000787 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700788#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700789 if (err.ws) {
790 return PyErr_SetFromWindowsErr(err.ws);
791 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700792#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700793 if (err.c) {
794 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700795 return PyErr_SetFromErrno(PyExc_OSError);
796 }
797 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200798 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000799 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200800 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000802 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200803 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000804 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000805 }
806 } else {
807 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 }
809 break;
810 }
811 case SSL_ERROR_SSL:
812 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700814 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200815 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000816 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700817 }
818 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
819 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
820 type = PySSLCertVerificationErrorObject;
821 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 break;
823 }
824 default:
825 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
826 errstr = "Invalid error code";
827 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700829 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000830 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200831 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000833}
834
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200836_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000837
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200838 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200840 else
841 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700842 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000843 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000845}
846
Christian Heimes61d478c2018-01-27 15:51:38 +0100847/*
848 * SSL objects
849 */
850
851static int
852_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
853{
854 int retval = -1;
855 ASN1_OCTET_STRING *ip;
856 PyObject *hostname;
857 size_t len;
858
859 assert(server_hostname);
860
861 /* Disable OpenSSL's special mode with leading dot in hostname:
862 * When name starts with a dot (e.g ".example.com"), it will be
863 * matched by a certificate valid for any sub-domain of name.
864 */
865 len = strlen(server_hostname);
866 if (len == 0 || *server_hostname == '.') {
867 PyErr_SetString(
868 PyExc_ValueError,
869 "server_hostname cannot be an empty string or start with a "
870 "leading dot.");
871 return retval;
872 }
873
874 /* inet_pton is not available on all platforms. */
875 ip = a2i_IPADDRESS(server_hostname);
876 if (ip == NULL) {
877 ERR_clear_error();
878 }
879
Christian Heimes11a14932018-02-24 02:35:08 +0100880 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100881 if (hostname == NULL) {
882 goto error;
883 }
884 self->server_hostname = hostname;
885
886 /* Only send SNI extension for non-IP hostnames */
887 if (ip == NULL) {
888 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
889 _setSSLError(NULL, 0, __FILE__, __LINE__);
890 }
891 }
892 if (self->ctx->check_hostname) {
893 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
894 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200895 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
896 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100897 _setSSLError(NULL, 0, __FILE__, __LINE__);
898 goto error;
899 }
900 } else {
901 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
902 ASN1_STRING_length(ip))) {
903 _setSSLError(NULL, 0, __FILE__, __LINE__);
904 goto error;
905 }
906 }
907 }
908 retval = 0;
909 error:
910 if (ip != NULL) {
911 ASN1_OCTET_STRING_free(ip);
912 }
913 return retval;
914}
915
Antoine Pitrou152efa22010-05-16 18:19:27 +0000916static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100917newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000918 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100920 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200921 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000922{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000923 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100924 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700925 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000926
Antoine Pitrou152efa22010-05-16 18:19:27 +0000927 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 if (self == NULL)
929 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100933 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700934 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200935 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200936 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700937 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700938 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200939 self->exc_type = NULL;
940 self->exc_value = NULL;
941 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000945
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000947 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700949 if (self->ssl == NULL) {
950 Py_DECREF(self);
951 _setSSLError(NULL, 0, __FILE__, __LINE__);
952 return NULL;
953 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200954 SSL_set_app_data(self->ssl, self);
955 if (sock) {
956 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
957 } else {
958 /* BIOs are reference counted and SSL_set_bio borrows our reference.
959 * To prevent a double free in memory_bio_dealloc() we need to take an
960 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200961 BIO_up_ref(inbio->bio);
962 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200963 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
964 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400965 SSL_set_mode(self->ssl,
966 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000967
Christian Heimesf0f59302019-07-01 08:29:17 +0200968#ifdef TLS1_3_VERSION
969 if (sslctx->post_handshake_auth == 1) {
970 if (socket_type == PY_SSL_SERVER) {
971 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
972 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
973 * only in combination with SSL_VERIFY_PEER flag. */
974 int mode = SSL_get_verify_mode(self->ssl);
975 if (mode & SSL_VERIFY_PEER) {
976 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
977 verify_cb = SSL_get_verify_callback(self->ssl);
978 mode |= SSL_VERIFY_POST_HANDSHAKE;
979 SSL_set_verify(self->ssl, mode, verify_cb);
980 }
981 } else {
982 /* client socket */
983 SSL_set_post_handshake_auth(self->ssl, 1);
984 }
985 }
986#endif
987
Christian Heimes61d478c2018-01-27 15:51:38 +0100988 if (server_hostname != NULL) {
989 if (_ssl_configure_hostname(self, server_hostname) < 0) {
990 Py_DECREF(self);
991 return NULL;
992 }
993 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 /* If the socket is in non-blocking mode or timeout mode, set the BIO
995 * to non-blocking mode (blocking is the default)
996 */
Victor Stinnere2452312015-03-28 03:00:46 +0100997 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
999 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
1000 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 PySSL_BEGIN_ALLOW_THREADS
1003 if (socket_type == PY_SSL_CLIENT)
1004 SSL_set_connect_state(self->ssl);
1005 else
1006 SSL_set_accept_state(self->ssl);
1007 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001008
Antoine Pitroud6494802011-07-21 01:11:30 +02001009 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001010 if (sock != NULL) {
1011 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1012 if (self->Socket == NULL) {
1013 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001014 return NULL;
1015 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001016 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001017 if (owner && owner != Py_None) {
1018 if (PySSL_set_owner(self, owner, NULL) == -1) {
1019 Py_DECREF(self);
1020 return NULL;
1021 }
1022 }
1023 if (session && session != Py_None) {
1024 if (PySSL_set_session(self, session, NULL) == -1) {
1025 Py_DECREF(self);
1026 return NULL;
1027 }
1028 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001030}
1031
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001032/* SSL object methods */
1033
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001034/*[clinic input]
1035_ssl._SSLSocket.do_handshake
1036[clinic start generated code]*/
1037
1038static PyObject *
1039_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1040/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001041{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001043 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001045 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001046 _PyTime_t timeout, deadline = 0;
1047 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001048
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001049 if (sock) {
1050 if (((PyObject*)sock) == Py_None) {
1051 _setSSLError("Underlying socket connection gone",
1052 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1053 return NULL;
1054 }
1055 Py_INCREF(sock);
1056
1057 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001058 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001059 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1060 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001062
Victor Stinner14690702015-04-06 22:46:13 +02001063 timeout = GET_SOCKET_TIMEOUT(sock);
1064 has_timeout = (timeout > 0);
1065 if (has_timeout)
1066 deadline = _PyTime_GetMonotonicClock() + timeout;
1067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 /* Actually negotiate SSL connection */
1069 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001071 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001073 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001075 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001076
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001077 if (PyErr_CheckSignals())
1078 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001079
Victor Stinner14690702015-04-06 22:46:13 +02001080 if (has_timeout)
1081 timeout = deadline - _PyTime_GetMonotonicClock();
1082
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001083 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001084 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001085 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001086 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 } else {
1088 sockstate = SOCKET_OPERATION_OK;
1089 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001090
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001092 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001093 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001094 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1096 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001097 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001098 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001099 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1100 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001101 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001102 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1104 break;
1105 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001106 } while (err.ssl == SSL_ERROR_WANT_READ ||
1107 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001108 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 if (ret < 1)
1110 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001111 if (PySSL_ChainExceptions(self) < 0)
1112 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001113 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001114error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001115 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001116 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001117 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001118}
1119
Thomas Woutersed03b412007-08-28 21:37:11 +00001120static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001121_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1122{
1123 char buf[X509_NAME_MAXLEN];
1124 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001126 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001127
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001128 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 if (buflen < 0) {
1130 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001131 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001132 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001133 /* initial buffer is too small for oid + terminating null byte */
1134 if (buflen > X509_NAME_MAXLEN - 1) {
1135 /* make OBJ_obj2txt() calculate the required buflen */
1136 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1137 /* allocate len + 1 for terminating NULL byte */
1138 namebuf = PyMem_Malloc(buflen + 1);
1139 if (namebuf == NULL) {
1140 PyErr_NoMemory();
1141 return NULL;
1142 }
1143 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1144 if (buflen < 0) {
1145 _setSSLError(NULL, 0, __FILE__, __LINE__);
1146 goto done;
1147 }
1148 }
1149 if (!buflen && no_name) {
1150 Py_INCREF(Py_None);
1151 name_obj = Py_None;
1152 }
1153 else {
1154 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1155 }
1156
1157 done:
1158 if (buf != namebuf) {
1159 PyMem_Free(namebuf);
1160 }
1161 return name_obj;
1162}
1163
1164static PyObject *
1165_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1166{
1167 Py_ssize_t buflen;
1168 unsigned char *valuebuf = NULL;
1169 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001170
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1172 if (buflen < 0) {
1173 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001174 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001176 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001179}
1180
1181static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001182_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001183{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001184 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1185 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1186 PyObject *rdnt;
1187 PyObject *attr = NULL; /* tuple to hold an attribute */
1188 int entry_count = X509_NAME_entry_count(xname);
1189 X509_NAME_ENTRY *entry;
1190 ASN1_OBJECT *name;
1191 ASN1_STRING *value;
1192 int index_counter;
1193 int rdn_level = -1;
1194 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 dn = PyList_New(0);
1197 if (dn == NULL)
1198 return NULL;
1199 /* now create another tuple to hold the top-level RDN */
1200 rdn = PyList_New(0);
1201 if (rdn == NULL)
1202 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 for (index_counter = 0;
1205 index_counter < entry_count;
1206 index_counter++)
1207 {
1208 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 /* check to see if we've gotten to a new RDN */
1211 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001212 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 /* yes, new RDN */
1214 /* add old RDN to DN */
1215 rdnt = PyList_AsTuple(rdn);
1216 Py_DECREF(rdn);
1217 if (rdnt == NULL)
1218 goto fail0;
1219 retcode = PyList_Append(dn, rdnt);
1220 Py_DECREF(rdnt);
1221 if (retcode < 0)
1222 goto fail0;
1223 /* create new RDN */
1224 rdn = PyList_New(0);
1225 if (rdn == NULL)
1226 goto fail0;
1227 }
1228 }
Christian Heimes598894f2016-09-05 23:19:05 +02001229 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001230
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 /* now add this attribute to the current RDN */
1232 name = X509_NAME_ENTRY_get_object(entry);
1233 value = X509_NAME_ENTRY_get_data(entry);
1234 attr = _create_tuple_for_attribute(name, value);
1235 /*
1236 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1237 entry->set,
1238 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1239 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1240 */
1241 if (attr == NULL)
1242 goto fail1;
1243 retcode = PyList_Append(rdn, attr);
1244 Py_DECREF(attr);
1245 if (retcode < 0)
1246 goto fail1;
1247 }
1248 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001249 if (rdn != NULL) {
1250 if (PyList_GET_SIZE(rdn) > 0) {
1251 rdnt = PyList_AsTuple(rdn);
1252 Py_DECREF(rdn);
1253 if (rdnt == NULL)
1254 goto fail0;
1255 retcode = PyList_Append(dn, rdnt);
1256 Py_DECREF(rdnt);
1257 if (retcode < 0)
1258 goto fail0;
1259 }
1260 else {
1261 Py_DECREF(rdn);
1262 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 /* convert list to tuple */
1266 rdnt = PyList_AsTuple(dn);
1267 Py_DECREF(dn);
1268 if (rdnt == NULL)
1269 return NULL;
1270 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001271
1272 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
1275 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 Py_XDECREF(dn);
1277 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001278}
1279
1280static PyObject *
1281_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001283 /* this code follows the procedure outlined in
1284 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1285 function to extract the STACK_OF(GENERAL_NAME),
1286 then iterates through the stack to add the
1287 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001289 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001291 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 GENERAL_NAMES *names = NULL;
1293 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 BIO *biobuf = NULL;
1295 char buf[2048];
1296 char *vptr;
1297 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 if (certificate == NULL)
1300 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001302 /* get a memory buffer */
1303 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001304 if (biobuf == NULL) {
1305 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1306 return NULL;
1307 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001309 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1310 certificate, NID_subject_alt_name, NULL, NULL);
1311 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (peer_alt_names == Py_None) {
1313 peer_alt_names = PyList_New(0);
1314 if (peer_alt_names == NULL)
1315 goto fail;
1316 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001320 int gntype;
1321 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001324 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001325 switch (gntype) {
1326 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001327 /* we special-case DirName as a tuple of
1328 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 t = PyTuple_New(2);
1331 if (t == NULL) {
1332 goto fail;
1333 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 v = PyUnicode_FromString("DirName");
1336 if (v == NULL) {
1337 Py_DECREF(t);
1338 goto fail;
1339 }
1340 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001342 v = _create_tuple_for_X509_NAME (name->d.dirn);
1343 if (v == NULL) {
1344 Py_DECREF(t);
1345 goto fail;
1346 }
1347 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001348 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001349
Christian Heimes824f7f32013-08-17 00:54:47 +02001350 case GEN_EMAIL:
1351 case GEN_DNS:
1352 case GEN_URI:
1353 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1354 correctly, CVE-2013-4238 */
1355 t = PyTuple_New(2);
1356 if (t == NULL)
1357 goto fail;
1358 switch (gntype) {
1359 case GEN_EMAIL:
1360 v = PyUnicode_FromString("email");
1361 as = name->d.rfc822Name;
1362 break;
1363 case GEN_DNS:
1364 v = PyUnicode_FromString("DNS");
1365 as = name->d.dNSName;
1366 break;
1367 case GEN_URI:
1368 v = PyUnicode_FromString("URI");
1369 as = name->d.uniformResourceIdentifier;
1370 break;
1371 }
1372 if (v == NULL) {
1373 Py_DECREF(t);
1374 goto fail;
1375 }
1376 PyTuple_SET_ITEM(t, 0, v);
1377 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1378 ASN1_STRING_length(as));
1379 if (v == NULL) {
1380 Py_DECREF(t);
1381 goto fail;
1382 }
1383 PyTuple_SET_ITEM(t, 1, v);
1384 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001385
Christian Heimes1c03abd2016-09-06 23:25:35 +02001386 case GEN_RID:
1387 t = PyTuple_New(2);
1388 if (t == NULL)
1389 goto fail;
1390
1391 v = PyUnicode_FromString("Registered ID");
1392 if (v == NULL) {
1393 Py_DECREF(t);
1394 goto fail;
1395 }
1396 PyTuple_SET_ITEM(t, 0, v);
1397
1398 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1399 if (len < 0) {
1400 Py_DECREF(t);
1401 _setSSLError(NULL, 0, __FILE__, __LINE__);
1402 goto fail;
1403 } else if (len >= (int)sizeof(buf)) {
1404 v = PyUnicode_FromString("<INVALID>");
1405 } else {
1406 v = PyUnicode_FromStringAndSize(buf, len);
1407 }
1408 if (v == NULL) {
1409 Py_DECREF(t);
1410 goto fail;
1411 }
1412 PyTuple_SET_ITEM(t, 1, v);
1413 break;
1414
Christian Heimes2b7de662019-12-07 17:59:36 +01001415 case GEN_IPADD:
1416 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1417 * the trailing newline. Remove it in all versions
1418 */
1419 t = PyTuple_New(2);
1420 if (t == NULL)
1421 goto fail;
1422
1423 v = PyUnicode_FromString("IP Address");
1424 if (v == NULL) {
1425 Py_DECREF(t);
1426 goto fail;
1427 }
1428 PyTuple_SET_ITEM(t, 0, v);
1429
1430 if (name->d.ip->length == 4) {
1431 unsigned char *p = name->d.ip->data;
1432 v = PyUnicode_FromFormat(
1433 "%d.%d.%d.%d",
1434 p[0], p[1], p[2], p[3]
1435 );
1436 } else if (name->d.ip->length == 16) {
1437 /* PyUnicode_FromFormat() does not support %X */
1438 unsigned char *p = name->d.ip->data;
1439 len = sprintf(
1440 buf,
1441 "%X:%X:%X:%X:%X:%X:%X:%X",
1442 p[0] << 8 | p[1],
1443 p[2] << 8 | p[3],
1444 p[4] << 8 | p[5],
1445 p[6] << 8 | p[7],
1446 p[8] << 8 | p[9],
1447 p[10] << 8 | p[11],
1448 p[12] << 8 | p[13],
1449 p[14] << 8 | p[15]
1450 );
1451 v = PyUnicode_FromStringAndSize(buf, len);
1452 } else {
1453 v = PyUnicode_FromString("<invalid>");
1454 }
1455
1456 if (v == NULL) {
1457 Py_DECREF(t);
1458 goto fail;
1459 }
1460 PyTuple_SET_ITEM(t, 1, v);
1461 break;
1462
Christian Heimes824f7f32013-08-17 00:54:47 +02001463 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001465 switch (gntype) {
1466 /* check for new general name type */
1467 case GEN_OTHERNAME:
1468 case GEN_X400:
1469 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001470 case GEN_RID:
1471 break;
1472 default:
1473 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1474 "Unknown general name type %d",
1475 gntype) == -1) {
1476 goto fail;
1477 }
1478 break;
1479 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 (void) BIO_reset(biobuf);
1481 GENERAL_NAME_print(biobuf, name);
1482 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1483 if (len < 0) {
1484 _setSSLError(NULL, 0, __FILE__, __LINE__);
1485 goto fail;
1486 }
1487 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001488 if (vptr == NULL) {
1489 PyErr_Format(PyExc_ValueError,
1490 "Invalid value %.200s",
1491 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001493 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001494 t = PyTuple_New(2);
1495 if (t == NULL)
1496 goto fail;
1497 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1498 if (v == NULL) {
1499 Py_DECREF(t);
1500 goto fail;
1501 }
1502 PyTuple_SET_ITEM(t, 0, v);
1503 v = PyUnicode_FromStringAndSize((vptr + 1),
1504 (len - (vptr - buf + 1)));
1505 if (v == NULL) {
1506 Py_DECREF(t);
1507 goto fail;
1508 }
1509 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001510 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 if (PyList_Append(peer_alt_names, t) < 0) {
1516 Py_DECREF(t);
1517 goto fail;
1518 }
1519 Py_DECREF(t);
1520 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001521 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 }
1523 BIO_free(biobuf);
1524 if (peer_alt_names != Py_None) {
1525 v = PyList_AsTuple(peer_alt_names);
1526 Py_DECREF(peer_alt_names);
1527 return v;
1528 } else {
1529 return peer_alt_names;
1530 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001531
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001532
1533 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 if (biobuf != NULL)
1535 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001537 if (peer_alt_names != Py_None) {
1538 Py_XDECREF(peer_alt_names);
1539 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542}
1543
1544static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001545_get_aia_uri(X509 *certificate, int nid) {
1546 PyObject *lst = NULL, *ostr = NULL;
1547 int i, result;
1548 AUTHORITY_INFO_ACCESS *info;
1549
1550 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001551 if (info == NULL)
1552 return Py_None;
1553 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1554 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001555 return Py_None;
1556 }
1557
1558 if ((lst = PyList_New(0)) == NULL) {
1559 goto fail;
1560 }
1561
1562 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1563 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1564 ASN1_IA5STRING *uri;
1565
1566 if ((OBJ_obj2nid(ad->method) != nid) ||
1567 (ad->location->type != GEN_URI)) {
1568 continue;
1569 }
1570 uri = ad->location->d.uniformResourceIdentifier;
1571 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1572 uri->length);
1573 if (ostr == NULL) {
1574 goto fail;
1575 }
1576 result = PyList_Append(lst, ostr);
1577 Py_DECREF(ostr);
1578 if (result < 0) {
1579 goto fail;
1580 }
1581 }
1582 AUTHORITY_INFO_ACCESS_free(info);
1583
1584 /* convert to tuple or None */
1585 if (PyList_Size(lst) == 0) {
1586 Py_DECREF(lst);
1587 return Py_None;
1588 } else {
1589 PyObject *tup;
1590 tup = PyList_AsTuple(lst);
1591 Py_DECREF(lst);
1592 return tup;
1593 }
1594
1595 fail:
1596 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001597 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001598 return NULL;
1599}
1600
1601static PyObject *
1602_get_crl_dp(X509 *certificate) {
1603 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001604 int i, j;
1605 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001606
Christian Heimes598894f2016-09-05 23:19:05 +02001607 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001608
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001609 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001610 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001611
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001612 lst = PyList_New(0);
1613 if (lst == NULL)
1614 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001615
1616 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1617 DIST_POINT *dp;
1618 STACK_OF(GENERAL_NAME) *gns;
1619
1620 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001621 if (dp->distpoint == NULL) {
1622 /* Ignore empty DP value, CVE-2019-5010 */
1623 continue;
1624 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001625 gns = dp->distpoint->name.fullname;
1626
1627 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1628 GENERAL_NAME *gn;
1629 ASN1_IA5STRING *uri;
1630 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001631 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001632
1633 gn = sk_GENERAL_NAME_value(gns, j);
1634 if (gn->type != GEN_URI) {
1635 continue;
1636 }
1637 uri = gn->d.uniformResourceIdentifier;
1638 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1639 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001640 if (ouri == NULL)
1641 goto done;
1642
1643 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001644 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001645 if (err < 0)
1646 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001647 }
1648 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001649
1650 /* Convert to tuple. */
1651 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1652
1653 done:
1654 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001655 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001656 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001657}
1658
1659static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001660_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001662 PyObject *retval = NULL;
1663 BIO *biobuf = NULL;
1664 PyObject *peer;
1665 PyObject *peer_alt_names = NULL;
1666 PyObject *issuer;
1667 PyObject *version;
1668 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001669 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 ASN1_INTEGER *serialNumber;
1671 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001672 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001673 ASN1_TIME *notBefore, *notAfter;
1674 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001675
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001676 retval = PyDict_New();
1677 if (retval == NULL)
1678 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001679
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001680 peer = _create_tuple_for_X509_NAME(
1681 X509_get_subject_name(certificate));
1682 if (peer == NULL)
1683 goto fail0;
1684 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1685 Py_DECREF(peer);
1686 goto fail0;
1687 }
1688 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001689
Antoine Pitroufb046912010-11-09 20:21:19 +00001690 issuer = _create_tuple_for_X509_NAME(
1691 X509_get_issuer_name(certificate));
1692 if (issuer == NULL)
1693 goto fail0;
1694 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001696 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001698 Py_DECREF(issuer);
1699
1700 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001701 if (version == NULL)
1702 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001703 if (PyDict_SetItemString(retval, "version", version) < 0) {
1704 Py_DECREF(version);
1705 goto fail0;
1706 }
1707 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001709 /* get a memory buffer */
1710 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001711 if (biobuf == NULL) {
1712 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1713 goto fail0;
1714 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001715
Antoine Pitroufb046912010-11-09 20:21:19 +00001716 (void) BIO_reset(biobuf);
1717 serialNumber = X509_get_serialNumber(certificate);
1718 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1719 i2a_ASN1_INTEGER(biobuf, serialNumber);
1720 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1721 if (len < 0) {
1722 _setSSLError(NULL, 0, __FILE__, __LINE__);
1723 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001724 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001725 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1726 if (sn_obj == NULL)
1727 goto fail1;
1728 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1729 Py_DECREF(sn_obj);
1730 goto fail1;
1731 }
1732 Py_DECREF(sn_obj);
1733
1734 (void) BIO_reset(biobuf);
1735 notBefore = X509_get_notBefore(certificate);
1736 ASN1_TIME_print(biobuf, notBefore);
1737 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1738 if (len < 0) {
1739 _setSSLError(NULL, 0, __FILE__, __LINE__);
1740 goto fail1;
1741 }
1742 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1743 if (pnotBefore == NULL)
1744 goto fail1;
1745 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1746 Py_DECREF(pnotBefore);
1747 goto fail1;
1748 }
1749 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 (void) BIO_reset(biobuf);
1752 notAfter = X509_get_notAfter(certificate);
1753 ASN1_TIME_print(biobuf, notAfter);
1754 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1755 if (len < 0) {
1756 _setSSLError(NULL, 0, __FILE__, __LINE__);
1757 goto fail1;
1758 }
1759 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1760 if (pnotAfter == NULL)
1761 goto fail1;
1762 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1763 Py_DECREF(pnotAfter);
1764 goto fail1;
1765 }
1766 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001770 peer_alt_names = _get_peer_alt_names(certificate);
1771 if (peer_alt_names == NULL)
1772 goto fail1;
1773 else if (peer_alt_names != Py_None) {
1774 if (PyDict_SetItemString(retval, "subjectAltName",
1775 peer_alt_names) < 0) {
1776 Py_DECREF(peer_alt_names);
1777 goto fail1;
1778 }
1779 Py_DECREF(peer_alt_names);
1780 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001781
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001782 /* Authority Information Access: OCSP URIs */
1783 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1784 if (obj == NULL) {
1785 goto fail1;
1786 } else if (obj != Py_None) {
1787 result = PyDict_SetItemString(retval, "OCSP", obj);
1788 Py_DECREF(obj);
1789 if (result < 0) {
1790 goto fail1;
1791 }
1792 }
1793
1794 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1795 if (obj == NULL) {
1796 goto fail1;
1797 } else if (obj != Py_None) {
1798 result = PyDict_SetItemString(retval, "caIssuers", obj);
1799 Py_DECREF(obj);
1800 if (result < 0) {
1801 goto fail1;
1802 }
1803 }
1804
1805 /* CDP (CRL distribution points) */
1806 obj = _get_crl_dp(certificate);
1807 if (obj == NULL) {
1808 goto fail1;
1809 } else if (obj != Py_None) {
1810 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1811 Py_DECREF(obj);
1812 if (result < 0) {
1813 goto fail1;
1814 }
1815 }
1816
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 BIO_free(biobuf);
1818 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001819
1820 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (biobuf != NULL)
1822 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001823 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 Py_XDECREF(retval);
1825 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001826}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001827
Christian Heimes9a5395a2013-06-17 15:44:12 +02001828static PyObject *
1829_certificate_to_der(X509 *certificate)
1830{
1831 unsigned char *bytes_buf = NULL;
1832 int len;
1833 PyObject *retval;
1834
1835 bytes_buf = NULL;
1836 len = i2d_X509(certificate, &bytes_buf);
1837 if (len < 0) {
1838 _setSSLError(NULL, 0, __FILE__, __LINE__);
1839 return NULL;
1840 }
1841 /* this is actually an immutable bytes sequence */
1842 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1843 OPENSSL_free(bytes_buf);
1844 return retval;
1845}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001846
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001847/*[clinic input]
1848_ssl._test_decode_cert
1849 path: object(converter="PyUnicode_FSConverter")
1850 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001851
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001852[clinic start generated code]*/
1853
1854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001855_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1856/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001857{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 X509 *x=NULL;
1860 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001861
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1863 PyErr_SetString(PySSLErrorObject,
1864 "Can't malloc memory to read file");
1865 goto fail0;
1866 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001868 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 PyErr_SetString(PySSLErrorObject,
1870 "Can't open file");
1871 goto fail0;
1872 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001873
Alex Gaynor40dad952019-08-15 08:31:28 -04001874 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 if (x == NULL) {
1876 PyErr_SetString(PySSLErrorObject,
1877 "Error decoding PEM-encoded file");
1878 goto fail0;
1879 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001880
Antoine Pitroufb046912010-11-09 20:21:19 +00001881 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001882 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001883
1884 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001885 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001886 if (cert != NULL) BIO_free(cert);
1887 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001888}
1889
1890
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001891/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001892_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001893 der as binary_mode: bool = False
1894 /
1895
1896Returns the certificate for the peer.
1897
1898If no certificate was provided, returns None. If a certificate was
1899provided, but not validated, returns an empty dictionary. Otherwise
1900returns a dict containing information about the peer certificate.
1901
1902If the optional argument is True, returns a DER-encoded copy of the
1903peer certificate, or None if no certificate was provided. This will
1904return the certificate even if it wasn't validated.
1905[clinic start generated code]*/
1906
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001907static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001908_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1909/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001910{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001912 X509 *peer_cert;
1913 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001914
Christian Heimes66dc33b2017-05-23 16:02:02 -07001915 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001916 PyErr_SetString(PyExc_ValueError,
1917 "handshake not done yet");
1918 return NULL;
1919 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001920 peer_cert = SSL_get_peer_certificate(self->ssl);
1921 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923
Antoine Pitrou721738f2012-08-15 23:20:39 +02001924 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001925 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001926 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001928 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001929 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001930 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001931 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001932 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001933 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001934 X509_free(peer_cert);
1935 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001936}
1937
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001938static PyObject *
1939cipher_to_tuple(const SSL_CIPHER *cipher)
1940{
1941 const char *cipher_name, *cipher_protocol;
1942 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 if (retval == NULL)
1944 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001945
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001946 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001948 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001949 PyTuple_SET_ITEM(retval, 0, Py_None);
1950 } else {
1951 v = PyUnicode_FromString(cipher_name);
1952 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001953 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001954 PyTuple_SET_ITEM(retval, 0, v);
1955 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001956
1957 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001959 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 PyTuple_SET_ITEM(retval, 1, Py_None);
1961 } else {
1962 v = PyUnicode_FromString(cipher_protocol);
1963 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001964 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001965 PyTuple_SET_ITEM(retval, 1, v);
1966 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001967
1968 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001969 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001970 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001974
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001975 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001976 Py_DECREF(retval);
1977 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001978}
1979
Christian Heimes25bfcd52016-09-06 00:04:45 +02001980#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1981static PyObject *
1982cipher_to_dict(const SSL_CIPHER *cipher)
1983{
1984 const char *cipher_name, *cipher_protocol;
1985
1986 unsigned long cipher_id;
1987 int alg_bits, strength_bits, len;
1988 char buf[512] = {0};
1989#if OPENSSL_VERSION_1_1
1990 int aead, nid;
1991 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1992#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001993
1994 /* can be NULL */
1995 cipher_name = SSL_CIPHER_get_name(cipher);
1996 cipher_protocol = SSL_CIPHER_get_version(cipher);
1997 cipher_id = SSL_CIPHER_get_id(cipher);
1998 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001999 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
2000 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02002001 if (len > 1 && buf[len-1] == '\n')
2002 buf[len-1] = '\0';
2003 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
2004
2005#if OPENSSL_VERSION_1_1
2006 aead = SSL_CIPHER_is_aead(cipher);
2007 nid = SSL_CIPHER_get_cipher_nid(cipher);
2008 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2009 nid = SSL_CIPHER_get_digest_nid(cipher);
2010 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2011 nid = SSL_CIPHER_get_kx_nid(cipher);
2012 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2013 nid = SSL_CIPHER_get_auth_nid(cipher);
2014 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2015#endif
2016
Victor Stinner410b9882016-09-12 12:00:23 +02002017 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002018 "{sksssssssisi"
2019#if OPENSSL_VERSION_1_1
2020 "sOssssssss"
2021#endif
2022 "}",
2023 "id", cipher_id,
2024 "name", cipher_name,
2025 "protocol", cipher_protocol,
2026 "description", buf,
2027 "strength_bits", strength_bits,
2028 "alg_bits", alg_bits
2029#if OPENSSL_VERSION_1_1
2030 ,"aead", aead ? Py_True : Py_False,
2031 "symmetric", skcipher,
2032 "digest", digest,
2033 "kea", kx,
2034 "auth", auth
2035#endif
2036 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002037}
2038#endif
2039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002040/*[clinic input]
2041_ssl._SSLSocket.shared_ciphers
2042[clinic start generated code]*/
2043
2044static PyObject *
2045_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2046/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002047{
2048 STACK_OF(SSL_CIPHER) *ciphers;
2049 int i;
2050 PyObject *res;
2051
Christian Heimes598894f2016-09-05 23:19:05 +02002052 ciphers = SSL_get_ciphers(self->ssl);
2053 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002054 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002055 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2056 if (!res)
2057 return NULL;
2058 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2059 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2060 if (!tup) {
2061 Py_DECREF(res);
2062 return NULL;
2063 }
2064 PyList_SET_ITEM(res, i, tup);
2065 }
2066 return res;
2067}
2068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002069/*[clinic input]
2070_ssl._SSLSocket.cipher
2071[clinic start generated code]*/
2072
2073static PyObject *
2074_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2075/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002076{
2077 const SSL_CIPHER *current;
2078
2079 if (self->ssl == NULL)
2080 Py_RETURN_NONE;
2081 current = SSL_get_current_cipher(self->ssl);
2082 if (current == NULL)
2083 Py_RETURN_NONE;
2084 return cipher_to_tuple(current);
2085}
2086
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002087/*[clinic input]
2088_ssl._SSLSocket.version
2089[clinic start generated code]*/
2090
2091static PyObject *
2092_ssl__SSLSocket_version_impl(PySSLSocket *self)
2093/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002094{
2095 const char *version;
2096
2097 if (self->ssl == NULL)
2098 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002099 if (!SSL_is_init_finished(self->ssl)) {
2100 /* handshake not finished */
2101 Py_RETURN_NONE;
2102 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002103 version = SSL_get_version(self->ssl);
2104 if (!strcmp(version, "unknown"))
2105 Py_RETURN_NONE;
2106 return PyUnicode_FromString(version);
2107}
2108
Christian Heimes29eab552018-02-25 12:31:33 +01002109#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002110/*[clinic input]
2111_ssl._SSLSocket.selected_npn_protocol
2112[clinic start generated code]*/
2113
2114static PyObject *
2115_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2116/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2117{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002118 const unsigned char *out;
2119 unsigned int outlen;
2120
Victor Stinner4569cd52013-06-23 14:58:43 +02002121 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002122 &out, &outlen);
2123
2124 if (out == NULL)
2125 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002126 return PyUnicode_FromStringAndSize((char *)out, outlen);
2127}
2128#endif
2129
Christian Heimes29eab552018-02-25 12:31:33 +01002130#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002131/*[clinic input]
2132_ssl._SSLSocket.selected_alpn_protocol
2133[clinic start generated code]*/
2134
2135static PyObject *
2136_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2137/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2138{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002139 const unsigned char *out;
2140 unsigned int outlen;
2141
2142 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2143
2144 if (out == NULL)
2145 Py_RETURN_NONE;
2146 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002147}
2148#endif
2149
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002150/*[clinic input]
2151_ssl._SSLSocket.compression
2152[clinic start generated code]*/
2153
2154static PyObject *
2155_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2156/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2157{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002158#ifdef OPENSSL_NO_COMP
2159 Py_RETURN_NONE;
2160#else
2161 const COMP_METHOD *comp_method;
2162 const char *short_name;
2163
2164 if (self->ssl == NULL)
2165 Py_RETURN_NONE;
2166 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002167 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002168 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002169 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002170 if (short_name == NULL)
2171 Py_RETURN_NONE;
2172 return PyUnicode_DecodeFSDefault(short_name);
2173#endif
2174}
2175
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002176static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2177 Py_INCREF(self->ctx);
2178 return self->ctx;
2179}
2180
2181static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2182 void *closure) {
2183
2184 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002185#if !HAVE_SNI
2186 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2187 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002188 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002189#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002190 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002191 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002192 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002193#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002194 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002195 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002196 return -1;
2197 }
2198
2199 return 0;
2200}
2201
2202PyDoc_STRVAR(PySSL_set_context_doc,
2203"_setter_context(ctx)\n\
2204\
2205This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002206used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002207on the SSLContext to change the certificate information associated with the\n\
2208SSLSocket before the cryptographic exchange handshake messages\n");
2209
2210
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002211static PyObject *
2212PySSL_get_server_side(PySSLSocket *self, void *c)
2213{
2214 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2215}
2216
2217PyDoc_STRVAR(PySSL_get_server_side_doc,
2218"Whether this is a server-side socket.");
2219
2220static PyObject *
2221PySSL_get_server_hostname(PySSLSocket *self, void *c)
2222{
2223 if (self->server_hostname == NULL)
2224 Py_RETURN_NONE;
2225 Py_INCREF(self->server_hostname);
2226 return self->server_hostname;
2227}
2228
2229PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2230"The currently set server hostname (for SNI).");
2231
2232static PyObject *
2233PySSL_get_owner(PySSLSocket *self, void *c)
2234{
2235 PyObject *owner;
2236
2237 if (self->owner == NULL)
2238 Py_RETURN_NONE;
2239
2240 owner = PyWeakref_GetObject(self->owner);
2241 Py_INCREF(owner);
2242 return owner;
2243}
2244
2245static int
2246PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2247{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002248 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002249 if (self->owner == NULL)
2250 return -1;
2251 return 0;
2252}
2253
2254PyDoc_STRVAR(PySSL_get_owner_doc,
2255"The Python-level owner of this object.\
2256Passed as \"self\" in servername callback.");
2257
Christian Heimesc7f70692019-05-31 11:44:05 +02002258static int
2259PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2260{
2261 Py_VISIT(self->exc_type);
2262 Py_VISIT(self->exc_value);
2263 Py_VISIT(self->exc_tb);
2264 return 0;
2265}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002266
Christian Heimesc7f70692019-05-31 11:44:05 +02002267static int
2268PySSL_clear(PySSLSocket *self)
2269{
2270 Py_CLEAR(self->exc_type);
2271 Py_CLEAR(self->exc_value);
2272 Py_CLEAR(self->exc_tb);
2273 return 0;
2274}
2275
2276static void
2277PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002278{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 if (self->ssl)
2280 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002282 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002283 Py_XDECREF(self->server_hostname);
2284 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002286}
2287
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002288/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002289 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002290 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002291 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002292
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002293static int
Victor Stinner14690702015-04-06 22:46:13 +02002294PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002295{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002296 int rc;
2297#ifdef HAVE_POLL
2298 struct pollfd pollfd;
2299 _PyTime_t ms;
2300#else
2301 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 fd_set fds;
2303 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002304#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002305
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002307 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002309 else if (timeout < 0) {
2310 if (s->sock_timeout > 0)
2311 return SOCKET_HAS_TIMED_OUT;
2312 else
2313 return SOCKET_IS_BLOCKING;
2314 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002316 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002317 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 /* Prefer poll, if available, since you can poll() any fd
2321 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002322#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002323 pollfd.fd = s->sock_fd;
2324 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002325
Victor Stinner14690702015-04-06 22:46:13 +02002326 /* timeout is in seconds, poll() uses milliseconds */
2327 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002328 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002329
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002330 PySSL_BEGIN_ALLOW_THREADS
2331 rc = poll(&pollfd, 1, (int)ms);
2332 PySSL_END_ALLOW_THREADS
2333#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002335 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002337
Victor Stinner14690702015-04-06 22:46:13 +02002338 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 FD_ZERO(&fds);
2341 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002342
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002344 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002345 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002347 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002349 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002351#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2354 (when we are able to write or when there's something to read) */
2355 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002356}
2357
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002358/*[clinic input]
2359_ssl._SSLSocket.write
2360 b: Py_buffer
2361 /
2362
2363Writes the bytes-like object b into the SSL object.
2364
2365Returns the number of bytes written.
2366[clinic start generated code]*/
2367
2368static PyObject *
2369_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2370/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002371{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002372 int len;
2373 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002374 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002375 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002376 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002377 _PyTime_t timeout, deadline = 0;
2378 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002379
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002380 if (sock != NULL) {
2381 if (((PyObject*)sock) == Py_None) {
2382 _setSSLError("Underlying socket connection gone",
2383 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2384 return NULL;
2385 }
2386 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 }
2388
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002389 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002390 PyErr_Format(PyExc_OverflowError,
2391 "string longer than %d bytes", INT_MAX);
2392 goto error;
2393 }
2394
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002395 if (sock != NULL) {
2396 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002397 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002398 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2399 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2400 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002401
Victor Stinner14690702015-04-06 22:46:13 +02002402 timeout = GET_SOCKET_TIMEOUT(sock);
2403 has_timeout = (timeout > 0);
2404 if (has_timeout)
2405 deadline = _PyTime_GetMonotonicClock() + timeout;
2406
2407 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002408 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002409 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 "The write operation timed out");
2411 goto error;
2412 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2413 PyErr_SetString(PySSLErrorObject,
2414 "Underlying socket has been closed.");
2415 goto error;
2416 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2417 PyErr_SetString(PySSLErrorObject,
2418 "Underlying socket too large for select().");
2419 goto error;
2420 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002424 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002425 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002427 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002428
2429 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002431
Victor Stinner14690702015-04-06 22:46:13 +02002432 if (has_timeout)
2433 timeout = deadline - _PyTime_GetMonotonicClock();
2434
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002435 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002436 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002437 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002438 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 } else {
2440 sockstate = SOCKET_OPERATION_OK;
2441 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002442
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002444 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 "The write operation timed out");
2446 goto error;
2447 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2448 PyErr_SetString(PySSLErrorObject,
2449 "Underlying socket has been closed.");
2450 goto error;
2451 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2452 break;
2453 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002454 } while (err.ssl == SSL_ERROR_WANT_READ ||
2455 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002456
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002457 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002458 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002460 if (PySSL_ChainExceptions(self) < 0)
2461 return NULL;
2462 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002463error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002464 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002465 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002467}
2468
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002469/*[clinic input]
2470_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002471
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002472Returns the number of already decrypted bytes available for read, pending on the connection.
2473[clinic start generated code]*/
2474
2475static PyObject *
2476_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2477/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002478{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002480 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002481
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002482 PySSL_BEGIN_ALLOW_THREADS
2483 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002484 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002486 self->err = err;
2487
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002488 if (count < 0)
2489 return PySSL_SetError(self, count, __FILE__, __LINE__);
2490 else
2491 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002492}
2493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002494/*[clinic input]
2495_ssl._SSLSocket.read
2496 size as len: int
2497 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002498 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002499 ]
2500 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002501
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002502Read up to size bytes from the SSL socket.
2503[clinic start generated code]*/
2504
2505static PyObject *
2506_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2507 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002508/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002509{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002512 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002514 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002515 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002516 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002517 _PyTime_t timeout, deadline = 0;
2518 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002519
Martin Panter5503d472016-03-27 05:35:19 +00002520 if (!group_right_1 && len < 0) {
2521 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2522 return NULL;
2523 }
2524
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002525 if (sock != NULL) {
2526 if (((PyObject*)sock) == Py_None) {
2527 _setSSLError("Underlying socket connection gone",
2528 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2529 return NULL;
2530 }
2531 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 }
2533
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002534 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002535 dest = PyBytes_FromStringAndSize(NULL, len);
2536 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002537 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002538 if (len == 0) {
2539 Py_XDECREF(sock);
2540 return dest;
2541 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002542 mem = PyBytes_AS_STRING(dest);
2543 }
2544 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002545 mem = buffer->buf;
2546 if (len <= 0 || len > buffer->len) {
2547 len = (int) buffer->len;
2548 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002549 PyErr_SetString(PyExc_OverflowError,
2550 "maximum length can't fit in a C 'int'");
2551 goto error;
2552 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002553 if (len == 0) {
2554 count = 0;
2555 goto done;
2556 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002557 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 }
2559
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002560 if (sock != NULL) {
2561 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002562 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002563 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2564 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2565 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002566
Victor Stinner14690702015-04-06 22:46:13 +02002567 timeout = GET_SOCKET_TIMEOUT(sock);
2568 has_timeout = (timeout > 0);
2569 if (has_timeout)
2570 deadline = _PyTime_GetMonotonicClock() + timeout;
2571
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 PySSL_BEGIN_ALLOW_THREADS
2574 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002575 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002577 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579 if (PyErr_CheckSignals())
2580 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002581
Victor Stinner14690702015-04-06 22:46:13 +02002582 if (has_timeout)
2583 timeout = deadline - _PyTime_GetMonotonicClock();
2584
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002585 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002586 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002587 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002588 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002589 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002590 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002591 {
2592 count = 0;
2593 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002594 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002595 else
2596 sockstate = SOCKET_OPERATION_OK;
2597
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002598 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002599 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002600 "The read operation timed out");
2601 goto error;
2602 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2603 break;
2604 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002605 } while (err.ssl == SSL_ERROR_WANT_READ ||
2606 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002607
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002608 if (count <= 0) {
2609 PySSL_SetError(self, count, __FILE__, __LINE__);
2610 goto error;
2611 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002612 if (self->exc_type != NULL)
2613 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002614
2615done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002616 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002617 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002618 _PyBytes_Resize(&dest, count);
2619 return dest;
2620 }
2621 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002622 return PyLong_FromLong(count);
2623 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002624
2625error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002626 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002627 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002628 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002629 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002630 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002631}
2632
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002633/*[clinic input]
2634_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002635
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002636Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002637[clinic start generated code]*/
2638
2639static PyObject *
2640_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002641/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002642{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002643 _PySSLError err;
2644 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002645 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002646 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002647 _PyTime_t timeout, deadline = 0;
2648 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002649
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002650 if (sock != NULL) {
2651 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002652 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002653 _setSSLError("Underlying socket connection gone",
2654 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2655 return NULL;
2656 }
2657 Py_INCREF(sock);
2658
2659 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002660 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002661 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2662 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002663 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002664
Victor Stinner14690702015-04-06 22:46:13 +02002665 timeout = GET_SOCKET_TIMEOUT(sock);
2666 has_timeout = (timeout > 0);
2667 if (has_timeout)
2668 deadline = _PyTime_GetMonotonicClock() + timeout;
2669
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002670 while (1) {
2671 PySSL_BEGIN_ALLOW_THREADS
2672 /* Disable read-ahead so that unwrap can work correctly.
2673 * Otherwise OpenSSL might read in too much data,
2674 * eating clear text data that happens to be
2675 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002676 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002677 * function is used and the shutdown_seen_zero != 0
2678 * condition is met.
2679 */
2680 if (self->shutdown_seen_zero)
2681 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002682 ret = SSL_shutdown(self->ssl);
2683 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002684 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002685 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002686
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002687 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002688 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002689 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002690 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002691 /* Don't loop endlessly; instead preserve legacy
2692 behaviour of trying SSL_shutdown() only twice.
2693 This looks necessary for OpenSSL < 0.9.8m */
2694 if (++zeros > 1)
2695 break;
2696 /* Shutdown was sent, now try receiving */
2697 self->shutdown_seen_zero = 1;
2698 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002699 }
2700
Victor Stinner14690702015-04-06 22:46:13 +02002701 if (has_timeout)
2702 timeout = deadline - _PyTime_GetMonotonicClock();
2703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002704 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002705 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002706 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002707 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002708 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002709 else
2710 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002711
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002712 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002713 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002714 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002715 "The read operation timed out");
2716 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002717 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002718 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002719 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002720 }
2721 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2722 PyErr_SetString(PySSLErrorObject,
2723 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002724 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002725 }
2726 else if (sockstate != SOCKET_OPERATION_OK)
2727 /* Retain the SSL error code */
2728 break;
2729 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002730 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002731 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002732 PySSL_SetError(self, ret, __FILE__, __LINE__);
2733 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002734 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002735 if (self->exc_type != NULL)
2736 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002737 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002738 /* It's already INCREF'ed */
2739 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002740 else
2741 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002742
2743error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002744 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002745 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002746 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002747}
2748
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002749/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002750_ssl._SSLSocket.get_channel_binding
2751 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002752
Christian Heimes141c5e82018-02-24 21:10:57 +01002753Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002754
Christian Heimes141c5e82018-02-24 21:10:57 +01002755Raise ValueError if the requested `cb_type` is not supported. Return bytes
2756of the data or None if the data is not available (e.g. before the handshake).
2757Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002758[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002759
Antoine Pitroud6494802011-07-21 01:11:30 +02002760static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002761_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2762 const char *cb_type)
2763/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002764{
Antoine Pitroud6494802011-07-21 01:11:30 +02002765 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002766 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002767
Christian Heimes141c5e82018-02-24 21:10:57 +01002768 if (strcmp(cb_type, "tls-unique") == 0) {
2769 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2770 /* if session is resumed XOR we are the client */
2771 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2772 }
2773 else {
2774 /* if a new session XOR we are the server */
2775 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2776 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002777 }
2778 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002779 PyErr_Format(
2780 PyExc_ValueError,
2781 "'%s' channel binding type not implemented",
2782 cb_type
2783 );
2784 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002785 }
2786
2787 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002788 if (len == 0)
2789 Py_RETURN_NONE;
2790
Christian Heimes141c5e82018-02-24 21:10:57 +01002791 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002792}
2793
Christian Heimes9fb051f2018-09-23 08:32:31 +02002794/*[clinic input]
2795_ssl._SSLSocket.verify_client_post_handshake
2796
2797Initiate TLS 1.3 post-handshake authentication
2798[clinic start generated code]*/
2799
2800static PyObject *
2801_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2802/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2803{
2804#ifdef TLS1_3_VERSION
2805 int err = SSL_verify_client_post_handshake(self->ssl);
2806 if (err == 0)
2807 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2808 else
2809 Py_RETURN_NONE;
2810#else
2811 PyErr_SetString(PyExc_NotImplementedError,
2812 "Post-handshake auth is not supported by your "
2813 "OpenSSL version.");
2814 return NULL;
2815#endif
2816}
2817
Christian Heimes99a65702016-09-10 23:44:53 +02002818#ifdef OPENSSL_VERSION_1_1
2819
2820static SSL_SESSION*
2821_ssl_session_dup(SSL_SESSION *session) {
2822 SSL_SESSION *newsession = NULL;
2823 int slen;
2824 unsigned char *senc = NULL, *p;
2825 const unsigned char *const_p;
2826
2827 if (session == NULL) {
2828 PyErr_SetString(PyExc_ValueError, "Invalid session");
2829 goto error;
2830 }
2831
2832 /* get length */
2833 slen = i2d_SSL_SESSION(session, NULL);
2834 if (slen == 0 || slen > 0xFF00) {
2835 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2836 goto error;
2837 }
2838 if ((senc = PyMem_Malloc(slen)) == NULL) {
2839 PyErr_NoMemory();
2840 goto error;
2841 }
2842 p = senc;
2843 if (!i2d_SSL_SESSION(session, &p)) {
2844 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2845 goto error;
2846 }
2847 const_p = senc;
2848 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2849 if (session == NULL) {
2850 goto error;
2851 }
2852 PyMem_Free(senc);
2853 return newsession;
2854 error:
2855 if (senc != NULL) {
2856 PyMem_Free(senc);
2857 }
2858 return NULL;
2859}
2860#endif
2861
2862static PyObject *
2863PySSL_get_session(PySSLSocket *self, void *closure) {
2864 /* get_session can return sessions from a server-side connection,
2865 * it does not check for handshake done or client socket. */
2866 PySSLSession *pysess;
2867 SSL_SESSION *session;
2868
2869#ifdef OPENSSL_VERSION_1_1
2870 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2871 * https://github.com/openssl/openssl/issues/1550 */
2872 session = SSL_get0_session(self->ssl); /* borrowed reference */
2873 if (session == NULL) {
2874 Py_RETURN_NONE;
2875 }
2876 if ((session = _ssl_session_dup(session)) == NULL) {
2877 return NULL;
2878 }
2879#else
2880 session = SSL_get1_session(self->ssl);
2881 if (session == NULL) {
2882 Py_RETURN_NONE;
2883 }
2884#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002885 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002886 if (pysess == NULL) {
2887 SSL_SESSION_free(session);
2888 return NULL;
2889 }
2890
2891 assert(self->ctx);
2892 pysess->ctx = self->ctx;
2893 Py_INCREF(pysess->ctx);
2894 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002895 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002896 return (PyObject *)pysess;
2897}
2898
2899static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2900 void *closure)
2901 {
2902 PySSLSession *pysess;
2903#ifdef OPENSSL_VERSION_1_1
2904 SSL_SESSION *session;
2905#endif
2906 int result;
2907
2908 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002909 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002910 return -1;
2911 }
2912 pysess = (PySSLSession *)value;
2913
2914 if (self->ctx->ctx != pysess->ctx->ctx) {
2915 PyErr_SetString(PyExc_ValueError,
2916 "Session refers to a different SSLContext.");
2917 return -1;
2918 }
2919 if (self->socket_type != PY_SSL_CLIENT) {
2920 PyErr_SetString(PyExc_ValueError,
2921 "Cannot set session for server-side SSLSocket.");
2922 return -1;
2923 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002924 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002925 PyErr_SetString(PyExc_ValueError,
2926 "Cannot set session after handshake.");
2927 return -1;
2928 }
2929#ifdef OPENSSL_VERSION_1_1
2930 /* duplicate session */
2931 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2932 return -1;
2933 }
2934 result = SSL_set_session(self->ssl, session);
2935 /* free duplicate, SSL_set_session() bumps ref count */
2936 SSL_SESSION_free(session);
2937#else
2938 result = SSL_set_session(self->ssl, pysess->session);
2939#endif
2940 if (result == 0) {
2941 _setSSLError(NULL, 0, __FILE__, __LINE__);
2942 return -1;
2943 }
2944 return 0;
2945}
2946
2947PyDoc_STRVAR(PySSL_set_session_doc,
2948"_setter_session(session)\n\
2949\
2950Get / set SSLSession.");
2951
2952static PyObject *
2953PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2954 if (SSL_session_reused(self->ssl)) {
2955 Py_RETURN_TRUE;
2956 } else {
2957 Py_RETURN_FALSE;
2958 }
2959}
2960
2961PyDoc_STRVAR(PySSL_get_session_reused_doc,
2962"Was the client session reused during handshake?");
2963
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002964static PyGetSetDef ssl_getsetlist[] = {
2965 {"context", (getter) PySSL_get_context,
2966 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002967 {"server_side", (getter) PySSL_get_server_side, NULL,
2968 PySSL_get_server_side_doc},
2969 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2970 PySSL_get_server_hostname_doc},
2971 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2972 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002973 {"session", (getter) PySSL_get_session,
2974 (setter) PySSL_set_session, PySSL_set_session_doc},
2975 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2976 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002977 {NULL}, /* sentinel */
2978};
2979
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002980static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002981 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2982 _SSL__SSLSOCKET_WRITE_METHODDEF
2983 _SSL__SSLSOCKET_READ_METHODDEF
2984 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002985 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2986 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002987 _SSL__SSLSOCKET_CIPHER_METHODDEF
2988 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2989 _SSL__SSLSOCKET_VERSION_METHODDEF
2990 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2991 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2992 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2993 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002994 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002995 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002996};
2997
Antoine Pitrou152efa22010-05-16 18:19:27 +00002998static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002999 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00003000 "_ssl._SSLSocket", /*tp_name*/
3001 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003002 0, /*tp_itemsize*/
3003 /* methods */
3004 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003005 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003006 0, /*tp_getattr*/
3007 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02003008 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003009 0, /*tp_repr*/
3010 0, /*tp_as_number*/
3011 0, /*tp_as_sequence*/
3012 0, /*tp_as_mapping*/
3013 0, /*tp_hash*/
3014 0, /*tp_call*/
3015 0, /*tp_str*/
3016 0, /*tp_getattro*/
3017 0, /*tp_setattro*/
3018 0, /*tp_as_buffer*/
3019 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3020 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003021 (traverseproc) PySSL_traverse, /*tp_traverse*/
3022 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003023 0, /*tp_richcompare*/
3024 0, /*tp_weaklistoffset*/
3025 0, /*tp_iter*/
3026 0, /*tp_iternext*/
3027 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003028 0, /*tp_members*/
3029 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003030};
3031
Antoine Pitrou152efa22010-05-16 18:19:27 +00003032
3033/*
3034 * _SSLContext objects
3035 */
3036
Christian Heimes5fe668c2016-09-12 00:01:11 +02003037static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003038_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003039{
3040 int mode;
3041 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3042
3043 switch(n) {
3044 case PY_SSL_CERT_NONE:
3045 mode = SSL_VERIFY_NONE;
3046 break;
3047 case PY_SSL_CERT_OPTIONAL:
3048 mode = SSL_VERIFY_PEER;
3049 break;
3050 case PY_SSL_CERT_REQUIRED:
3051 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3052 break;
3053 default:
3054 PyErr_SetString(PyExc_ValueError,
3055 "invalid value for verify_mode");
3056 return -1;
3057 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003058
3059 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3060 * server sockets and SSL_set_post_handshake_auth() for client. */
3061
Christian Heimes5fe668c2016-09-12 00:01:11 +02003062 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003063 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3064 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003065 return 0;
3066}
3067
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003068/*[clinic input]
3069@classmethod
3070_ssl._SSLContext.__new__
3071 protocol as proto_version: int
3072 /
3073[clinic start generated code]*/
3074
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003076_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3077/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003078{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003079 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003080 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003081 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003082 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003083 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003084#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003085 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003086#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087
Antoine Pitrou152efa22010-05-16 18:19:27 +00003088 PySSL_BEGIN_ALLOW_THREADS
3089 if (proto_version == PY_SSL_VERSION_TLS1)
3090 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003091#if HAVE_TLSv1_2
3092 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3093 ctx = SSL_CTX_new(TLSv1_1_method());
3094 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3095 ctx = SSL_CTX_new(TLSv1_2_method());
3096#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003097#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003098 else if (proto_version == PY_SSL_VERSION_SSL3)
3099 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003100#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003101#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003102 else if (proto_version == PY_SSL_VERSION_SSL2)
3103 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003104#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003105 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003106 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003107 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3108 ctx = SSL_CTX_new(TLS_client_method());
3109 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3110 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003111 else
3112 proto_version = -1;
3113 PySSL_END_ALLOW_THREADS
3114
3115 if (proto_version == -1) {
3116 PyErr_SetString(PyExc_ValueError,
3117 "invalid protocol version");
3118 return NULL;
3119 }
3120 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003121 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003122 return NULL;
3123 }
3124
3125 assert(type != NULL && type->tp_alloc != NULL);
3126 self = (PySSLContext *) type->tp_alloc(type, 0);
3127 if (self == NULL) {
3128 SSL_CTX_free(ctx);
3129 return NULL;
3130 }
3131 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003132 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003133 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003134 self->msg_cb = NULL;
3135#ifdef HAVE_OPENSSL_KEYLOG
3136 self->keylog_filename = NULL;
3137 self->keylog_bio = NULL;
3138#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003139#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003140 self->npn_protocols = NULL;
3141#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003142#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003143 self->alpn_protocols = NULL;
3144#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003145#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003146 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003147#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003148 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003149 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3150 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003151 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003152 Py_DECREF(self);
3153 return NULL;
3154 }
3155 } else {
3156 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003157 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003158 Py_DECREF(self);
3159 return NULL;
3160 }
3161 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003162 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003163 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3164 if (proto_version != PY_SSL_VERSION_SSL2)
3165 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003166 if (proto_version != PY_SSL_VERSION_SSL3)
3167 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003168 /* Minimal security flags for server and client side context.
3169 * Client sockets ignore server-side parameters. */
3170#ifdef SSL_OP_NO_COMPRESSION
3171 options |= SSL_OP_NO_COMPRESSION;
3172#endif
3173#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3174 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3175#endif
3176#ifdef SSL_OP_SINGLE_DH_USE
3177 options |= SSL_OP_SINGLE_DH_USE;
3178#endif
3179#ifdef SSL_OP_SINGLE_ECDH_USE
3180 options |= SSL_OP_SINGLE_ECDH_USE;
3181#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003182 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003183
Semen Zhydenko1295e112017-10-15 21:28:31 +02003184 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003185 * It's far from perfect but gives users a better head start. */
3186 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003187#if PY_SSL_DEFAULT_CIPHERS == 2
3188 /* stick to OpenSSL's default settings */
3189 result = 1;
3190#else
3191 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3192#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003193 } else {
3194 /* SSLv2 needs MD5 */
3195 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3196 }
3197 if (result == 0) {
3198 Py_DECREF(self);
3199 ERR_clear_error();
3200 PyErr_SetString(PySSLErrorObject,
3201 "No cipher can be selected.");
3202 return NULL;
3203 }
3204
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003205#if defined(SSL_MODE_RELEASE_BUFFERS)
3206 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3207 usage for no cost at all. However, don't do this for OpenSSL versions
3208 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3209 2014-0198. I can't find exactly which beta fixed this CVE, so be
3210 conservative and assume it wasn't fixed until release. We do this check
3211 at runtime to avoid problems from the dynamic linker.
3212 See #25672 for more on this. */
3213 libver = SSLeay();
3214 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3215 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3216 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3217 }
3218#endif
3219
3220
Donald Stufft8ae264c2017-03-02 11:45:29 -05003221#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003222 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3223 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003224 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3225 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003226#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003227 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3228#else
3229 {
3230 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3231 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3232 EC_KEY_free(key);
3233 }
3234#endif
3235#endif
3236
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003237#define SID_CTX "Python"
3238 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3239 sizeof(SID_CTX));
3240#undef SID_CTX
3241
Christian Heimes61d478c2018-01-27 15:51:38 +01003242 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003243#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003244 /* Improve trust chain building when cross-signed intermediate
3245 certificates are present. See https://bugs.python.org/issue23476. */
3246 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003247#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003248 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003249
Christian Heimes9fb051f2018-09-23 08:32:31 +02003250#ifdef TLS1_3_VERSION
3251 self->post_handshake_auth = 0;
3252 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3253#endif
3254
Antoine Pitrou152efa22010-05-16 18:19:27 +00003255 return (PyObject *)self;
3256}
3257
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003258static int
3259context_traverse(PySSLContext *self, visitproc visit, void *arg)
3260{
3261#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003262 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003263#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003264 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003265 return 0;
3266}
3267
3268static int
3269context_clear(PySSLContext *self)
3270{
3271#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003272 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003273#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003274 Py_CLEAR(self->msg_cb);
3275#ifdef HAVE_OPENSSL_KEYLOG
3276 Py_CLEAR(self->keylog_filename);
3277 if (self->keylog_bio != NULL) {
3278 PySSL_BEGIN_ALLOW_THREADS
3279 BIO_free_all(self->keylog_bio);
3280 PySSL_END_ALLOW_THREADS
3281 self->keylog_bio = NULL;
3282 }
3283#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003284 return 0;
3285}
3286
Antoine Pitrou152efa22010-05-16 18:19:27 +00003287static void
3288context_dealloc(PySSLContext *self)
3289{
INADA Naokia6296d32017-08-24 14:55:17 +09003290 /* bpo-31095: UnTrack is needed before calling any callbacks */
3291 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003292 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003293 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003294#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003295 PyMem_FREE(self->npn_protocols);
3296#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003297#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003298 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003299#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003300 Py_TYPE(self)->tp_free(self);
3301}
3302
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003303/*[clinic input]
3304_ssl._SSLContext.set_ciphers
3305 cipherlist: str
3306 /
3307[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003308
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003309static PyObject *
3310_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3311/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3312{
3313 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003315 /* Clearing the error queue is necessary on some OpenSSL versions,
3316 otherwise the error will be reported again when another SSL call
3317 is done. */
3318 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003319 PyErr_SetString(PySSLErrorObject,
3320 "No cipher can be selected.");
3321 return NULL;
3322 }
3323 Py_RETURN_NONE;
3324}
3325
Christian Heimes25bfcd52016-09-06 00:04:45 +02003326#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3327/*[clinic input]
3328_ssl._SSLContext.get_ciphers
3329[clinic start generated code]*/
3330
3331static PyObject *
3332_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3333/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3334{
3335 SSL *ssl = NULL;
3336 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003337 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003338 int i=0;
3339 PyObject *result = NULL, *dct;
3340
3341 ssl = SSL_new(self->ctx);
3342 if (ssl == NULL) {
3343 _setSSLError(NULL, 0, __FILE__, __LINE__);
3344 goto exit;
3345 }
3346 sk = SSL_get_ciphers(ssl);
3347
3348 result = PyList_New(sk_SSL_CIPHER_num(sk));
3349 if (result == NULL) {
3350 goto exit;
3351 }
3352
3353 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3354 cipher = sk_SSL_CIPHER_value(sk, i);
3355 dct = cipher_to_dict(cipher);
3356 if (dct == NULL) {
3357 Py_CLEAR(result);
3358 goto exit;
3359 }
3360 PyList_SET_ITEM(result, i, dct);
3361 }
3362
3363 exit:
3364 if (ssl != NULL)
3365 SSL_free(ssl);
3366 return result;
3367
3368}
3369#endif
3370
3371
Christian Heimes29eab552018-02-25 12:31:33 +01003372#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003373static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003374do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3375 const unsigned char *server_protocols, unsigned int server_protocols_len,
3376 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003377{
Benjamin Peterson88615022015-01-23 17:30:26 -05003378 int ret;
3379 if (client_protocols == NULL) {
3380 client_protocols = (unsigned char *)"";
3381 client_protocols_len = 0;
3382 }
3383 if (server_protocols == NULL) {
3384 server_protocols = (unsigned char *)"";
3385 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003386 }
3387
Benjamin Peterson88615022015-01-23 17:30:26 -05003388 ret = SSL_select_next_proto(out, outlen,
3389 server_protocols, server_protocols_len,
3390 client_protocols, client_protocols_len);
3391 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3392 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003393
3394 return SSL_TLSEXT_ERR_OK;
3395}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003396#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003397
Christian Heimes29eab552018-02-25 12:31:33 +01003398#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003399/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3400static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003401_advertiseNPN_cb(SSL *s,
3402 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003403 void *args)
3404{
3405 PySSLContext *ssl_ctx = (PySSLContext *) args;
3406
3407 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003408 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003409 *len = 0;
3410 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003411 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003412 *len = ssl_ctx->npn_protocols_len;
3413 }
3414
3415 return SSL_TLSEXT_ERR_OK;
3416}
3417/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3418static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003419_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003420 unsigned char **out, unsigned char *outlen,
3421 const unsigned char *server, unsigned int server_len,
3422 void *args)
3423{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003424 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003425 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003426 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003427}
3428#endif
3429
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003430/*[clinic input]
3431_ssl._SSLContext._set_npn_protocols
3432 protos: Py_buffer
3433 /
3434[clinic start generated code]*/
3435
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003436static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003437_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3438 Py_buffer *protos)
3439/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003440{
Christian Heimes29eab552018-02-25 12:31:33 +01003441#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003442 PyMem_Free(self->npn_protocols);
3443 self->npn_protocols = PyMem_Malloc(protos->len);
3444 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003445 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003446 memcpy(self->npn_protocols, protos->buf, protos->len);
3447 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003448
3449 /* set both server and client callbacks, because the context can
3450 * be used to create both types of sockets */
3451 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3452 _advertiseNPN_cb,
3453 self);
3454 SSL_CTX_set_next_proto_select_cb(self->ctx,
3455 _selectNPN_cb,
3456 self);
3457
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003458 Py_RETURN_NONE;
3459#else
3460 PyErr_SetString(PyExc_NotImplementedError,
3461 "The NPN extension requires OpenSSL 1.0.1 or later.");
3462 return NULL;
3463#endif
3464}
3465
Christian Heimes29eab552018-02-25 12:31:33 +01003466#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003467static int
3468_selectALPN_cb(SSL *s,
3469 const unsigned char **out, unsigned char *outlen,
3470 const unsigned char *client_protocols, unsigned int client_protocols_len,
3471 void *args)
3472{
3473 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003474 return do_protocol_selection(1, (unsigned char **)out, outlen,
3475 ctx->alpn_protocols, ctx->alpn_protocols_len,
3476 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003477}
3478#endif
3479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003480/*[clinic input]
3481_ssl._SSLContext._set_alpn_protocols
3482 protos: Py_buffer
3483 /
3484[clinic start generated code]*/
3485
Benjamin Petersoncca27322015-01-23 16:35:37 -05003486static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003487_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3488 Py_buffer *protos)
3489/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003490{
Christian Heimes29eab552018-02-25 12:31:33 +01003491#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003492 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003493 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003494 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003495 return NULL;
3496 }
3497
Benjamin Petersoncca27322015-01-23 16:35:37 -05003498 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003499 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003500 if (!self->alpn_protocols)
3501 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003502 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003503 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003504
3505 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3506 return PyErr_NoMemory();
3507 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3508
Benjamin Petersoncca27322015-01-23 16:35:37 -05003509 Py_RETURN_NONE;
3510#else
3511 PyErr_SetString(PyExc_NotImplementedError,
3512 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3513 return NULL;
3514#endif
3515}
3516
Antoine Pitrou152efa22010-05-16 18:19:27 +00003517static PyObject *
3518get_verify_mode(PySSLContext *self, void *c)
3519{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003520 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3521 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3522 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3523 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003524 case SSL_VERIFY_NONE:
3525 return PyLong_FromLong(PY_SSL_CERT_NONE);
3526 case SSL_VERIFY_PEER:
3527 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3528 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3529 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3530 }
3531 PyErr_SetString(PySSLErrorObject,
3532 "invalid return value from SSL_CTX_get_verify_mode");
3533 return NULL;
3534}
3535
3536static int
3537set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3538{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003539 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003540 if (!PyArg_Parse(arg, "i", &n))
3541 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003542 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003543 PyErr_SetString(PyExc_ValueError,
3544 "Cannot set verify_mode to CERT_NONE when "
3545 "check_hostname is enabled.");
3546 return -1;
3547 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003548 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003549}
3550
3551static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003552get_verify_flags(PySSLContext *self, void *c)
3553{
Christian Heimes598894f2016-09-05 23:19:05 +02003554 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003555 unsigned long flags;
3556
Christian Heimes61d478c2018-01-27 15:51:38 +01003557 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003558 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003559 return PyLong_FromUnsignedLong(flags);
3560}
3561
3562static int
3563set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3564{
Christian Heimes598894f2016-09-05 23:19:05 +02003565 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003566 unsigned long new_flags, flags, set, clear;
3567
3568 if (!PyArg_Parse(arg, "k", &new_flags))
3569 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003570 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003571 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003572 clear = flags & ~new_flags;
3573 set = ~flags & new_flags;
3574 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003575 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003576 _setSSLError(NULL, 0, __FILE__, __LINE__);
3577 return -1;
3578 }
3579 }
3580 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003581 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003582 _setSSLError(NULL, 0, __FILE__, __LINE__);
3583 return -1;
3584 }
3585 }
3586 return 0;
3587}
3588
Christian Heimes698dde12018-02-27 11:54:43 +01003589/* Getter and setter for protocol version */
3590#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3591
3592
3593static int
3594set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3595{
3596 long v;
3597 int result;
3598
3599 if (!PyArg_Parse(arg, "l", &v))
3600 return -1;
3601 if (v > INT_MAX) {
3602 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3603 return -1;
3604 }
3605
3606 switch(self->protocol) {
3607 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3608 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3609 case PY_SSL_VERSION_TLS:
3610 break;
3611 default:
3612 PyErr_SetString(
3613 PyExc_ValueError,
3614 "The context's protocol doesn't support modification of "
3615 "highest and lowest version."
3616 );
3617 return -1;
3618 }
3619
3620 if (what == 0) {
3621 switch(v) {
3622 case PY_PROTO_MINIMUM_SUPPORTED:
3623 v = 0;
3624 break;
3625 case PY_PROTO_MAXIMUM_SUPPORTED:
3626 /* Emulate max for set_min_proto_version */
3627 v = PY_PROTO_MAXIMUM_AVAILABLE;
3628 break;
3629 default:
3630 break;
3631 }
3632 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3633 }
3634 else {
3635 switch(v) {
3636 case PY_PROTO_MAXIMUM_SUPPORTED:
3637 v = 0;
3638 break;
3639 case PY_PROTO_MINIMUM_SUPPORTED:
3640 /* Emulate max for set_min_proto_version */
3641 v = PY_PROTO_MINIMUM_AVAILABLE;
3642 break;
3643 default:
3644 break;
3645 }
3646 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3647 }
3648 if (result == 0) {
3649 PyErr_Format(PyExc_ValueError,
3650 "Unsupported protocol version 0x%x", v);
3651 return -1;
3652 }
3653 return 0;
3654}
3655
3656static PyObject *
3657get_minimum_version(PySSLContext *self, void *c)
3658{
3659 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3660 if (v == 0) {
3661 v = PY_PROTO_MINIMUM_SUPPORTED;
3662 }
3663 return PyLong_FromLong(v);
3664}
3665
3666static int
3667set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3668{
3669 return set_min_max_proto_version(self, arg, 0);
3670}
3671
3672static PyObject *
3673get_maximum_version(PySSLContext *self, void *c)
3674{
3675 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3676 if (v == 0) {
3677 v = PY_PROTO_MAXIMUM_SUPPORTED;
3678 }
3679 return PyLong_FromLong(v);
3680}
3681
3682static int
3683set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3684{
3685 return set_min_max_proto_version(self, arg, 1);
3686}
3687#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3688
Christian Heimes78c7d522019-06-03 21:00:10 +02003689#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3690static PyObject *
3691get_num_tickets(PySSLContext *self, void *c)
3692{
Victor Stinner76611c72019-07-09 13:30:52 +02003693 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003694}
3695
3696static int
3697set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3698{
3699 long num;
3700 if (!PyArg_Parse(arg, "l", &num))
3701 return -1;
3702 if (num < 0) {
3703 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3704 return -1;
3705 }
3706 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3707 PyErr_SetString(PyExc_ValueError,
3708 "SSLContext is not a server context.");
3709 return -1;
3710 }
3711 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3712 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3713 return -1;
3714 }
3715 return 0;
3716}
3717
3718PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3719"Control the number of TLSv1.3 session tickets");
3720#endif /* OpenSSL 1.1.1 */
3721
Christian Heimes22587792013-11-21 23:56:13 +01003722static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003723get_options(PySSLContext *self, void *c)
3724{
3725 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3726}
3727
3728static int
3729set_options(PySSLContext *self, PyObject *arg, void *c)
3730{
3731 long new_opts, opts, set, clear;
3732 if (!PyArg_Parse(arg, "l", &new_opts))
3733 return -1;
3734 opts = SSL_CTX_get_options(self->ctx);
3735 clear = opts & ~new_opts;
3736 set = ~opts & new_opts;
3737 if (clear) {
3738#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3739 SSL_CTX_clear_options(self->ctx, clear);
3740#else
3741 PyErr_SetString(PyExc_ValueError,
3742 "can't clear options before OpenSSL 0.9.8m");
3743 return -1;
3744#endif
3745 }
3746 if (set)
3747 SSL_CTX_set_options(self->ctx, set);
3748 return 0;
3749}
3750
Christian Heimes1aa9a752013-12-02 02:41:19 +01003751static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003752get_host_flags(PySSLContext *self, void *c)
3753{
3754 return PyLong_FromUnsignedLong(self->hostflags);
3755}
3756
3757static int
3758set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3759{
3760 X509_VERIFY_PARAM *param;
3761 unsigned int new_flags = 0;
3762
3763 if (!PyArg_Parse(arg, "I", &new_flags))
3764 return -1;
3765
3766 param = SSL_CTX_get0_param(self->ctx);
3767 self->hostflags = new_flags;
3768 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3769 return 0;
3770}
3771
3772static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003773get_check_hostname(PySSLContext *self, void *c)
3774{
3775 return PyBool_FromLong(self->check_hostname);
3776}
3777
3778static int
3779set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3780{
3781 int check_hostname;
3782 if (!PyArg_Parse(arg, "p", &check_hostname))
3783 return -1;
3784 if (check_hostname &&
3785 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003786 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003787 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003788 return -1;
3789 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003790 }
3791 self->check_hostname = check_hostname;
3792 return 0;
3793}
3794
Christian Heimes11a14932018-02-24 02:35:08 +01003795static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003796get_post_handshake_auth(PySSLContext *self, void *c) {
3797#if TLS1_3_VERSION
3798 return PyBool_FromLong(self->post_handshake_auth);
3799#else
3800 Py_RETURN_NONE;
3801#endif
3802}
3803
3804#if TLS1_3_VERSION
3805static int
3806set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003807 if (arg == NULL) {
3808 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3809 return -1;
3810 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003811 int pha = PyObject_IsTrue(arg);
3812
3813 if (pha == -1) {
3814 return -1;
3815 }
3816 self->post_handshake_auth = pha;
3817
Christian Heimesf0f59302019-07-01 08:29:17 +02003818 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3819 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003820
3821 return 0;
3822}
3823#endif
3824
3825static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003826get_protocol(PySSLContext *self, void *c) {
3827 return PyLong_FromLong(self->protocol);
3828}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003829
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003830typedef struct {
3831 PyThreadState *thread_state;
3832 PyObject *callable;
3833 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003834 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003835 int error;
3836} _PySSLPasswordInfo;
3837
3838static int
3839_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3840 const char *bad_type_error)
3841{
3842 /* Set the password and size fields of a _PySSLPasswordInfo struct
3843 from a unicode, bytes, or byte array object.
3844 The password field will be dynamically allocated and must be freed
3845 by the caller */
3846 PyObject *password_bytes = NULL;
3847 const char *data = NULL;
3848 Py_ssize_t size;
3849
3850 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003851 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003852 if (!password_bytes) {
3853 goto error;
3854 }
3855 data = PyBytes_AS_STRING(password_bytes);
3856 size = PyBytes_GET_SIZE(password_bytes);
3857 } else if (PyBytes_Check(password)) {
3858 data = PyBytes_AS_STRING(password);
3859 size = PyBytes_GET_SIZE(password);
3860 } else if (PyByteArray_Check(password)) {
3861 data = PyByteArray_AS_STRING(password);
3862 size = PyByteArray_GET_SIZE(password);
3863 } else {
3864 PyErr_SetString(PyExc_TypeError, bad_type_error);
3865 goto error;
3866 }
3867
Victor Stinner9ee02032013-06-23 15:08:23 +02003868 if (size > (Py_ssize_t)INT_MAX) {
3869 PyErr_Format(PyExc_ValueError,
3870 "password cannot be longer than %d bytes", INT_MAX);
3871 goto error;
3872 }
3873
Victor Stinner11ebff22013-07-07 17:07:52 +02003874 PyMem_Free(pw_info->password);
3875 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003876 if (!pw_info->password) {
3877 PyErr_SetString(PyExc_MemoryError,
3878 "unable to allocate password buffer");
3879 goto error;
3880 }
3881 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003882 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003883
3884 Py_XDECREF(password_bytes);
3885 return 1;
3886
3887error:
3888 Py_XDECREF(password_bytes);
3889 return 0;
3890}
3891
3892static int
3893_password_callback(char *buf, int size, int rwflag, void *userdata)
3894{
3895 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3896 PyObject *fn_ret = NULL;
3897
3898 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3899
3900 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003901 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003902 if (!fn_ret) {
3903 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3904 core python API, so we could use it to add a frame here */
3905 goto error;
3906 }
3907
3908 if (!_pwinfo_set(pw_info, fn_ret,
3909 "password callback must return a string")) {
3910 goto error;
3911 }
3912 Py_CLEAR(fn_ret);
3913 }
3914
3915 if (pw_info->size > size) {
3916 PyErr_Format(PyExc_ValueError,
3917 "password cannot be longer than %d bytes", size);
3918 goto error;
3919 }
3920
3921 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3922 memcpy(buf, pw_info->password, pw_info->size);
3923 return pw_info->size;
3924
3925error:
3926 Py_XDECREF(fn_ret);
3927 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3928 pw_info->error = 1;
3929 return -1;
3930}
3931
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003932/*[clinic input]
3933_ssl._SSLContext.load_cert_chain
3934 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003935 keyfile: object = None
3936 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003937
3938[clinic start generated code]*/
3939
Antoine Pitroub5218772010-05-21 09:56:06 +00003940static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003941_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3942 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003943/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003944{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003945 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003946 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3947 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003948 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003949 int r;
3950
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003951 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003952 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003953 if (keyfile == Py_None)
3954 keyfile = NULL;
3955 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003956 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3957 PyErr_SetString(PyExc_TypeError,
3958 "certfile should be a valid filesystem path");
3959 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003960 return NULL;
3961 }
3962 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003963 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3964 PyErr_SetString(PyExc_TypeError,
3965 "keyfile should be a valid filesystem path");
3966 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003967 goto error;
3968 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003969 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003970 if (PyCallable_Check(password)) {
3971 pw_info.callable = password;
3972 } else if (!_pwinfo_set(&pw_info, password,
3973 "password should be a string or callable")) {
3974 goto error;
3975 }
3976 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3977 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3978 }
3979 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003980 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3981 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003982 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003983 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003984 if (pw_info.error) {
3985 ERR_clear_error();
3986 /* the password callback has already set the error information */
3987 }
3988 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003989 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003990 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003991 }
3992 else {
3993 _setSSLError(NULL, 0, __FILE__, __LINE__);
3994 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995 goto error;
3996 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003997 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003998 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003999 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
4000 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004001 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
4002 Py_CLEAR(keyfile_bytes);
4003 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004005 if (pw_info.error) {
4006 ERR_clear_error();
4007 /* the password callback has already set the error information */
4008 }
4009 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004010 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004011 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004012 }
4013 else {
4014 _setSSLError(NULL, 0, __FILE__, __LINE__);
4015 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004016 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004017 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004018 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004019 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004020 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 if (r != 1) {
4022 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004023 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004025 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4026 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004027 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004028 Py_RETURN_NONE;
4029
4030error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004031 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4032 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004033 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004034 Py_XDECREF(keyfile_bytes);
4035 Py_XDECREF(certfile_bytes);
4036 return NULL;
4037}
4038
Christian Heimesefff7062013-11-21 03:35:02 +01004039/* internal helper function, returns -1 on error
4040 */
4041static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004042_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004043 int filetype)
4044{
4045 BIO *biobuf = NULL;
4046 X509_STORE *store;
4047 int retval = 0, err, loaded = 0;
4048
4049 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4050
4051 if (len <= 0) {
4052 PyErr_SetString(PyExc_ValueError,
4053 "Empty certificate data");
4054 return -1;
4055 } else if (len > INT_MAX) {
4056 PyErr_SetString(PyExc_OverflowError,
4057 "Certificate data is too long.");
4058 return -1;
4059 }
4060
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004061 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004062 if (biobuf == NULL) {
4063 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4064 return -1;
4065 }
4066
4067 store = SSL_CTX_get_cert_store(self->ctx);
4068 assert(store != NULL);
4069
4070 while (1) {
4071 X509 *cert = NULL;
4072 int r;
4073
4074 if (filetype == SSL_FILETYPE_ASN1) {
4075 cert = d2i_X509_bio(biobuf, NULL);
4076 } else {
4077 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004078 SSL_CTX_get_default_passwd_cb(self->ctx),
4079 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4080 );
Christian Heimesefff7062013-11-21 03:35:02 +01004081 }
4082 if (cert == NULL) {
4083 break;
4084 }
4085 r = X509_STORE_add_cert(store, cert);
4086 X509_free(cert);
4087 if (!r) {
4088 err = ERR_peek_last_error();
4089 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4090 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4091 /* cert already in hash table, not an error */
4092 ERR_clear_error();
4093 } else {
4094 break;
4095 }
4096 }
4097 loaded++;
4098 }
4099
4100 err = ERR_peek_last_error();
4101 if ((filetype == SSL_FILETYPE_ASN1) &&
4102 (loaded > 0) &&
4103 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4104 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4105 /* EOF ASN1 file, not an error */
4106 ERR_clear_error();
4107 retval = 0;
4108 } else if ((filetype == SSL_FILETYPE_PEM) &&
4109 (loaded > 0) &&
4110 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4111 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4112 /* EOF PEM file, not an error */
4113 ERR_clear_error();
4114 retval = 0;
4115 } else {
4116 _setSSLError(NULL, 0, __FILE__, __LINE__);
4117 retval = -1;
4118 }
4119
4120 BIO_free(biobuf);
4121 return retval;
4122}
4123
4124
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125/*[clinic input]
4126_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004127 cafile: object = None
4128 capath: object = None
4129 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130
4131[clinic start generated code]*/
4132
Antoine Pitrou152efa22010-05-16 18:19:27 +00004133static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004134_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4135 PyObject *cafile,
4136 PyObject *capath,
4137 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004138/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004139{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004140 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4141 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004142 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004143
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004144 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004145 if (cafile == Py_None)
4146 cafile = NULL;
4147 if (capath == Py_None)
4148 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004149 if (cadata == Py_None)
4150 cadata = NULL;
4151
4152 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004153 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004154 "cafile, capath and cadata cannot be all omitted");
4155 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004156 }
4157 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004158 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4159 PyErr_SetString(PyExc_TypeError,
4160 "cafile should be a valid filesystem path");
4161 }
Christian Heimesefff7062013-11-21 03:35:02 +01004162 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004163 }
4164 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004165 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4166 PyErr_SetString(PyExc_TypeError,
4167 "capath should be a valid filesystem path");
4168 }
Christian Heimesefff7062013-11-21 03:35:02 +01004169 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004170 }
Christian Heimesefff7062013-11-21 03:35:02 +01004171
4172 /* validata cadata type and load cadata */
4173 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004174 if (PyUnicode_Check(cadata)) {
4175 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4176 if (cadata_ascii == NULL) {
4177 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4178 goto invalid_cadata;
4179 }
4180 goto error;
4181 }
4182 r = _add_ca_certs(self,
4183 PyBytes_AS_STRING(cadata_ascii),
4184 PyBytes_GET_SIZE(cadata_ascii),
4185 SSL_FILETYPE_PEM);
4186 Py_DECREF(cadata_ascii);
4187 if (r == -1) {
4188 goto error;
4189 }
4190 }
4191 else if (PyObject_CheckBuffer(cadata)) {
4192 Py_buffer buf;
4193 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4194 goto error;
4195 }
Christian Heimesefff7062013-11-21 03:35:02 +01004196 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4197 PyBuffer_Release(&buf);
4198 PyErr_SetString(PyExc_TypeError,
4199 "cadata should be a contiguous buffer with "
4200 "a single dimension");
4201 goto error;
4202 }
4203 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4204 PyBuffer_Release(&buf);
4205 if (r == -1) {
4206 goto error;
4207 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004208 }
4209 else {
4210 invalid_cadata:
4211 PyErr_SetString(PyExc_TypeError,
4212 "cadata should be an ASCII string or a "
4213 "bytes-like object");
4214 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004215 }
4216 }
4217
4218 /* load cafile or capath */
4219 if (cafile || capath) {
4220 if (cafile)
4221 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4222 if (capath)
4223 capath_buf = PyBytes_AS_STRING(capath_bytes);
4224 PySSL_BEGIN_ALLOW_THREADS
4225 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4226 PySSL_END_ALLOW_THREADS
4227 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004228 if (errno != 0) {
4229 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004230 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004231 }
4232 else {
4233 _setSSLError(NULL, 0, __FILE__, __LINE__);
4234 }
4235 goto error;
4236 }
4237 }
4238 goto end;
4239
4240 error:
4241 ok = 0;
4242 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004243 Py_XDECREF(cafile_bytes);
4244 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004245 if (ok) {
4246 Py_RETURN_NONE;
4247 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004248 return NULL;
4249 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004250}
4251
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004252/*[clinic input]
4253_ssl._SSLContext.load_dh_params
4254 path as filepath: object
4255 /
4256
4257[clinic start generated code]*/
4258
Antoine Pitrou152efa22010-05-16 18:19:27 +00004259static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004260_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4261/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004262{
4263 FILE *f;
4264 DH *dh;
4265
Victor Stinnerdaf45552013-08-28 00:53:59 +02004266 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004267 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004268 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004269
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004270 errno = 0;
4271 PySSL_BEGIN_ALLOW_THREADS
4272 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004273 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004274 PySSL_END_ALLOW_THREADS
4275 if (dh == NULL) {
4276 if (errno != 0) {
4277 ERR_clear_error();
4278 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4279 }
4280 else {
4281 _setSSLError(NULL, 0, __FILE__, __LINE__);
4282 }
4283 return NULL;
4284 }
4285 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4286 _setSSLError(NULL, 0, __FILE__, __LINE__);
4287 DH_free(dh);
4288 Py_RETURN_NONE;
4289}
4290
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004291/*[clinic input]
4292_ssl._SSLContext._wrap_socket
4293 sock: object(subclass_of="PySocketModule.Sock_Type")
4294 server_side: int
4295 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004296 *
4297 owner: object = None
4298 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004299
4300[clinic start generated code]*/
4301
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004302static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004303_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004304 int server_side, PyObject *hostname_obj,
4305 PyObject *owner, PyObject *session)
4306/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004307{
Antoine Pitroud5323212010-10-22 18:19:07 +00004308 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004309 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004310
Antoine Pitroud5323212010-10-22 18:19:07 +00004311 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004312 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004313 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004314 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004315 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004316 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004318 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4319 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004320 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004321 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004322 if (hostname != NULL)
4323 PyMem_Free(hostname);
4324 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004325}
4326
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004327/*[clinic input]
4328_ssl._SSLContext._wrap_bio
4329 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4330 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4331 server_side: int
4332 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004333 *
4334 owner: object = None
4335 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004336
4337[clinic start generated code]*/
4338
Antoine Pitroub0182c82010-10-12 20:09:02 +00004339static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004340_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4341 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004342 PyObject *hostname_obj, PyObject *owner,
4343 PyObject *session)
4344/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004345{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004346 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004347 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004348
4349 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004350 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004351 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004352 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004353 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004354 }
4355
4356 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004357 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004358 incoming, outgoing);
4359
4360 PyMem_Free(hostname);
4361 return res;
4362}
4363
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004364/*[clinic input]
4365_ssl._SSLContext.session_stats
4366[clinic start generated code]*/
4367
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004368static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004369_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4370/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004371{
4372 int r;
4373 PyObject *value, *stats = PyDict_New();
4374 if (!stats)
4375 return NULL;
4376
4377#define ADD_STATS(SSL_NAME, KEY_NAME) \
4378 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4379 if (value == NULL) \
4380 goto error; \
4381 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4382 Py_DECREF(value); \
4383 if (r < 0) \
4384 goto error;
4385
4386 ADD_STATS(number, "number");
4387 ADD_STATS(connect, "connect");
4388 ADD_STATS(connect_good, "connect_good");
4389 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4390 ADD_STATS(accept, "accept");
4391 ADD_STATS(accept_good, "accept_good");
4392 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4393 ADD_STATS(accept, "accept");
4394 ADD_STATS(hits, "hits");
4395 ADD_STATS(misses, "misses");
4396 ADD_STATS(timeouts, "timeouts");
4397 ADD_STATS(cache_full, "cache_full");
4398
4399#undef ADD_STATS
4400
4401 return stats;
4402
4403error:
4404 Py_DECREF(stats);
4405 return NULL;
4406}
4407
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004408/*[clinic input]
4409_ssl._SSLContext.set_default_verify_paths
4410[clinic start generated code]*/
4411
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004412static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004413_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4414/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004415{
4416 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4417 _setSSLError(NULL, 0, __FILE__, __LINE__);
4418 return NULL;
4419 }
4420 Py_RETURN_NONE;
4421}
4422
Antoine Pitrou501da612011-12-21 09:27:41 +01004423#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004424/*[clinic input]
4425_ssl._SSLContext.set_ecdh_curve
4426 name: object
4427 /
4428
4429[clinic start generated code]*/
4430
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004431static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004432_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4433/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004434{
4435 PyObject *name_bytes;
4436 int nid;
4437 EC_KEY *key;
4438
4439 if (!PyUnicode_FSConverter(name, &name_bytes))
4440 return NULL;
4441 assert(PyBytes_Check(name_bytes));
4442 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4443 Py_DECREF(name_bytes);
4444 if (nid == 0) {
4445 PyErr_Format(PyExc_ValueError,
4446 "unknown elliptic curve name %R", name);
4447 return NULL;
4448 }
4449 key = EC_KEY_new_by_curve_name(nid);
4450 if (key == NULL) {
4451 _setSSLError(NULL, 0, __FILE__, __LINE__);
4452 return NULL;
4453 }
4454 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4455 EC_KEY_free(key);
4456 Py_RETURN_NONE;
4457}
Antoine Pitrou501da612011-12-21 09:27:41 +01004458#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004459
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004460#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004461static int
4462_servername_callback(SSL *s, int *al, void *args)
4463{
4464 int ret;
4465 PySSLContext *ssl_ctx = (PySSLContext *) args;
4466 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004467 PyObject *result;
4468 /* The high-level ssl.SSLSocket object */
4469 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004470 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004471 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004472
Christian Heimes11a14932018-02-24 02:35:08 +01004473 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004474 /* remove race condition in this the call back while if removing the
4475 * callback is in progress */
4476 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004477 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004478 }
4479
4480 ssl = SSL_get_app_data(s);
4481 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004482
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004483 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004484 * SSL connection and that has a .context attribute that can be changed to
4485 * identify the requested hostname. Since the official API is the Python
4486 * level API we want to pass the callback a Python level object rather than
4487 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4488 * SSLObject) that will be passed. Otherwise if there's a socket then that
4489 * will be passed. If both do not exist only then the C-level object is
4490 * passed. */
4491 if (ssl->owner)
4492 ssl_socket = PyWeakref_GetObject(ssl->owner);
4493 else if (ssl->Socket)
4494 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4495 else
4496 ssl_socket = (PyObject *) ssl;
4497
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004498 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004499 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004500 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004501
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004502 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004503 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004504 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004505 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004506 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004507 PyObject *servername_bytes;
4508 PyObject *servername_str;
4509
4510 servername_bytes = PyBytes_FromString(servername);
4511 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004512 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4513 goto error;
4514 }
Christian Heimes11a14932018-02-24 02:35:08 +01004515 /* server_hostname was encoded to an A-label by our caller; put it
4516 * back into a str object, but still as an A-label (bpo-28414)
4517 */
4518 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4519 Py_DECREF(servername_bytes);
4520 if (servername_str == NULL) {
4521 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004522 goto error;
4523 }
Christian Heimes11a14932018-02-24 02:35:08 +01004524 result = PyObject_CallFunctionObjArgs(
4525 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4526 ssl_ctx, NULL);
4527 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004528 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004529 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004530
4531 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004532 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004533 *al = SSL_AD_HANDSHAKE_FAILURE;
4534 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4535 }
4536 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004537 /* Result may be None, a SSLContext or an integer
4538 * None and SSLContext are OK, integer or other values are an error.
4539 */
4540 if (result == Py_None) {
4541 ret = SSL_TLSEXT_ERR_OK;
4542 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004543 *al = (int) PyLong_AsLong(result);
4544 if (PyErr_Occurred()) {
4545 PyErr_WriteUnraisable(result);
4546 *al = SSL_AD_INTERNAL_ERROR;
4547 }
4548 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4549 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004550 Py_DECREF(result);
4551 }
4552
4553 PyGILState_Release(gstate);
4554 return ret;
4555
4556error:
4557 Py_DECREF(ssl_socket);
4558 *al = SSL_AD_INTERNAL_ERROR;
4559 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4560 PyGILState_Release(gstate);
4561 return ret;
4562}
Antoine Pitroua5963382013-03-30 16:39:00 +01004563#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004564
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004565static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004566get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004567{
Christian Heimes11a14932018-02-24 02:35:08 +01004568 PyObject *cb = self->set_sni_cb;
4569 if (cb == NULL) {
4570 Py_RETURN_NONE;
4571 }
4572 Py_INCREF(cb);
4573 return cb;
4574}
4575
4576static int
4577set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4578{
4579 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4580 PyErr_SetString(PyExc_ValueError,
4581 "sni_callback cannot be set on TLS_CLIENT context");
4582 return -1;
4583 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004584#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004585 Py_CLEAR(self->set_sni_cb);
4586 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004587 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4588 }
4589 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004590 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004591 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4592 PyErr_SetString(PyExc_TypeError,
4593 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004594 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004595 }
Christian Heimes11a14932018-02-24 02:35:08 +01004596 Py_INCREF(arg);
4597 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004598 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4599 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4600 }
Christian Heimes11a14932018-02-24 02:35:08 +01004601 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004602#else
4603 PyErr_SetString(PyExc_NotImplementedError,
4604 "The TLS extension servername callback, "
4605 "SSL_CTX_set_tlsext_servername_callback, "
4606 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004607 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004608#endif
4609}
4610
Christian Heimes11a14932018-02-24 02:35:08 +01004611PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4612"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4613\n\
4614If the argument is None then the callback is disabled. The method is called\n\
4615with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4616See RFC 6066 for details of the SNI extension.");
4617
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004618/*[clinic input]
4619_ssl._SSLContext.cert_store_stats
4620
4621Returns quantities of loaded X.509 certificates.
4622
4623X.509 certificates with a CA extension and certificate revocation lists
4624inside the context's cert store.
4625
4626NOTE: Certificates in a capath directory aren't loaded unless they have
4627been used at least once.
4628[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004629
4630static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004631_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4632/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004633{
4634 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004635 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004636 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004637 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004638
4639 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004640 objs = X509_STORE_get0_objects(store);
4641 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4642 obj = sk_X509_OBJECT_value(objs, i);
4643 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004644 case X509_LU_X509:
4645 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004646 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004647 ca++;
4648 }
4649 break;
4650 case X509_LU_CRL:
4651 crl++;
4652 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004653 default:
4654 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4655 * As far as I can tell they are internal states and never
4656 * stored in a cert store */
4657 break;
4658 }
4659 }
4660 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4661 "x509_ca", ca);
4662}
4663
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664/*[clinic input]
4665_ssl._SSLContext.get_ca_certs
4666 binary_form: bool = False
4667
4668Returns a list of dicts with information of loaded CA certs.
4669
4670If the optional argument is True, returns a DER-encoded copy of the CA
4671certificate.
4672
4673NOTE: Certificates in a capath directory aren't loaded unless they have
4674been used at least once.
4675[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004676
4677static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004678_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4679/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004680{
4681 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004682 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004683 PyObject *ci = NULL, *rlist = NULL;
4684 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004685
4686 if ((rlist = PyList_New(0)) == NULL) {
4687 return NULL;
4688 }
4689
4690 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004691 objs = X509_STORE_get0_objects(store);
4692 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004693 X509_OBJECT *obj;
4694 X509 *cert;
4695
Christian Heimes598894f2016-09-05 23:19:05 +02004696 obj = sk_X509_OBJECT_value(objs, i);
4697 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004698 /* not a x509 cert */
4699 continue;
4700 }
4701 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004702 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004703 if (!X509_check_ca(cert)) {
4704 continue;
4705 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004706 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004707 ci = _certificate_to_der(cert);
4708 } else {
4709 ci = _decode_certificate(cert);
4710 }
4711 if (ci == NULL) {
4712 goto error;
4713 }
4714 if (PyList_Append(rlist, ci) == -1) {
4715 goto error;
4716 }
4717 Py_CLEAR(ci);
4718 }
4719 return rlist;
4720
4721 error:
4722 Py_XDECREF(ci);
4723 Py_XDECREF(rlist);
4724 return NULL;
4725}
4726
4727
Antoine Pitrou152efa22010-05-16 18:19:27 +00004728static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004729 {"check_hostname", (getter) get_check_hostname,
4730 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004731 {"_host_flags", (getter) get_host_flags,
4732 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004733#if SSL_CTRL_GET_MAX_PROTO_VERSION
4734 {"minimum_version", (getter) get_minimum_version,
4735 (setter) set_minimum_version, NULL},
4736 {"maximum_version", (getter) get_maximum_version,
4737 (setter) set_maximum_version, NULL},
4738#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004739#ifdef HAVE_OPENSSL_KEYLOG
4740 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4741 (setter) _PySSLContext_set_keylog_filename, NULL},
4742#endif
4743 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4744 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004745 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004746 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004747#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4748 {"num_tickets", (getter) get_num_tickets,
4749 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4750#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004751 {"options", (getter) get_options,
4752 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004753 {"post_handshake_auth", (getter) get_post_handshake_auth,
4754#ifdef TLS1_3_VERSION
4755 (setter) set_post_handshake_auth,
4756#else
4757 NULL,
4758#endif
4759 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004760 {"protocol", (getter) get_protocol,
4761 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004762 {"verify_flags", (getter) get_verify_flags,
4763 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004764 {"verify_mode", (getter) get_verify_mode,
4765 (setter) set_verify_mode, NULL},
4766 {NULL}, /* sentinel */
4767};
4768
4769static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004770 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4771 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4772 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4773 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4774 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4775 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4776 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4777 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4778 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4779 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4780 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004781 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4782 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004783 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004784 {NULL, NULL} /* sentinel */
4785};
4786
4787static PyTypeObject PySSLContext_Type = {
4788 PyVarObject_HEAD_INIT(NULL, 0)
4789 "_ssl._SSLContext", /*tp_name*/
4790 sizeof(PySSLContext), /*tp_basicsize*/
4791 0, /*tp_itemsize*/
4792 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004793 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004794 0, /*tp_getattr*/
4795 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004796 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004797 0, /*tp_repr*/
4798 0, /*tp_as_number*/
4799 0, /*tp_as_sequence*/
4800 0, /*tp_as_mapping*/
4801 0, /*tp_hash*/
4802 0, /*tp_call*/
4803 0, /*tp_str*/
4804 0, /*tp_getattro*/
4805 0, /*tp_setattro*/
4806 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004807 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004808 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004809 (traverseproc) context_traverse, /*tp_traverse*/
4810 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004811 0, /*tp_richcompare*/
4812 0, /*tp_weaklistoffset*/
4813 0, /*tp_iter*/
4814 0, /*tp_iternext*/
4815 context_methods, /*tp_methods*/
4816 0, /*tp_members*/
4817 context_getsetlist, /*tp_getset*/
4818 0, /*tp_base*/
4819 0, /*tp_dict*/
4820 0, /*tp_descr_get*/
4821 0, /*tp_descr_set*/
4822 0, /*tp_dictoffset*/
4823 0, /*tp_init*/
4824 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004825 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004826};
4827
4828
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004829/*
4830 * MemoryBIO objects
4831 */
4832
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004833/*[clinic input]
4834@classmethod
4835_ssl.MemoryBIO.__new__
4836
4837[clinic start generated code]*/
4838
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004839static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004840_ssl_MemoryBIO_impl(PyTypeObject *type)
4841/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004842{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004843 BIO *bio;
4844 PySSLMemoryBIO *self;
4845
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004846 bio = BIO_new(BIO_s_mem());
4847 if (bio == NULL) {
4848 PyErr_SetString(PySSLErrorObject,
4849 "failed to allocate BIO");
4850 return NULL;
4851 }
4852 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4853 * just that no data is currently available. The SSL routines should retry
4854 * the read, which we can achieve by calling BIO_set_retry_read(). */
4855 BIO_set_retry_read(bio);
4856 BIO_set_mem_eof_return(bio, -1);
4857
4858 assert(type != NULL && type->tp_alloc != NULL);
4859 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4860 if (self == NULL) {
4861 BIO_free(bio);
4862 return NULL;
4863 }
4864 self->bio = bio;
4865 self->eof_written = 0;
4866
4867 return (PyObject *) self;
4868}
4869
4870static void
4871memory_bio_dealloc(PySSLMemoryBIO *self)
4872{
4873 BIO_free(self->bio);
4874 Py_TYPE(self)->tp_free(self);
4875}
4876
4877static PyObject *
4878memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4879{
Segev Finer5cff6372017-07-27 01:19:17 +03004880 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004881}
4882
4883PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4884"The number of bytes pending in the memory BIO.");
4885
4886static PyObject *
4887memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4888{
4889 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4890 && self->eof_written);
4891}
4892
4893PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4894"Whether the memory BIO is at EOF.");
4895
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004896/*[clinic input]
4897_ssl.MemoryBIO.read
4898 size as len: int = -1
4899 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004900
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004901Read up to size bytes from the memory BIO.
4902
4903If size is not specified, read the entire buffer.
4904If the return value is an empty bytes instance, this means either
4905EOF or that no data is available. Use the "eof" property to
4906distinguish between the two.
4907[clinic start generated code]*/
4908
4909static PyObject *
4910_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4911/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4912{
4913 int avail, nbytes;
4914 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004915
Segev Finer5cff6372017-07-27 01:19:17 +03004916 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004917 if ((len < 0) || (len > avail))
4918 len = avail;
4919
4920 result = PyBytes_FromStringAndSize(NULL, len);
4921 if ((result == NULL) || (len == 0))
4922 return result;
4923
4924 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004925 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004926 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004927 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004928 return NULL;
4929 }
4930
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004931 /* There should never be any short reads but check anyway. */
4932 if (nbytes < len) {
4933 _PyBytes_Resize(&result, nbytes);
4934 }
4935
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004936 return result;
4937}
4938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004939/*[clinic input]
4940_ssl.MemoryBIO.write
4941 b: Py_buffer
4942 /
4943
4944Writes the bytes b into the memory BIO.
4945
4946Returns the number of bytes written.
4947[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004948
4949static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004950_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4951/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004952{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004953 int nbytes;
4954
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004955 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004956 PyErr_Format(PyExc_OverflowError,
4957 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004958 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004959 }
4960
4961 if (self->eof_written) {
4962 PyErr_SetString(PySSLErrorObject,
4963 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004964 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004965 }
4966
Segev Finer5cff6372017-07-27 01:19:17 +03004967 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004968 if (nbytes < 0) {
4969 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004970 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971 }
4972
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004973 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004974}
4975
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004976/*[clinic input]
4977_ssl.MemoryBIO.write_eof
4978
4979Write an EOF marker to the memory BIO.
4980
4981When all data has been read, the "eof" property will be True.
4982[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004983
4984static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004985_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4986/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004987{
4988 self->eof_written = 1;
4989 /* After an EOF is written, a zero return from read() should be a real EOF
4990 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4991 BIO_clear_retry_flags(self->bio);
4992 BIO_set_mem_eof_return(self->bio, 0);
4993
4994 Py_RETURN_NONE;
4995}
4996
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004997static PyGetSetDef memory_bio_getsetlist[] = {
4998 {"pending", (getter) memory_bio_get_pending, NULL,
4999 PySSL_memory_bio_pending_doc},
5000 {"eof", (getter) memory_bio_get_eof, NULL,
5001 PySSL_memory_bio_eof_doc},
5002 {NULL}, /* sentinel */
5003};
5004
5005static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005006 _SSL_MEMORYBIO_READ_METHODDEF
5007 _SSL_MEMORYBIO_WRITE_METHODDEF
5008 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005009 {NULL, NULL} /* sentinel */
5010};
5011
5012static PyTypeObject PySSLMemoryBIO_Type = {
5013 PyVarObject_HEAD_INIT(NULL, 0)
5014 "_ssl.MemoryBIO", /*tp_name*/
5015 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5016 0, /*tp_itemsize*/
5017 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005018 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005019 0, /*tp_getattr*/
5020 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005021 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005022 0, /*tp_repr*/
5023 0, /*tp_as_number*/
5024 0, /*tp_as_sequence*/
5025 0, /*tp_as_mapping*/
5026 0, /*tp_hash*/
5027 0, /*tp_call*/
5028 0, /*tp_str*/
5029 0, /*tp_getattro*/
5030 0, /*tp_setattro*/
5031 0, /*tp_as_buffer*/
5032 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5033 0, /*tp_doc*/
5034 0, /*tp_traverse*/
5035 0, /*tp_clear*/
5036 0, /*tp_richcompare*/
5037 0, /*tp_weaklistoffset*/
5038 0, /*tp_iter*/
5039 0, /*tp_iternext*/
5040 memory_bio_methods, /*tp_methods*/
5041 0, /*tp_members*/
5042 memory_bio_getsetlist, /*tp_getset*/
5043 0, /*tp_base*/
5044 0, /*tp_dict*/
5045 0, /*tp_descr_get*/
5046 0, /*tp_descr_set*/
5047 0, /*tp_dictoffset*/
5048 0, /*tp_init*/
5049 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005051};
5052
Antoine Pitrou152efa22010-05-16 18:19:27 +00005053
Christian Heimes99a65702016-09-10 23:44:53 +02005054/*
5055 * SSL Session object
5056 */
5057
5058static void
5059PySSLSession_dealloc(PySSLSession *self)
5060{
INADA Naokia6296d32017-08-24 14:55:17 +09005061 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005062 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005063 Py_XDECREF(self->ctx);
5064 if (self->session != NULL) {
5065 SSL_SESSION_free(self->session);
5066 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005067 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005068}
5069
5070static PyObject *
5071PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5072{
5073 int result;
5074
5075 if (left == NULL || right == NULL) {
5076 PyErr_BadInternalCall();
5077 return NULL;
5078 }
5079
5080 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5081 Py_RETURN_NOTIMPLEMENTED;
5082 }
5083
5084 if (left == right) {
5085 result = 0;
5086 } else {
5087 const unsigned char *left_id, *right_id;
5088 unsigned int left_len, right_len;
5089 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5090 &left_len);
5091 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5092 &right_len);
5093 if (left_len == right_len) {
5094 result = memcmp(left_id, right_id, left_len);
5095 } else {
5096 result = 1;
5097 }
5098 }
5099
5100 switch (op) {
5101 case Py_EQ:
5102 if (result == 0) {
5103 Py_RETURN_TRUE;
5104 } else {
5105 Py_RETURN_FALSE;
5106 }
5107 break;
5108 case Py_NE:
5109 if (result != 0) {
5110 Py_RETURN_TRUE;
5111 } else {
5112 Py_RETURN_FALSE;
5113 }
5114 break;
5115 case Py_LT:
5116 case Py_LE:
5117 case Py_GT:
5118 case Py_GE:
5119 Py_RETURN_NOTIMPLEMENTED;
5120 break;
5121 default:
5122 PyErr_BadArgument();
5123 return NULL;
5124 }
5125}
5126
5127static int
5128PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5129{
5130 Py_VISIT(self->ctx);
5131 return 0;
5132}
5133
5134static int
5135PySSLSession_clear(PySSLSession *self)
5136{
5137 Py_CLEAR(self->ctx);
5138 return 0;
5139}
5140
5141
5142static PyObject *
5143PySSLSession_get_time(PySSLSession *self, void *closure) {
5144 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5145}
5146
5147PyDoc_STRVAR(PySSLSession_get_time_doc,
5148"Session creation time (seconds since epoch).");
5149
5150
5151static PyObject *
5152PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5153 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5154}
5155
5156PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5157"Session timeout (delta in seconds).");
5158
5159
5160static PyObject *
5161PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5162 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5163 return PyLong_FromUnsignedLong(hint);
5164}
5165
5166PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5167"Ticket life time hint.");
5168
5169
5170static PyObject *
5171PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5172 const unsigned char *id;
5173 unsigned int len;
5174 id = SSL_SESSION_get_id(self->session, &len);
5175 return PyBytes_FromStringAndSize((const char *)id, len);
5176}
5177
5178PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5179"Session id");
5180
5181
5182static PyObject *
5183PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5184 if (SSL_SESSION_has_ticket(self->session)) {
5185 Py_RETURN_TRUE;
5186 } else {
5187 Py_RETURN_FALSE;
5188 }
5189}
5190
5191PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5192"Does the session contain a ticket?");
5193
5194
5195static PyGetSetDef PySSLSession_getsetlist[] = {
5196 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5197 PySSLSession_get_has_ticket_doc},
5198 {"id", (getter) PySSLSession_get_session_id, NULL,
5199 PySSLSession_get_session_id_doc},
5200 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5201 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5202 {"time", (getter) PySSLSession_get_time, NULL,
5203 PySSLSession_get_time_doc},
5204 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5205 PySSLSession_get_timeout_doc},
5206 {NULL}, /* sentinel */
5207};
5208
5209static PyTypeObject PySSLSession_Type = {
5210 PyVarObject_HEAD_INIT(NULL, 0)
5211 "_ssl.Session", /*tp_name*/
5212 sizeof(PySSLSession), /*tp_basicsize*/
5213 0, /*tp_itemsize*/
5214 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005215 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005216 0, /*tp_getattr*/
5217 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005218 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005219 0, /*tp_repr*/
5220 0, /*tp_as_number*/
5221 0, /*tp_as_sequence*/
5222 0, /*tp_as_mapping*/
5223 0, /*tp_hash*/
5224 0, /*tp_call*/
5225 0, /*tp_str*/
5226 0, /*tp_getattro*/
5227 0, /*tp_setattro*/
5228 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005229 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005230 0, /*tp_doc*/
5231 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5232 (inquiry)PySSLSession_clear, /*tp_clear*/
5233 PySSLSession_richcompare, /*tp_richcompare*/
5234 0, /*tp_weaklistoffset*/
5235 0, /*tp_iter*/
5236 0, /*tp_iternext*/
5237 0, /*tp_methods*/
5238 0, /*tp_members*/
5239 PySSLSession_getsetlist, /*tp_getset*/
5240};
5241
5242
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005243/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005244/*[clinic input]
5245_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005246 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005247 entropy: double
5248 /
5249
5250Mix string into the OpenSSL PRNG state.
5251
5252entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305253string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005254[clinic start generated code]*/
5255
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005256static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005257_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005258/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005259{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005260 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005261 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005262
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005263 buf = (const char *)view->buf;
5264 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005265 do {
5266 written = Py_MIN(len, INT_MAX);
5267 RAND_add(buf, (int)written, entropy);
5268 buf += written;
5269 len -= written;
5270 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005271 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005272}
5273
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005274static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005275PySSL_RAND(int len, int pseudo)
5276{
5277 int ok;
5278 PyObject *bytes;
5279 unsigned long err;
5280 const char *errstr;
5281 PyObject *v;
5282
Victor Stinner1e81a392013-12-19 16:47:04 +01005283 if (len < 0) {
5284 PyErr_SetString(PyExc_ValueError, "num must be positive");
5285 return NULL;
5286 }
5287
Victor Stinner99c8b162011-05-24 12:05:19 +02005288 bytes = PyBytes_FromStringAndSize(NULL, len);
5289 if (bytes == NULL)
5290 return NULL;
5291 if (pseudo) {
5292 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5293 if (ok == 0 || ok == 1)
5294 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5295 }
5296 else {
5297 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5298 if (ok == 1)
5299 return bytes;
5300 }
5301 Py_DECREF(bytes);
5302
5303 err = ERR_get_error();
5304 errstr = ERR_reason_error_string(err);
5305 v = Py_BuildValue("(ks)", err, errstr);
5306 if (v != NULL) {
5307 PyErr_SetObject(PySSLErrorObject, v);
5308 Py_DECREF(v);
5309 }
5310 return NULL;
5311}
5312
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005313/*[clinic input]
5314_ssl.RAND_bytes
5315 n: int
5316 /
5317
5318Generate n cryptographically strong pseudo-random bytes.
5319[clinic start generated code]*/
5320
Victor Stinner99c8b162011-05-24 12:05:19 +02005321static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005322_ssl_RAND_bytes_impl(PyObject *module, int n)
5323/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005324{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005325 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005326}
5327
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005328/*[clinic input]
5329_ssl.RAND_pseudo_bytes
5330 n: int
5331 /
5332
5333Generate n pseudo-random bytes.
5334
5335Return a pair (bytes, is_cryptographic). is_cryptographic is True
5336if the bytes generated are cryptographically strong.
5337[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005338
5339static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005340_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5341/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005342{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005343 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005344}
5345
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005346/*[clinic input]
5347_ssl.RAND_status
5348
5349Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5350
5351It is necessary to seed the PRNG with RAND_add() on some platforms before
5352using the ssl() function.
5353[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005354
5355static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005356_ssl_RAND_status_impl(PyObject *module)
5357/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005358{
Christian Heimes217cfd12007-12-02 14:31:20 +00005359 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005360}
5361
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005362#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005363/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005364/*[clinic input]
5365_ssl.RAND_egd
5366 path: object(converter="PyUnicode_FSConverter")
5367 /
5368
5369Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5370
5371Returns number of bytes read. Raises SSLError if connection to EGD
5372fails or if it does not provide enough data to seed PRNG.
5373[clinic start generated code]*/
5374
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005375static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005376_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5377/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005378{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005379 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005380 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005381 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005382 PyErr_SetString(PySSLErrorObject,
5383 "EGD connection failed or EGD did not return "
5384 "enough data to seed the PRNG");
5385 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005386 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005387 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005388}
Christian Heimesa5d07652016-09-24 10:48:05 +02005389/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005390#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005391
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005392
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005393
5394/*[clinic input]
5395_ssl.get_default_verify_paths
5396
5397Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5398
5399The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5400[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005401
5402static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005403_ssl_get_default_verify_paths_impl(PyObject *module)
5404/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005405{
5406 PyObject *ofile_env = NULL;
5407 PyObject *ofile = NULL;
5408 PyObject *odir_env = NULL;
5409 PyObject *odir = NULL;
5410
Benjamin Petersond113c962015-07-18 10:59:13 -07005411#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005412 const char *tmp = (info); \
5413 target = NULL; \
5414 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5415 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5416 target = PyBytes_FromString(tmp); } \
5417 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005418 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005419
Benjamin Petersond113c962015-07-18 10:59:13 -07005420 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5421 CONVERT(X509_get_default_cert_file(), ofile);
5422 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5423 CONVERT(X509_get_default_cert_dir(), odir);
5424#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005425
Christian Heimes200bb1b2013-06-14 15:14:29 +02005426 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005427
5428 error:
5429 Py_XDECREF(ofile_env);
5430 Py_XDECREF(ofile);
5431 Py_XDECREF(odir_env);
5432 Py_XDECREF(odir);
5433 return NULL;
5434}
5435
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005436static PyObject*
5437asn1obj2py(ASN1_OBJECT *obj)
5438{
5439 int nid;
5440 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005441
5442 nid = OBJ_obj2nid(obj);
5443 if (nid == NID_undef) {
5444 PyErr_Format(PyExc_ValueError, "Unknown object");
5445 return NULL;
5446 }
5447 sn = OBJ_nid2sn(nid);
5448 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005449 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005450}
5451
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005452/*[clinic input]
5453_ssl.txt2obj
5454 txt: str
5455 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005456
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005457Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5458
5459By default objects are looked up by OID. With name=True short and
5460long name are also matched.
5461[clinic start generated code]*/
5462
5463static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005464_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5465/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005466{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005467 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005468 ASN1_OBJECT *obj;
5469
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005470 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5471 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005472 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005473 return NULL;
5474 }
5475 result = asn1obj2py(obj);
5476 ASN1_OBJECT_free(obj);
5477 return result;
5478}
5479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005480/*[clinic input]
5481_ssl.nid2obj
5482 nid: int
5483 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005485Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5486[clinic start generated code]*/
5487
5488static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005489_ssl_nid2obj_impl(PyObject *module, int nid)
5490/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005491{
5492 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005493 ASN1_OBJECT *obj;
5494
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005495 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005496 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005497 return NULL;
5498 }
5499 obj = OBJ_nid2obj(nid);
5500 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005501 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005502 return NULL;
5503 }
5504 result = asn1obj2py(obj);
5505 ASN1_OBJECT_free(obj);
5506 return result;
5507}
5508
Christian Heimes46bebee2013-06-09 19:03:31 +02005509#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005510
5511static PyObject*
5512certEncodingType(DWORD encodingType)
5513{
5514 static PyObject *x509_asn = NULL;
5515 static PyObject *pkcs_7_asn = NULL;
5516
5517 if (x509_asn == NULL) {
5518 x509_asn = PyUnicode_InternFromString("x509_asn");
5519 if (x509_asn == NULL)
5520 return NULL;
5521 }
5522 if (pkcs_7_asn == NULL) {
5523 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5524 if (pkcs_7_asn == NULL)
5525 return NULL;
5526 }
5527 switch(encodingType) {
5528 case X509_ASN_ENCODING:
5529 Py_INCREF(x509_asn);
5530 return x509_asn;
5531 case PKCS_7_ASN_ENCODING:
5532 Py_INCREF(pkcs_7_asn);
5533 return pkcs_7_asn;
5534 default:
5535 return PyLong_FromLong(encodingType);
5536 }
5537}
5538
5539static PyObject*
5540parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5541{
5542 CERT_ENHKEY_USAGE *usage;
5543 DWORD size, error, i;
5544 PyObject *retval;
5545
5546 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5547 error = GetLastError();
5548 if (error == CRYPT_E_NOT_FOUND) {
5549 Py_RETURN_TRUE;
5550 }
5551 return PyErr_SetFromWindowsErr(error);
5552 }
5553
5554 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5555 if (usage == NULL) {
5556 return PyErr_NoMemory();
5557 }
5558
5559 /* Now get the actual enhanced usage property */
5560 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5561 PyMem_Free(usage);
5562 error = GetLastError();
5563 if (error == CRYPT_E_NOT_FOUND) {
5564 Py_RETURN_TRUE;
5565 }
5566 return PyErr_SetFromWindowsErr(error);
5567 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005568 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005569 if (retval == NULL) {
5570 goto error;
5571 }
5572 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5573 if (usage->rgpszUsageIdentifier[i]) {
5574 PyObject *oid;
5575 int err;
5576 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5577 if (oid == NULL) {
5578 Py_CLEAR(retval);
5579 goto error;
5580 }
5581 err = PySet_Add(retval, oid);
5582 Py_DECREF(oid);
5583 if (err == -1) {
5584 Py_CLEAR(retval);
5585 goto error;
5586 }
5587 }
5588 }
5589 error:
5590 PyMem_Free(usage);
5591 return retval;
5592}
5593
kctherookied93fbbf2019-03-29 00:59:06 +07005594static HCERTSTORE
5595ssl_collect_certificates(const char *store_name)
5596{
5597/* this function collects the system certificate stores listed in
5598 * system_stores into a collection certificate store for being
5599 * enumerated. The store must be readable to be added to the
5600 * store collection.
5601 */
5602
5603 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5604 static DWORD system_stores[] = {
5605 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5606 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5607 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5608 CERT_SYSTEM_STORE_CURRENT_USER,
5609 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5610 CERT_SYSTEM_STORE_SERVICES,
5611 CERT_SYSTEM_STORE_USERS};
5612 size_t i, storesAdded;
5613 BOOL result;
5614
5615 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5616 (HCRYPTPROV)NULL, 0, NULL);
5617 if (!hCollectionStore) {
5618 return NULL;
5619 }
5620 storesAdded = 0;
5621 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5622 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5623 (HCRYPTPROV)NULL,
5624 CERT_STORE_READONLY_FLAG |
5625 system_stores[i], store_name);
5626 if (hSystemStore) {
5627 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5628 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5629 if (result) {
5630 ++storesAdded;
5631 }
neoneneed701292019-09-09 21:33:43 +09005632 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005633 }
5634 }
5635 if (storesAdded == 0) {
5636 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5637 return NULL;
5638 }
5639
5640 return hCollectionStore;
5641}
5642
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005643/*[clinic input]
5644_ssl.enum_certificates
5645 store_name: str
5646
5647Retrieve certificates from Windows' cert store.
5648
5649store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5650more cert storages, too. The function returns a list of (bytes,
5651encoding_type, trust) tuples. The encoding_type flag can be interpreted
5652with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5653a set of OIDs or the boolean True.
5654[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005655
Christian Heimes46bebee2013-06-09 19:03:31 +02005656static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005657_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5658/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005659{
kctherookied93fbbf2019-03-29 00:59:06 +07005660 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005661 PCCERT_CONTEXT pCertCtx = NULL;
5662 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005663 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005664
Christian Heimes915cd3f2019-09-09 18:06:55 +02005665 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005666 if (result == NULL) {
5667 return NULL;
5668 }
kctherookied93fbbf2019-03-29 00:59:06 +07005669 hCollectionStore = ssl_collect_certificates(store_name);
5670 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005671 Py_DECREF(result);
5672 return PyErr_SetFromWindowsErr(GetLastError());
5673 }
5674
kctherookied93fbbf2019-03-29 00:59:06 +07005675 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005676 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5677 pCertCtx->cbCertEncoded);
5678 if (!cert) {
5679 Py_CLEAR(result);
5680 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005681 }
Christian Heimes44109d72013-11-22 01:51:30 +01005682 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5683 Py_CLEAR(result);
5684 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005685 }
Christian Heimes44109d72013-11-22 01:51:30 +01005686 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5687 if (keyusage == Py_True) {
5688 Py_DECREF(keyusage);
5689 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005690 }
Christian Heimes44109d72013-11-22 01:51:30 +01005691 if (keyusage == NULL) {
5692 Py_CLEAR(result);
5693 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005694 }
Christian Heimes44109d72013-11-22 01:51:30 +01005695 if ((tup = PyTuple_New(3)) == NULL) {
5696 Py_CLEAR(result);
5697 break;
5698 }
5699 PyTuple_SET_ITEM(tup, 0, cert);
5700 cert = NULL;
5701 PyTuple_SET_ITEM(tup, 1, enc);
5702 enc = NULL;
5703 PyTuple_SET_ITEM(tup, 2, keyusage);
5704 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005705 if (PySet_Add(result, tup) == -1) {
5706 Py_CLEAR(result);
5707 Py_CLEAR(tup);
5708 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005709 }
5710 Py_CLEAR(tup);
5711 }
5712 if (pCertCtx) {
5713 /* loop ended with an error, need to clean up context manually */
5714 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005715 }
5716
5717 /* In error cases cert, enc and tup may not be NULL */
5718 Py_XDECREF(cert);
5719 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005720 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005721 Py_XDECREF(tup);
5722
kctherookied93fbbf2019-03-29 00:59:06 +07005723 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5724 associated with the store, in this case our collection store and the
5725 associated system stores. */
5726 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005727 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005728 Py_XDECREF(result);
5729 return PyErr_SetFromWindowsErr(GetLastError());
5730 }
kctherookied93fbbf2019-03-29 00:59:06 +07005731
Christian Heimes915cd3f2019-09-09 18:06:55 +02005732 /* convert set to list */
5733 if (result == NULL) {
5734 return NULL;
5735 } else {
5736 PyObject *lst = PySequence_List(result);
5737 Py_DECREF(result);
5738 return lst;
5739 }
Christian Heimes44109d72013-11-22 01:51:30 +01005740}
5741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005742/*[clinic input]
5743_ssl.enum_crls
5744 store_name: str
5745
5746Retrieve CRLs from Windows' cert store.
5747
5748store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5749more cert storages, too. The function returns a list of (bytes,
5750encoding_type) tuples. The encoding_type flag can be interpreted with
5751X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5752[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005753
5754static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005755_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5756/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005757{
kctherookied93fbbf2019-03-29 00:59:06 +07005758 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005759 PCCRL_CONTEXT pCrlCtx = NULL;
5760 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5761 PyObject *result = NULL;
5762
Christian Heimes915cd3f2019-09-09 18:06:55 +02005763 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005764 if (result == NULL) {
5765 return NULL;
5766 }
kctherookied93fbbf2019-03-29 00:59:06 +07005767 hCollectionStore = ssl_collect_certificates(store_name);
5768 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005769 Py_DECREF(result);
5770 return PyErr_SetFromWindowsErr(GetLastError());
5771 }
Christian Heimes44109d72013-11-22 01:51:30 +01005772
kctherookied93fbbf2019-03-29 00:59:06 +07005773 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005774 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5775 pCrlCtx->cbCrlEncoded);
5776 if (!crl) {
5777 Py_CLEAR(result);
5778 break;
5779 }
5780 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5781 Py_CLEAR(result);
5782 break;
5783 }
5784 if ((tup = PyTuple_New(2)) == NULL) {
5785 Py_CLEAR(result);
5786 break;
5787 }
5788 PyTuple_SET_ITEM(tup, 0, crl);
5789 crl = NULL;
5790 PyTuple_SET_ITEM(tup, 1, enc);
5791 enc = NULL;
5792
Christian Heimes915cd3f2019-09-09 18:06:55 +02005793 if (PySet_Add(result, tup) == -1) {
5794 Py_CLEAR(result);
5795 Py_CLEAR(tup);
5796 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005797 }
5798 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005799 }
Christian Heimes44109d72013-11-22 01:51:30 +01005800 if (pCrlCtx) {
5801 /* loop ended with an error, need to clean up context manually */
5802 CertFreeCRLContext(pCrlCtx);
5803 }
5804
5805 /* In error cases cert, enc and tup may not be NULL */
5806 Py_XDECREF(crl);
5807 Py_XDECREF(enc);
5808 Py_XDECREF(tup);
5809
kctherookied93fbbf2019-03-29 00:59:06 +07005810 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5811 associated with the store, in this case our collection store and the
5812 associated system stores. */
5813 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005814 /* This error case might shadow another exception.*/
5815 Py_XDECREF(result);
5816 return PyErr_SetFromWindowsErr(GetLastError());
5817 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005818 /* convert set to list */
5819 if (result == NULL) {
5820 return NULL;
5821 } else {
5822 PyObject *lst = PySequence_List(result);
5823 Py_DECREF(result);
5824 return lst;
5825 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005826}
Christian Heimes44109d72013-11-22 01:51:30 +01005827
5828#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005829
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005830/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005831static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005832 _SSL__TEST_DECODE_CERT_METHODDEF
5833 _SSL_RAND_ADD_METHODDEF
5834 _SSL_RAND_BYTES_METHODDEF
5835 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5836 _SSL_RAND_EGD_METHODDEF
5837 _SSL_RAND_STATUS_METHODDEF
5838 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5839 _SSL_ENUM_CERTIFICATES_METHODDEF
5840 _SSL_ENUM_CRLS_METHODDEF
5841 _SSL_TXT2OBJ_METHODDEF
5842 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005843 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005844};
5845
5846
Christian Heimes598894f2016-09-05 23:19:05 +02005847#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005848
5849/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005850 * of the Python C thread library
5851 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5852 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005853
5854static PyThread_type_lock *_ssl_locks = NULL;
5855
Christian Heimes4d98ca92013-08-19 17:36:29 +02005856#if OPENSSL_VERSION_NUMBER >= 0x10000000
5857/* use new CRYPTO_THREADID API. */
5858static void
5859_ssl_threadid_callback(CRYPTO_THREADID *id)
5860{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005861 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005862}
5863#else
5864/* deprecated CRYPTO_set_id_callback() API. */
5865static unsigned long
5866_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005867 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005868}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005869#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005870
Bill Janssen6e027db2007-11-15 22:23:56 +00005871static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005872 (int mode, int n, const char *file, int line) {
5873 /* this function is needed to perform locking on shared data
5874 structures. (Note that OpenSSL uses a number of global data
5875 structures that will be implicitly shared whenever multiple
5876 threads use OpenSSL.) Multi-threaded applications will
5877 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 locking_function() must be able to handle up to
5880 CRYPTO_num_locks() different mutex locks. It sets the n-th
5881 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005882
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005883 file and line are the file number of the function setting the
5884 lock. They can be useful for debugging.
5885 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005886
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005887 if ((_ssl_locks == NULL) ||
5888 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5889 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005891 if (mode & CRYPTO_LOCK) {
5892 PyThread_acquire_lock(_ssl_locks[n], 1);
5893 } else {
5894 PyThread_release_lock(_ssl_locks[n]);
5895 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005896}
5897
5898static int _setup_ssl_threads(void) {
5899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005900 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005901
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005902 if (_ssl_locks == NULL) {
5903 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005904 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5905 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005906 if (_ssl_locks == NULL) {
5907 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005908 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005909 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005910 for (i = 0; i < _ssl_locks_count; i++) {
5911 _ssl_locks[i] = PyThread_allocate_lock();
5912 if (_ssl_locks[i] == NULL) {
5913 unsigned int j;
5914 for (j = 0; j < i; j++) {
5915 PyThread_free_lock(_ssl_locks[j]);
5916 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005917 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005918 return 0;
5919 }
5920 }
5921 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005922#if OPENSSL_VERSION_NUMBER >= 0x10000000
5923 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5924#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005925 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005926#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005927 }
5928 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929}
5930
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005931#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005932
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005933PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005934"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005935for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005936
Martin v. Löwis1a214512008-06-11 05:26:20 +00005937
5938static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005939 PyModuleDef_HEAD_INIT,
5940 "_ssl",
5941 module_doc,
5942 -1,
5943 PySSL_methods,
5944 NULL,
5945 NULL,
5946 NULL,
5947 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005948};
5949
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005950
5951static void
5952parse_openssl_version(unsigned long libver,
5953 unsigned int *major, unsigned int *minor,
5954 unsigned int *fix, unsigned int *patch,
5955 unsigned int *status)
5956{
5957 *status = libver & 0xF;
5958 libver >>= 4;
5959 *patch = libver & 0xFF;
5960 libver >>= 8;
5961 *fix = libver & 0xFF;
5962 libver >>= 8;
5963 *minor = libver & 0xFF;
5964 libver >>= 8;
5965 *major = libver & 0xFF;
5966}
5967
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005968PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005969PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005970{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005971 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005972 unsigned long libver;
5973 unsigned int major, minor, fix, patch, status;
5974 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005975 struct py_ssl_error_code *errcode;
5976 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005977
Antoine Pitrou152efa22010-05-16 18:19:27 +00005978 if (PyType_Ready(&PySSLContext_Type) < 0)
5979 return NULL;
5980 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005981 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005982 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5983 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005984 if (PyType_Ready(&PySSLSession_Type) < 0)
5985 return NULL;
5986
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005988 m = PyModule_Create(&_sslmodule);
5989 if (m == NULL)
5990 return NULL;
5991 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005992
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005993 /* Load _socket module and its C API */
5994 socket_api = PySocketModule_ImportModuleAndAPI();
5995 if (!socket_api)
5996 return NULL;
5997 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005998
Christian Heimesc941e622017-09-05 15:47:11 +02005999#ifndef OPENSSL_VERSION_1_1
6000 /* Load all algorithms and initialize cpuid */
6001 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006002 /* Init OpenSSL */
6003 SSL_load_error_strings();
6004 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006005#endif
6006
Christian Heimes598894f2016-09-05 23:19:05 +02006007#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006008 /* note that this will start threading if not already started */
6009 if (!_setup_ssl_threads()) {
6010 return NULL;
6011 }
Christian Heimesc087a262020-05-15 20:55:25 +02006012#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006013 /* OpenSSL 1.1.0 builtin thread support is enabled */
6014 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006015#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006016
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006017 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006018 sslerror_type_slots[0].pfunc = PyExc_OSError;
6019 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006020 if (PySSLErrorObject == NULL)
6021 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006022
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006023 /* ssl.CertificateError used to be a subclass of ValueError */
6024 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6025 if (bases == NULL)
6026 return NULL;
6027 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6028 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6029 bases, NULL);
6030 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006031 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6032 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6033 PySSLErrorObject, NULL);
6034 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6035 "ssl.SSLWantReadError", SSLWantReadError_doc,
6036 PySSLErrorObject, NULL);
6037 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6038 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6039 PySSLErrorObject, NULL);
6040 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6041 "ssl.SSLSyscallError", SSLSyscallError_doc,
6042 PySSLErrorObject, NULL);
6043 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6044 "ssl.SSLEOFError", SSLEOFError_doc,
6045 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006046 if (PySSLCertVerificationErrorObject == NULL
6047 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006048 || PySSLWantReadErrorObject == NULL
6049 || PySSLWantWriteErrorObject == NULL
6050 || PySSLSyscallErrorObject == NULL
6051 || PySSLEOFErrorObject == NULL)
6052 return NULL;
6053 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006054 || PyDict_SetItemString(d, "SSLCertVerificationError",
6055 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006056 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6057 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6058 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6059 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6060 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006061 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006062 if (PyDict_SetItemString(d, "_SSLContext",
6063 (PyObject *)&PySSLContext_Type) != 0)
6064 return NULL;
6065 if (PyDict_SetItemString(d, "_SSLSocket",
6066 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006067 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006068 if (PyDict_SetItemString(d, "MemoryBIO",
6069 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6070 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006071 if (PyDict_SetItemString(d, "SSLSession",
6072 (PyObject *)&PySSLSession_Type) != 0)
6073 return NULL;
6074
Christian Heimes892d66e2018-01-29 14:10:18 +01006075 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6076 PY_SSL_DEFAULT_CIPHER_STRING);
6077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006078 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6079 PY_SSL_ERROR_ZERO_RETURN);
6080 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6081 PY_SSL_ERROR_WANT_READ);
6082 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6083 PY_SSL_ERROR_WANT_WRITE);
6084 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6085 PY_SSL_ERROR_WANT_X509_LOOKUP);
6086 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6087 PY_SSL_ERROR_SYSCALL);
6088 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6089 PY_SSL_ERROR_SSL);
6090 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6091 PY_SSL_ERROR_WANT_CONNECT);
6092 /* non ssl.h errorcodes */
6093 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6094 PY_SSL_ERROR_EOF);
6095 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6096 PY_SSL_ERROR_INVALID_ERROR_CODE);
6097 /* cert requirements */
6098 PyModule_AddIntConstant(m, "CERT_NONE",
6099 PY_SSL_CERT_NONE);
6100 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6101 PY_SSL_CERT_OPTIONAL);
6102 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6103 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006104 /* CRL verification for verification_flags */
6105 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6106 0);
6107 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6108 X509_V_FLAG_CRL_CHECK);
6109 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6110 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6111 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6112 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006113#ifdef X509_V_FLAG_TRUSTED_FIRST
6114 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6115 X509_V_FLAG_TRUSTED_FIRST);
6116#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006117
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006118 /* Alert Descriptions from ssl.h */
6119 /* note RESERVED constants no longer intended for use have been removed */
6120 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6121
6122#define ADD_AD_CONSTANT(s) \
6123 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6124 SSL_AD_##s)
6125
6126 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6127 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6128 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6129 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6130 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6131 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6132 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6133 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6134 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6135 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6136 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6137 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6138 ADD_AD_CONSTANT(UNKNOWN_CA);
6139 ADD_AD_CONSTANT(ACCESS_DENIED);
6140 ADD_AD_CONSTANT(DECODE_ERROR);
6141 ADD_AD_CONSTANT(DECRYPT_ERROR);
6142 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6143 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6144 ADD_AD_CONSTANT(INTERNAL_ERROR);
6145 ADD_AD_CONSTANT(USER_CANCELLED);
6146 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006147 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006148#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6149 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6150#endif
6151#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6152 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6153#endif
6154#ifdef SSL_AD_UNRECOGNIZED_NAME
6155 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6156#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006157#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6158 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6159#endif
6160#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6161 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6162#endif
6163#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6164 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6165#endif
6166
6167#undef ADD_AD_CONSTANT
6168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006169 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006170#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006171 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6172 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006173#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006174#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006175 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6176 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006177#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006178 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006179 PY_SSL_VERSION_TLS);
6180 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6181 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006182 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6183 PY_SSL_VERSION_TLS_CLIENT);
6184 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6185 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006186 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6187 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006188#if HAVE_TLSv1_2
6189 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6190 PY_SSL_VERSION_TLS1_1);
6191 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6192 PY_SSL_VERSION_TLS1_2);
6193#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006194
Antoine Pitroub5218772010-05-21 09:56:06 +00006195 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006196 PyModule_AddIntConstant(m, "OP_ALL",
6197 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006198 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6199 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6200 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006201#if HAVE_TLSv1_2
6202 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6203 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6204#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006205#ifdef SSL_OP_NO_TLSv1_3
6206 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6207#else
6208 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6209#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006210 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6211 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006212 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006213 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006214#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006215 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006216#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006217#ifdef SSL_OP_NO_COMPRESSION
6218 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6219 SSL_OP_NO_COMPRESSION);
6220#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006221#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6222 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6223 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6224#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006225#ifdef SSL_OP_NO_RENEGOTIATION
6226 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6227 SSL_OP_NO_RENEGOTIATION);
6228#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006229
Christian Heimes61d478c2018-01-27 15:51:38 +01006230#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6231 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6232 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6233#endif
6234#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6235 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6236 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6237#endif
6238#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6239 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6240 X509_CHECK_FLAG_NO_WILDCARDS);
6241#endif
6242#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6243 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6244 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6245#endif
6246#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6247 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6248 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6249#endif
6250#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6251 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6252 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6253#endif
6254
Christian Heimes698dde12018-02-27 11:54:43 +01006255 /* protocol versions */
6256 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6257 PY_PROTO_MINIMUM_SUPPORTED);
6258 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6259 PY_PROTO_MAXIMUM_SUPPORTED);
6260 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6261 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6262 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6263 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6264 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006265
Victor Stinnerb37672d2018-11-22 03:37:50 +01006266#define addbool(m, key, value) \
6267 do { \
6268 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6269 Py_INCREF(bool_obj); \
6270 PyModule_AddObject((m), (key), bool_obj); \
6271 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006272
6273#if HAVE_SNI
6274 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006275#else
Christian Heimes698dde12018-02-27 11:54:43 +01006276 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006277#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006278
6279 addbool(m, "HAS_TLS_UNIQUE", 1);
6280
6281#ifndef OPENSSL_NO_ECDH
6282 addbool(m, "HAS_ECDH", 1);
6283#else
6284 addbool(m, "HAS_ECDH", 0);
6285#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006286
Christian Heimes29eab552018-02-25 12:31:33 +01006287#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006288 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006289#else
Christian Heimes698dde12018-02-27 11:54:43 +01006290 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006291#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006292
Christian Heimes29eab552018-02-25 12:31:33 +01006293#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006294 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006295#else
Christian Heimes698dde12018-02-27 11:54:43 +01006296 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006297#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006298
6299#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6300 addbool(m, "HAS_SSLv2", 1);
6301#else
6302 addbool(m, "HAS_SSLv2", 0);
6303#endif
6304
6305#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6306 addbool(m, "HAS_SSLv3", 1);
6307#else
6308 addbool(m, "HAS_SSLv3", 0);
6309#endif
6310
6311#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6312 addbool(m, "HAS_TLSv1", 1);
6313#else
6314 addbool(m, "HAS_TLSv1", 0);
6315#endif
6316
6317#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6318 addbool(m, "HAS_TLSv1_1", 1);
6319#else
6320 addbool(m, "HAS_TLSv1_1", 0);
6321#endif
6322
6323#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6324 addbool(m, "HAS_TLSv1_2", 1);
6325#else
6326 addbool(m, "HAS_TLSv1_2", 0);
6327#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006328
Christian Heimescb5b68a2017-09-07 18:07:00 -07006329#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006330 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006331#else
Christian Heimes698dde12018-02-27 11:54:43 +01006332 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006333#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006334
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006335 /* Mappings for error codes */
6336 err_codes_to_names = PyDict_New();
6337 err_names_to_codes = PyDict_New();
6338 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6339 return NULL;
6340 errcode = error_codes;
6341 while (errcode->mnemonic != NULL) {
6342 PyObject *mnemo, *key;
6343 mnemo = PyUnicode_FromString(errcode->mnemonic);
6344 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6345 if (mnemo == NULL || key == NULL)
6346 return NULL;
6347 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6348 return NULL;
6349 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6350 return NULL;
6351 Py_DECREF(key);
6352 Py_DECREF(mnemo);
6353 errcode++;
6354 }
6355 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6356 return NULL;
6357 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6358 return NULL;
6359
6360 lib_codes_to_names = PyDict_New();
6361 if (lib_codes_to_names == NULL)
6362 return NULL;
6363 libcode = library_codes;
6364 while (libcode->library != NULL) {
6365 PyObject *mnemo, *key;
6366 key = PyLong_FromLong(libcode->code);
6367 mnemo = PyUnicode_FromString(libcode->library);
6368 if (key == NULL || mnemo == NULL)
6369 return NULL;
6370 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6371 return NULL;
6372 Py_DECREF(key);
6373 Py_DECREF(mnemo);
6374 libcode++;
6375 }
6376 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6377 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006378
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006379 /* OpenSSL version */
6380 /* SSLeay() gives us the version of the library linked against,
6381 which could be different from the headers version.
6382 */
6383 libver = SSLeay();
6384 r = PyLong_FromUnsignedLong(libver);
6385 if (r == NULL)
6386 return NULL;
6387 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6388 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006389 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006390 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6391 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6392 return NULL;
6393 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6394 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6395 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006396
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006397 libver = OPENSSL_VERSION_NUMBER;
6398 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6399 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6400 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6401 return NULL;
6402
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006403 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006404}