blob: 5fe65a8a1d6dff969bad4b55788115037ca9fa25 [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
Christian Heimes470fba12013-11-28 15:12:15 +0100150/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100151 * This includes the SSL_set_SSL_CTX() function.
152 */
153#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
154# define HAVE_SNI 1
155#else
156# define HAVE_SNI 0
157#endif
158
Benjamin Petersond3308222015-09-27 00:09:02 -0700159#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100160# define HAVE_ALPN 1
161#else
162# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500163#endif
164
Christian Heimes6cdb7952018-02-24 22:12:40 +0100165/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
166 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
167 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
168 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100169 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100170 */
171#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100172# define HAVE_NPN 0
173#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
174# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100175#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100176# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177#else
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_NPN 0
179#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100180
Christian Heimesc7f70692019-05-31 11:44:05 +0200181#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
182#define HAVE_OPENSSL_KEYLOG 1
183#endif
184
Victor Stinner524714e2016-07-22 17:43:59 +0200185#ifndef INVALID_SOCKET /* MS defines this */
186#define INVALID_SOCKET (-1)
187#endif
188
Christian Heimes4ca07392018-03-24 15:41:37 +0100189/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
190#ifndef OPENSSL_VERSION_1_1
191#define HAVE_OPENSSL_CRYPTO_LOCK
192#endif
193
194#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200195#define OPENSSL_NO_SSL2
196#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100197
198#ifndef PY_OPENSSL_1_1_API
199/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200200
201#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200202#define TLS_client_method SSLv23_client_method
203#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200204
205static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
206{
207 return ne->set;
208}
209
210#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200211/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200212static int COMP_get_type(const COMP_METHOD *meth)
213{
214 return meth->type;
215}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200216/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200217#endif
218
219static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
220{
221 return ctx->default_passwd_callback;
222}
223
224static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
225{
226 return ctx->default_passwd_callback_userdata;
227}
228
229static int X509_OBJECT_get_type(X509_OBJECT *x)
230{
231 return x->type;
232}
233
234static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
235{
236 return x->data.x509;
237}
238
239static int BIO_up_ref(BIO *b)
240{
241 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
242 return 1;
243}
244
245static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
246 return store->objs;
247}
248
Christian Heimes99a65702016-09-10 23:44:53 +0200249static int
250SSL_SESSION_has_ticket(const SSL_SESSION *s)
251{
252 return (s->tlsext_ticklen > 0) ? 1 : 0;
253}
254
255static unsigned long
256SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
257{
258 return s->tlsext_tick_lifetime_hint;
259}
260
Christian Heimes4ca07392018-03-24 15:41:37 +0100261#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200262
Christian Heimes892d66e2018-01-29 14:10:18 +0100263/* Default cipher suites */
264#ifndef PY_SSL_DEFAULT_CIPHERS
265#define PY_SSL_DEFAULT_CIPHERS 1
266#endif
267
268#if PY_SSL_DEFAULT_CIPHERS == 0
269 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
270 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
271 #endif
272#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200273/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100274 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
275 * !aNULL:!eNULL: really no NULL ciphers
276 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
277 * !aDSS: no authentication with discrete logarithm DSA algorithm
278 * !SRP:!PSK: no secure remote password or pre-shared key authentication
279 */
280 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
281#elif PY_SSL_DEFAULT_CIPHERS == 2
282/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
283 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
284#else
285 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
286#endif
287
Christian Heimes598894f2016-09-05 23:19:05 +0200288
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000289enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000290 /* these mirror ssl.h */
291 PY_SSL_ERROR_NONE,
292 PY_SSL_ERROR_SSL,
293 PY_SSL_ERROR_WANT_READ,
294 PY_SSL_ERROR_WANT_WRITE,
295 PY_SSL_ERROR_WANT_X509_LOOKUP,
296 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
297 PY_SSL_ERROR_ZERO_RETURN,
298 PY_SSL_ERROR_WANT_CONNECT,
299 /* start of non ssl.h errorcodes */
300 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
301 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
302 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000303};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000304
Thomas Woutersed03b412007-08-28 21:37:11 +0000305enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000306 PY_SSL_CLIENT,
307 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000308};
309
310enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000311 PY_SSL_CERT_NONE,
312 PY_SSL_CERT_OPTIONAL,
313 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000314};
315
316enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000317 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200318 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200319 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100320 PY_SSL_VERSION_TLS1,
321 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200322 PY_SSL_VERSION_TLS1_2,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200323 PY_SSL_VERSION_TLS_CLIENT=0x10,
324 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100325};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200326
Christian Heimes698dde12018-02-27 11:54:43 +0100327enum py_proto_version {
328 PY_PROTO_MINIMUM_SUPPORTED = -2,
329 PY_PROTO_SSLv3 = SSL3_VERSION,
330 PY_PROTO_TLSv1 = TLS1_VERSION,
331 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
332 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
333#ifdef TLS1_3_VERSION
334 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
335#else
336 PY_PROTO_TLSv1_3 = 0x304,
337#endif
338 PY_PROTO_MAXIMUM_SUPPORTED = -1,
339
340/* OpenSSL has no dedicated API to set the minimum version to the maximum
341 * available version, and the other way around. We have to figure out the
342 * minimum and maximum available version on our own and hope for the best.
343 */
344#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
345 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
346#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
347 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
348#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
349 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
350#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
351 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
352#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
353 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
354#else
355 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
356#endif
357
358#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
359 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
360#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
361 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
362#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
363 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
364#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
365 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
366#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
367 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
368#else
369 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
370#endif
371};
372
373
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000374/* serves as a flag to see whether we've initialized the SSL thread support. */
375/* 0 means no, greater than 0 means yes */
376
377static unsigned int _ssl_locks_count = 0;
378
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000379/* SSL socket object */
380
381#define X509_NAME_MAXLEN 256
382
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000383/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
384 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
385 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
386#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000387# define HAVE_SSL_CTX_CLEAR_OPTIONS
388#else
389# undef HAVE_SSL_CTX_CLEAR_OPTIONS
390#endif
391
Antoine Pitroud6494802011-07-21 01:11:30 +0200392/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
393 * older SSL, but let's be safe */
394#define PySSL_CB_MAXLEN 128
395
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100396
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000397typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000398 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000399 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100400#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500401 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100402 int npn_protocols_len;
403#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100404#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500405 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300406 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500407#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100408#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100409 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100410#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100411 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100412 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
413 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
414 */
415 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100416 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200417#ifdef TLS1_3_VERSION
418 int post_handshake_auth;
419#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200420 PyObject *msg_cb;
421#ifdef HAVE_OPENSSL_KEYLOG
422 PyObject *keylog_filename;
423 BIO *keylog_bio;
424#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000425} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000426
Antoine Pitrou152efa22010-05-16 18:19:27 +0000427typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700428 int ssl; /* last seen error from SSL */
429 int c; /* last seen error from libc */
430#ifdef MS_WINDOWS
431 int ws; /* last seen error from winsock */
432#endif
433} _PySSLError;
434
435typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000436 PyObject_HEAD
437 PyObject *Socket; /* weakref to socket on which we're layered */
438 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100439 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200440 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200441 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200442 PyObject *owner; /* Python level "owner" passed to servername callback */
443 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700444 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200445 /* Some SSL callbacks don't have error reporting. Callback wrappers
446 * store exception information on the socket. The handshake, read, write,
447 * and shutdown methods check for chained exceptions.
448 */
449 PyObject *exc_type;
450 PyObject *exc_value;
451 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000452} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000453
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200454typedef struct {
455 PyObject_HEAD
456 BIO *bio;
457 int eof_written;
458} PySSLMemoryBIO;
459
Christian Heimes99a65702016-09-10 23:44:53 +0200460typedef struct {
461 PyObject_HEAD
462 SSL_SESSION *session;
463 PySSLContext *ctx;
464} PySSLSession;
465
Antoine Pitrou152efa22010-05-16 18:19:27 +0000466static PyTypeObject PySSLContext_Type;
467static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200468static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200469static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000470
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700471static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
472{
473 _PySSLError err = { 0 };
474 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700475#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700476 err.ws = WSAGetLastError();
477 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700478#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700479 err.c = errno;
480 err.ssl = SSL_get_error(ssl, retcode);
481 }
482 return err;
483}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300485/*[clinic input]
486module _ssl
487class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
488class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
489class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200490class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300491[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200492/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300493
494#include "clinic/_ssl.c.h"
495
Victor Stinner14690702015-04-06 22:46:13 +0200496static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000497
Christian Heimes141c5e82018-02-24 21:10:57 +0100498static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
499static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Dong-hee Na1b55b652020-02-17 19:09:15 +0900500#define PySSLSocket_Check(v) Py_IS_TYPE(v, &PySSLSocket_Type)
501#define PySSLMemoryBIO_Check(v) Py_IS_TYPE(v, &PySSLMemoryBIO_Type)
502#define PySSLSession_Check(v) Py_IS_TYPE(v, &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000503
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000504typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000505 SOCKET_IS_NONBLOCKING,
506 SOCKET_IS_BLOCKING,
507 SOCKET_HAS_TIMED_OUT,
508 SOCKET_HAS_BEEN_CLOSED,
509 SOCKET_TOO_LARGE_FOR_SELECT,
510 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000511} timeout_state;
512
Thomas Woutersed03b412007-08-28 21:37:11 +0000513/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000514#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200515#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000516
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200517/* Get the socket from a PySSLSocket, if it has one */
518#define GET_SOCKET(obj) ((obj)->Socket ? \
519 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520
Victor Stinner14690702015-04-06 22:46:13 +0200521/* If sock is NULL, use a timeout of 0 second */
522#define GET_SOCKET_TIMEOUT(sock) \
523 ((sock != NULL) ? (sock)->sock_timeout : 0)
524
Christian Heimesc7f70692019-05-31 11:44:05 +0200525#include "_ssl/debughelpers.c"
526
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527/*
528 * SSL errors.
529 */
530
531PyDoc_STRVAR(SSLError_doc,
532"An error occurred in the SSL implementation.");
533
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700534PyDoc_STRVAR(SSLCertVerificationError_doc,
535"A certificate could not be verified.");
536
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200537PyDoc_STRVAR(SSLZeroReturnError_doc,
538"SSL/TLS session closed cleanly.");
539
540PyDoc_STRVAR(SSLWantReadError_doc,
541"Non-blocking SSL socket needs to read more data\n"
542"before the requested operation can be completed.");
543
544PyDoc_STRVAR(SSLWantWriteError_doc,
545"Non-blocking SSL socket needs to write more data\n"
546"before the requested operation can be completed.");
547
548PyDoc_STRVAR(SSLSyscallError_doc,
549"System error when attempting SSL operation.");
550
551PyDoc_STRVAR(SSLEOFError_doc,
552"SSL/TLS connection terminated abruptly.");
553
554static PyObject *
555SSLError_str(PyOSErrorObject *self)
556{
557 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
558 Py_INCREF(self->strerror);
559 return self->strerror;
560 }
561 else
562 return PyObject_Str(self->args);
563}
564
565static PyType_Slot sslerror_type_slots[] = {
566 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900567 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200568 {Py_tp_str, SSLError_str},
569 {0, 0},
570};
571
572static PyType_Spec sslerror_type_spec = {
573 "ssl.SSLError",
574 sizeof(PyOSErrorObject),
575 0,
576 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
577 sslerror_type_slots
578};
579
580static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700581fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
582 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200583{
584 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700585 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200586 PyObject *init_value, *msg, *key;
587 _Py_IDENTIFIER(reason);
588 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700589 _Py_IDENTIFIER(verify_message);
590 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200591
592 if (errcode != 0) {
593 int lib, reason;
594
595 lib = ERR_GET_LIB(errcode);
596 reason = ERR_GET_REASON(errcode);
597 key = Py_BuildValue("ii", lib, reason);
598 if (key == NULL)
599 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300600 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200601 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300602 if (reason_obj == NULL && PyErr_Occurred()) {
603 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200604 }
605 key = PyLong_FromLong(lib);
606 if (key == NULL)
607 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300608 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200609 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300610 if (lib_obj == NULL && PyErr_Occurred()) {
611 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 }
613 if (errstr == NULL)
614 errstr = ERR_reason_error_string(errcode);
615 }
616 if (errstr == NULL)
617 errstr = "unknown error";
618
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700619 /* verify code for cert validation error */
620 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
621 const char *verify_str = NULL;
622 long verify_code;
623
624 verify_code = SSL_get_verify_result(sslsock->ssl);
625 verify_code_obj = PyLong_FromLong(verify_code);
626 if (verify_code_obj == NULL) {
627 goto fail;
628 }
629
630 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700631#ifdef X509_V_ERR_HOSTNAME_MISMATCH
632 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700633 case X509_V_ERR_HOSTNAME_MISMATCH:
634 verify_obj = PyUnicode_FromFormat(
635 "Hostname mismatch, certificate is not valid for '%S'.",
636 sslsock->server_hostname
637 );
638 break;
Christian Heimes09153602017-09-08 14:47:58 -0700639#endif
640#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700641 case X509_V_ERR_IP_ADDRESS_MISMATCH:
642 verify_obj = PyUnicode_FromFormat(
643 "IP address mismatch, certificate is not valid for '%S'.",
644 sslsock->server_hostname
645 );
646 break;
Christian Heimes09153602017-09-08 14:47:58 -0700647#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700648 default:
649 verify_str = X509_verify_cert_error_string(verify_code);
650 if (verify_str != NULL) {
651 verify_obj = PyUnicode_FromString(verify_str);
652 } else {
653 verify_obj = Py_None;
654 Py_INCREF(verify_obj);
655 }
656 break;
657 }
658 if (verify_obj == NULL) {
659 goto fail;
660 }
661 }
662
663 if (verify_obj && reason_obj && lib_obj)
664 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
665 lib_obj, reason_obj, errstr, verify_obj,
666 lineno);
667 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200668 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
669 lib_obj, reason_obj, errstr, lineno);
670 else if (lib_obj)
671 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
672 lib_obj, errstr, lineno);
673 else
674 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200675 if (msg == NULL)
676 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100677
Paul Monsonfb7e7502019-05-15 15:38:55 -0700678 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100679 if (init_value == NULL)
680 goto fail;
681
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200682 err_value = PyObject_CallObject(type, init_value);
683 Py_DECREF(init_value);
684 if (err_value == NULL)
685 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100686
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200687 if (reason_obj == NULL)
688 reason_obj = Py_None;
689 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
690 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700691
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200692 if (lib_obj == NULL)
693 lib_obj = Py_None;
694 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
695 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700696
697 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
698 /* Only set verify code / message for SSLCertVerificationError */
699 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
700 verify_code_obj))
701 goto fail;
702 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
703 goto fail;
704 }
705
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200706 PyErr_SetObject(type, err_value);
707fail:
708 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700709 Py_XDECREF(verify_code_obj);
710 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000712
Christian Heimesc7f70692019-05-31 11:44:05 +0200713static int
714PySSL_ChainExceptions(PySSLSocket *sslsock) {
715 if (sslsock->exc_type == NULL)
716 return 0;
717
718 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
719 sslsock->exc_type = NULL;
720 sslsock->exc_value = NULL;
721 sslsock->exc_tb = NULL;
722 return -1;
723}
724
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000725static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700726PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000727{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200728 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200729 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700730 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200732 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000733
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200735 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000736
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700737 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700738 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000739
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700740 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200742 errstr = "TLS/SSL connection has been closed (EOF)";
743 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 p = PY_SSL_ERROR_ZERO_RETURN;
745 break;
746 case SSL_ERROR_WANT_READ:
747 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200748 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000749 p = PY_SSL_ERROR_WANT_READ;
750 break;
751 case SSL_ERROR_WANT_WRITE:
752 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200753 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 errstr = "The operation did not complete (write)";
755 break;
756 case SSL_ERROR_WANT_X509_LOOKUP:
757 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000758 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 break;
760 case SSL_ERROR_WANT_CONNECT:
761 p = PY_SSL_ERROR_WANT_CONNECT;
762 errstr = "The operation did not complete (connect)";
763 break;
764 case SSL_ERROR_SYSCALL:
765 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700767 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000769 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200770 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000771 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200772 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000773 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000774 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700775#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700776 if (err.ws) {
777 return PyErr_SetFromWindowsErr(err.ws);
778 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700779#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700780 if (err.c) {
781 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700782 return PyErr_SetFromErrno(PyExc_OSError);
783 }
784 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200785 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000786 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200787 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000789 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200790 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000791 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 }
793 } else {
794 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000795 }
796 break;
797 }
798 case SSL_ERROR_SSL:
799 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000800 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700801 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200802 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000803 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700804 }
805 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
806 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
807 type = PySSLCertVerificationErrorObject;
808 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 break;
810 }
811 default:
812 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
813 errstr = "Invalid error code";
814 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700816 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000817 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200818 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000820}
821
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000822static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200823_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000824
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200825 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200827 else
828 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700829 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000830 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000832}
833
Christian Heimes61d478c2018-01-27 15:51:38 +0100834/*
835 * SSL objects
836 */
837
838static int
839_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
840{
841 int retval = -1;
842 ASN1_OCTET_STRING *ip;
843 PyObject *hostname;
844 size_t len;
845
846 assert(server_hostname);
847
848 /* Disable OpenSSL's special mode with leading dot in hostname:
849 * When name starts with a dot (e.g ".example.com"), it will be
850 * matched by a certificate valid for any sub-domain of name.
851 */
852 len = strlen(server_hostname);
853 if (len == 0 || *server_hostname == '.') {
854 PyErr_SetString(
855 PyExc_ValueError,
856 "server_hostname cannot be an empty string or start with a "
857 "leading dot.");
858 return retval;
859 }
860
861 /* inet_pton is not available on all platforms. */
862 ip = a2i_IPADDRESS(server_hostname);
863 if (ip == NULL) {
864 ERR_clear_error();
865 }
866
Christian Heimes11a14932018-02-24 02:35:08 +0100867 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100868 if (hostname == NULL) {
869 goto error;
870 }
871 self->server_hostname = hostname;
872
873 /* Only send SNI extension for non-IP hostnames */
874 if (ip == NULL) {
875 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
876 _setSSLError(NULL, 0, __FILE__, __LINE__);
877 }
878 }
879 if (self->ctx->check_hostname) {
880 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
881 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200882 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
883 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100884 _setSSLError(NULL, 0, __FILE__, __LINE__);
885 goto error;
886 }
887 } else {
888 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
889 ASN1_STRING_length(ip))) {
890 _setSSLError(NULL, 0, __FILE__, __LINE__);
891 goto error;
892 }
893 }
894 }
895 retval = 0;
896 error:
897 if (ip != NULL) {
898 ASN1_OCTET_STRING_free(ip);
899 }
900 return retval;
901}
902
Antoine Pitrou152efa22010-05-16 18:19:27 +0000903static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100904newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000905 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200906 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100907 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200908 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000909{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000910 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100911 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700912 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000913
Antoine Pitrou152efa22010-05-16 18:19:27 +0000914 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 if (self == NULL)
916 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100920 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700921 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200922 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200923 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700924 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700925 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200926 self->exc_type = NULL;
927 self->exc_value = NULL;
928 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200929
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000934 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700936 if (self->ssl == NULL) {
937 Py_DECREF(self);
938 _setSSLError(NULL, 0, __FILE__, __LINE__);
939 return NULL;
940 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200941 SSL_set_app_data(self->ssl, self);
942 if (sock) {
943 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
944 } else {
945 /* BIOs are reference counted and SSL_set_bio borrows our reference.
946 * To prevent a double free in memory_bio_dealloc() we need to take an
947 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200948 BIO_up_ref(inbio->bio);
949 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200950 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
951 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400952 SSL_set_mode(self->ssl,
953 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000954
Christian Heimesf0f59302019-07-01 08:29:17 +0200955#ifdef TLS1_3_VERSION
956 if (sslctx->post_handshake_auth == 1) {
957 if (socket_type == PY_SSL_SERVER) {
958 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
959 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
960 * only in combination with SSL_VERIFY_PEER flag. */
961 int mode = SSL_get_verify_mode(self->ssl);
962 if (mode & SSL_VERIFY_PEER) {
963 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
964 verify_cb = SSL_get_verify_callback(self->ssl);
965 mode |= SSL_VERIFY_POST_HANDSHAKE;
966 SSL_set_verify(self->ssl, mode, verify_cb);
967 }
968 } else {
969 /* client socket */
970 SSL_set_post_handshake_auth(self->ssl, 1);
971 }
972 }
973#endif
974
Christian Heimes61d478c2018-01-27 15:51:38 +0100975 if (server_hostname != NULL) {
976 if (_ssl_configure_hostname(self, server_hostname) < 0) {
977 Py_DECREF(self);
978 return NULL;
979 }
980 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 /* If the socket is in non-blocking mode or timeout mode, set the BIO
982 * to non-blocking mode (blocking is the default)
983 */
Victor Stinnere2452312015-03-28 03:00:46 +0100984 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
986 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
987 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 PySSL_BEGIN_ALLOW_THREADS
990 if (socket_type == PY_SSL_CLIENT)
991 SSL_set_connect_state(self->ssl);
992 else
993 SSL_set_accept_state(self->ssl);
994 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000995
Antoine Pitroud6494802011-07-21 01:11:30 +0200996 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200997 if (sock != NULL) {
998 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
999 if (self->Socket == NULL) {
1000 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001001 return NULL;
1002 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001003 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001004 if (owner && owner != Py_None) {
1005 if (PySSL_set_owner(self, owner, NULL) == -1) {
1006 Py_DECREF(self);
1007 return NULL;
1008 }
1009 }
1010 if (session && session != Py_None) {
1011 if (PySSL_set_session(self, session, NULL) == -1) {
1012 Py_DECREF(self);
1013 return NULL;
1014 }
1015 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001017}
1018
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001019/* SSL object methods */
1020
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001021/*[clinic input]
1022_ssl._SSLSocket.do_handshake
1023[clinic start generated code]*/
1024
1025static PyObject *
1026_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1027/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001028{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001030 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001032 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001033 _PyTime_t timeout, deadline = 0;
1034 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001035
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001036 if (sock) {
1037 if (((PyObject*)sock) == Py_None) {
1038 _setSSLError("Underlying socket connection gone",
1039 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1040 return NULL;
1041 }
1042 Py_INCREF(sock);
1043
1044 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001045 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001046 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1047 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001049
Victor Stinner14690702015-04-06 22:46:13 +02001050 timeout = GET_SOCKET_TIMEOUT(sock);
1051 has_timeout = (timeout > 0);
1052 if (has_timeout)
1053 deadline = _PyTime_GetMonotonicClock() + timeout;
1054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 /* Actually negotiate SSL connection */
1056 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001058 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001060 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001062 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001063
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001064 if (PyErr_CheckSignals())
1065 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001066
Victor Stinner14690702015-04-06 22:46:13 +02001067 if (has_timeout)
1068 timeout = deadline - _PyTime_GetMonotonicClock();
1069
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001070 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001071 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001072 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001073 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 } else {
1075 sockstate = SOCKET_OPERATION_OK;
1076 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001079 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001080 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001081 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001082 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1083 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001084 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001085 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1087 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001088 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001089 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001090 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1091 break;
1092 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001093 } while (err.ssl == SSL_ERROR_WANT_READ ||
1094 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001095 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001096 if (ret < 1)
1097 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001098 if (PySSL_ChainExceptions(self) < 0)
1099 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001100 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001101error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001102 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001103 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001104 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001105}
1106
Thomas Woutersed03b412007-08-28 21:37:11 +00001107static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001108_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1109{
1110 char buf[X509_NAME_MAXLEN];
1111 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001113 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001114
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001115 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 if (buflen < 0) {
1117 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001118 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001120 /* initial buffer is too small for oid + terminating null byte */
1121 if (buflen > X509_NAME_MAXLEN - 1) {
1122 /* make OBJ_obj2txt() calculate the required buflen */
1123 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1124 /* allocate len + 1 for terminating NULL byte */
1125 namebuf = PyMem_Malloc(buflen + 1);
1126 if (namebuf == NULL) {
1127 PyErr_NoMemory();
1128 return NULL;
1129 }
1130 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1131 if (buflen < 0) {
1132 _setSSLError(NULL, 0, __FILE__, __LINE__);
1133 goto done;
1134 }
1135 }
1136 if (!buflen && no_name) {
1137 Py_INCREF(Py_None);
1138 name_obj = Py_None;
1139 }
1140 else {
1141 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1142 }
1143
1144 done:
1145 if (buf != namebuf) {
1146 PyMem_Free(namebuf);
1147 }
1148 return name_obj;
1149}
1150
1151static PyObject *
1152_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1153{
1154 Py_ssize_t buflen;
1155 unsigned char *valuebuf = NULL;
1156 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1159 if (buflen < 0) {
1160 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001161 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001163 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001166}
1167
1168static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001169_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001170{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1172 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1173 PyObject *rdnt;
1174 PyObject *attr = NULL; /* tuple to hold an attribute */
1175 int entry_count = X509_NAME_entry_count(xname);
1176 X509_NAME_ENTRY *entry;
1177 ASN1_OBJECT *name;
1178 ASN1_STRING *value;
1179 int index_counter;
1180 int rdn_level = -1;
1181 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 dn = PyList_New(0);
1184 if (dn == NULL)
1185 return NULL;
1186 /* now create another tuple to hold the top-level RDN */
1187 rdn = PyList_New(0);
1188 if (rdn == NULL)
1189 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 for (index_counter = 0;
1192 index_counter < entry_count;
1193 index_counter++)
1194 {
1195 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001196
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 /* check to see if we've gotten to a new RDN */
1198 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001199 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 /* yes, new RDN */
1201 /* add old RDN to DN */
1202 rdnt = PyList_AsTuple(rdn);
1203 Py_DECREF(rdn);
1204 if (rdnt == NULL)
1205 goto fail0;
1206 retcode = PyList_Append(dn, rdnt);
1207 Py_DECREF(rdnt);
1208 if (retcode < 0)
1209 goto fail0;
1210 /* create new RDN */
1211 rdn = PyList_New(0);
1212 if (rdn == NULL)
1213 goto fail0;
1214 }
1215 }
Christian Heimes598894f2016-09-05 23:19:05 +02001216 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 /* now add this attribute to the current RDN */
1219 name = X509_NAME_ENTRY_get_object(entry);
1220 value = X509_NAME_ENTRY_get_data(entry);
1221 attr = _create_tuple_for_attribute(name, value);
1222 /*
1223 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1224 entry->set,
1225 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1226 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1227 */
1228 if (attr == NULL)
1229 goto fail1;
1230 retcode = PyList_Append(rdn, attr);
1231 Py_DECREF(attr);
1232 if (retcode < 0)
1233 goto fail1;
1234 }
1235 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001236 if (rdn != NULL) {
1237 if (PyList_GET_SIZE(rdn) > 0) {
1238 rdnt = PyList_AsTuple(rdn);
1239 Py_DECREF(rdn);
1240 if (rdnt == NULL)
1241 goto fail0;
1242 retcode = PyList_Append(dn, rdnt);
1243 Py_DECREF(rdnt);
1244 if (retcode < 0)
1245 goto fail0;
1246 }
1247 else {
1248 Py_DECREF(rdn);
1249 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 /* convert list to tuple */
1253 rdnt = PyList_AsTuple(dn);
1254 Py_DECREF(dn);
1255 if (rdnt == NULL)
1256 return NULL;
1257 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001258
1259 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001261
1262 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 Py_XDECREF(dn);
1264 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265}
1266
1267static PyObject *
1268_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001269
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 /* this code follows the procedure outlined in
1271 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1272 function to extract the STACK_OF(GENERAL_NAME),
1273 then iterates through the stack to add the
1274 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001276 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001278 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 GENERAL_NAMES *names = NULL;
1280 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 BIO *biobuf = NULL;
1282 char buf[2048];
1283 char *vptr;
1284 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001286 if (certificate == NULL)
1287 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001288
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 /* get a memory buffer */
1290 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001291 if (biobuf == NULL) {
1292 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1293 return NULL;
1294 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001295
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001296 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1297 certificate, NID_subject_alt_name, NULL, NULL);
1298 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001299 if (peer_alt_names == Py_None) {
1300 peer_alt_names = PyList_New(0);
1301 if (peer_alt_names == NULL)
1302 goto fail;
1303 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001306 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001307 int gntype;
1308 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001311 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001312 switch (gntype) {
1313 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001314 /* we special-case DirName as a tuple of
1315 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 t = PyTuple_New(2);
1318 if (t == NULL) {
1319 goto fail;
1320 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001321
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001322 v = PyUnicode_FromString("DirName");
1323 if (v == NULL) {
1324 Py_DECREF(t);
1325 goto fail;
1326 }
1327 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 v = _create_tuple_for_X509_NAME (name->d.dirn);
1330 if (v == NULL) {
1331 Py_DECREF(t);
1332 goto fail;
1333 }
1334 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001335 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001336
Christian Heimes824f7f32013-08-17 00:54:47 +02001337 case GEN_EMAIL:
1338 case GEN_DNS:
1339 case GEN_URI:
1340 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1341 correctly, CVE-2013-4238 */
1342 t = PyTuple_New(2);
1343 if (t == NULL)
1344 goto fail;
1345 switch (gntype) {
1346 case GEN_EMAIL:
1347 v = PyUnicode_FromString("email");
1348 as = name->d.rfc822Name;
1349 break;
1350 case GEN_DNS:
1351 v = PyUnicode_FromString("DNS");
1352 as = name->d.dNSName;
1353 break;
1354 case GEN_URI:
1355 v = PyUnicode_FromString("URI");
1356 as = name->d.uniformResourceIdentifier;
1357 break;
1358 }
1359 if (v == NULL) {
1360 Py_DECREF(t);
1361 goto fail;
1362 }
1363 PyTuple_SET_ITEM(t, 0, v);
1364 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1365 ASN1_STRING_length(as));
1366 if (v == NULL) {
1367 Py_DECREF(t);
1368 goto fail;
1369 }
1370 PyTuple_SET_ITEM(t, 1, v);
1371 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001372
Christian Heimes1c03abd2016-09-06 23:25:35 +02001373 case GEN_RID:
1374 t = PyTuple_New(2);
1375 if (t == NULL)
1376 goto fail;
1377
1378 v = PyUnicode_FromString("Registered ID");
1379 if (v == NULL) {
1380 Py_DECREF(t);
1381 goto fail;
1382 }
1383 PyTuple_SET_ITEM(t, 0, v);
1384
1385 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1386 if (len < 0) {
1387 Py_DECREF(t);
1388 _setSSLError(NULL, 0, __FILE__, __LINE__);
1389 goto fail;
1390 } else if (len >= (int)sizeof(buf)) {
1391 v = PyUnicode_FromString("<INVALID>");
1392 } else {
1393 v = PyUnicode_FromStringAndSize(buf, len);
1394 }
1395 if (v == NULL) {
1396 Py_DECREF(t);
1397 goto fail;
1398 }
1399 PyTuple_SET_ITEM(t, 1, v);
1400 break;
1401
Christian Heimes2b7de662019-12-07 17:59:36 +01001402 case GEN_IPADD:
1403 /* OpenSSL < 3.0.0 adds a trailing \n to IPv6. 3.0.0 removed
1404 * the trailing newline. Remove it in all versions
1405 */
1406 t = PyTuple_New(2);
1407 if (t == NULL)
1408 goto fail;
1409
1410 v = PyUnicode_FromString("IP Address");
1411 if (v == NULL) {
1412 Py_DECREF(t);
1413 goto fail;
1414 }
1415 PyTuple_SET_ITEM(t, 0, v);
1416
1417 if (name->d.ip->length == 4) {
1418 unsigned char *p = name->d.ip->data;
1419 v = PyUnicode_FromFormat(
1420 "%d.%d.%d.%d",
1421 p[0], p[1], p[2], p[3]
1422 );
1423 } else if (name->d.ip->length == 16) {
1424 /* PyUnicode_FromFormat() does not support %X */
1425 unsigned char *p = name->d.ip->data;
1426 len = sprintf(
1427 buf,
1428 "%X:%X:%X:%X:%X:%X:%X:%X",
1429 p[0] << 8 | p[1],
1430 p[2] << 8 | p[3],
1431 p[4] << 8 | p[5],
1432 p[6] << 8 | p[7],
1433 p[8] << 8 | p[9],
1434 p[10] << 8 | p[11],
1435 p[12] << 8 | p[13],
1436 p[14] << 8 | p[15]
1437 );
1438 v = PyUnicode_FromStringAndSize(buf, len);
1439 } else {
1440 v = PyUnicode_FromString("<invalid>");
1441 }
1442
1443 if (v == NULL) {
1444 Py_DECREF(t);
1445 goto fail;
1446 }
1447 PyTuple_SET_ITEM(t, 1, v);
1448 break;
1449
Christian Heimes824f7f32013-08-17 00:54:47 +02001450 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001452 switch (gntype) {
1453 /* check for new general name type */
1454 case GEN_OTHERNAME:
1455 case GEN_X400:
1456 case GEN_EDIPARTY:
Christian Heimes824f7f32013-08-17 00:54:47 +02001457 case GEN_RID:
1458 break;
1459 default:
1460 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1461 "Unknown general name type %d",
1462 gntype) == -1) {
1463 goto fail;
1464 }
1465 break;
1466 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001467 (void) BIO_reset(biobuf);
1468 GENERAL_NAME_print(biobuf, name);
1469 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1470 if (len < 0) {
1471 _setSSLError(NULL, 0, __FILE__, __LINE__);
1472 goto fail;
1473 }
1474 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001475 if (vptr == NULL) {
1476 PyErr_Format(PyExc_ValueError,
1477 "Invalid value %.200s",
1478 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001480 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 t = PyTuple_New(2);
1482 if (t == NULL)
1483 goto fail;
1484 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1485 if (v == NULL) {
1486 Py_DECREF(t);
1487 goto fail;
1488 }
1489 PyTuple_SET_ITEM(t, 0, v);
1490 v = PyUnicode_FromStringAndSize((vptr + 1),
1491 (len - (vptr - buf + 1)));
1492 if (v == NULL) {
1493 Py_DECREF(t);
1494 goto fail;
1495 }
1496 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001497 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001498 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001499
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001500 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 if (PyList_Append(peer_alt_names, t) < 0) {
1503 Py_DECREF(t);
1504 goto fail;
1505 }
1506 Py_DECREF(t);
1507 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001508 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001509 }
1510 BIO_free(biobuf);
1511 if (peer_alt_names != Py_None) {
1512 v = PyList_AsTuple(peer_alt_names);
1513 Py_DECREF(peer_alt_names);
1514 return v;
1515 } else {
1516 return peer_alt_names;
1517 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001518
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001519
1520 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521 if (biobuf != NULL)
1522 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 if (peer_alt_names != Py_None) {
1525 Py_XDECREF(peer_alt_names);
1526 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001529}
1530
1531static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001532_get_aia_uri(X509 *certificate, int nid) {
1533 PyObject *lst = NULL, *ostr = NULL;
1534 int i, result;
1535 AUTHORITY_INFO_ACCESS *info;
1536
1537 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001538 if (info == NULL)
1539 return Py_None;
1540 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1541 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001542 return Py_None;
1543 }
1544
1545 if ((lst = PyList_New(0)) == NULL) {
1546 goto fail;
1547 }
1548
1549 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1550 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1551 ASN1_IA5STRING *uri;
1552
1553 if ((OBJ_obj2nid(ad->method) != nid) ||
1554 (ad->location->type != GEN_URI)) {
1555 continue;
1556 }
1557 uri = ad->location->d.uniformResourceIdentifier;
1558 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1559 uri->length);
1560 if (ostr == NULL) {
1561 goto fail;
1562 }
1563 result = PyList_Append(lst, ostr);
1564 Py_DECREF(ostr);
1565 if (result < 0) {
1566 goto fail;
1567 }
1568 }
1569 AUTHORITY_INFO_ACCESS_free(info);
1570
1571 /* convert to tuple or None */
1572 if (PyList_Size(lst) == 0) {
1573 Py_DECREF(lst);
1574 return Py_None;
1575 } else {
1576 PyObject *tup;
1577 tup = PyList_AsTuple(lst);
1578 Py_DECREF(lst);
1579 return tup;
1580 }
1581
1582 fail:
1583 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001584 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001585 return NULL;
1586}
1587
1588static PyObject *
1589_get_crl_dp(X509 *certificate) {
1590 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001591 int i, j;
1592 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001593
Christian Heimes598894f2016-09-05 23:19:05 +02001594 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001595
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001596 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001597 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001598
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001599 lst = PyList_New(0);
1600 if (lst == NULL)
1601 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001602
1603 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1604 DIST_POINT *dp;
1605 STACK_OF(GENERAL_NAME) *gns;
1606
1607 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001608 if (dp->distpoint == NULL) {
1609 /* Ignore empty DP value, CVE-2019-5010 */
1610 continue;
1611 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001612 gns = dp->distpoint->name.fullname;
1613
1614 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1615 GENERAL_NAME *gn;
1616 ASN1_IA5STRING *uri;
1617 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001618 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001619
1620 gn = sk_GENERAL_NAME_value(gns, j);
1621 if (gn->type != GEN_URI) {
1622 continue;
1623 }
1624 uri = gn->d.uniformResourceIdentifier;
1625 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1626 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001627 if (ouri == NULL)
1628 goto done;
1629
1630 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001631 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001632 if (err < 0)
1633 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001634 }
1635 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001636
1637 /* Convert to tuple. */
1638 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1639
1640 done:
1641 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001642 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001643 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001644}
1645
1646static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001647_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001649 PyObject *retval = NULL;
1650 BIO *biobuf = NULL;
1651 PyObject *peer;
1652 PyObject *peer_alt_names = NULL;
1653 PyObject *issuer;
1654 PyObject *version;
1655 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001656 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001657 ASN1_INTEGER *serialNumber;
1658 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001659 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001660 ASN1_TIME *notBefore, *notAfter;
1661 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 retval = PyDict_New();
1664 if (retval == NULL)
1665 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001667 peer = _create_tuple_for_X509_NAME(
1668 X509_get_subject_name(certificate));
1669 if (peer == NULL)
1670 goto fail0;
1671 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1672 Py_DECREF(peer);
1673 goto fail0;
1674 }
1675 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001676
Antoine Pitroufb046912010-11-09 20:21:19 +00001677 issuer = _create_tuple_for_X509_NAME(
1678 X509_get_issuer_name(certificate));
1679 if (issuer == NULL)
1680 goto fail0;
1681 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001683 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001684 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001685 Py_DECREF(issuer);
1686
1687 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001688 if (version == NULL)
1689 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001690 if (PyDict_SetItemString(retval, "version", version) < 0) {
1691 Py_DECREF(version);
1692 goto fail0;
1693 }
1694 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001695
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 /* get a memory buffer */
1697 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001698 if (biobuf == NULL) {
1699 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1700 goto fail0;
1701 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001702
Antoine Pitroufb046912010-11-09 20:21:19 +00001703 (void) BIO_reset(biobuf);
1704 serialNumber = X509_get_serialNumber(certificate);
1705 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1706 i2a_ASN1_INTEGER(biobuf, serialNumber);
1707 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1708 if (len < 0) {
1709 _setSSLError(NULL, 0, __FILE__, __LINE__);
1710 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001712 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1713 if (sn_obj == NULL)
1714 goto fail1;
1715 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1716 Py_DECREF(sn_obj);
1717 goto fail1;
1718 }
1719 Py_DECREF(sn_obj);
1720
1721 (void) BIO_reset(biobuf);
1722 notBefore = X509_get_notBefore(certificate);
1723 ASN1_TIME_print(biobuf, notBefore);
1724 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1725 if (len < 0) {
1726 _setSSLError(NULL, 0, __FILE__, __LINE__);
1727 goto fail1;
1728 }
1729 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1730 if (pnotBefore == NULL)
1731 goto fail1;
1732 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1733 Py_DECREF(pnotBefore);
1734 goto fail1;
1735 }
1736 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 (void) BIO_reset(biobuf);
1739 notAfter = X509_get_notAfter(certificate);
1740 ASN1_TIME_print(biobuf, notAfter);
1741 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1742 if (len < 0) {
1743 _setSSLError(NULL, 0, __FILE__, __LINE__);
1744 goto fail1;
1745 }
1746 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1747 if (pnotAfter == NULL)
1748 goto fail1;
1749 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1750 Py_DECREF(pnotAfter);
1751 goto fail1;
1752 }
1753 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 peer_alt_names = _get_peer_alt_names(certificate);
1758 if (peer_alt_names == NULL)
1759 goto fail1;
1760 else if (peer_alt_names != Py_None) {
1761 if (PyDict_SetItemString(retval, "subjectAltName",
1762 peer_alt_names) < 0) {
1763 Py_DECREF(peer_alt_names);
1764 goto fail1;
1765 }
1766 Py_DECREF(peer_alt_names);
1767 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001768
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001769 /* Authority Information Access: OCSP URIs */
1770 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1771 if (obj == NULL) {
1772 goto fail1;
1773 } else if (obj != Py_None) {
1774 result = PyDict_SetItemString(retval, "OCSP", obj);
1775 Py_DECREF(obj);
1776 if (result < 0) {
1777 goto fail1;
1778 }
1779 }
1780
1781 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1782 if (obj == NULL) {
1783 goto fail1;
1784 } else if (obj != Py_None) {
1785 result = PyDict_SetItemString(retval, "caIssuers", obj);
1786 Py_DECREF(obj);
1787 if (result < 0) {
1788 goto fail1;
1789 }
1790 }
1791
1792 /* CDP (CRL distribution points) */
1793 obj = _get_crl_dp(certificate);
1794 if (obj == NULL) {
1795 goto fail1;
1796 } else if (obj != Py_None) {
1797 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1798 Py_DECREF(obj);
1799 if (result < 0) {
1800 goto fail1;
1801 }
1802 }
1803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 BIO_free(biobuf);
1805 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001806
1807 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 if (biobuf != NULL)
1809 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001810 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 Py_XDECREF(retval);
1812 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001813}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001814
Christian Heimes9a5395a2013-06-17 15:44:12 +02001815static PyObject *
1816_certificate_to_der(X509 *certificate)
1817{
1818 unsigned char *bytes_buf = NULL;
1819 int len;
1820 PyObject *retval;
1821
1822 bytes_buf = NULL;
1823 len = i2d_X509(certificate, &bytes_buf);
1824 if (len < 0) {
1825 _setSSLError(NULL, 0, __FILE__, __LINE__);
1826 return NULL;
1827 }
1828 /* this is actually an immutable bytes sequence */
1829 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1830 OPENSSL_free(bytes_buf);
1831 return retval;
1832}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001833
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001834/*[clinic input]
1835_ssl._test_decode_cert
1836 path: object(converter="PyUnicode_FSConverter")
1837 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001838
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001839[clinic start generated code]*/
1840
1841static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001842_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1843/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001844{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001846 X509 *x=NULL;
1847 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1850 PyErr_SetString(PySSLErrorObject,
1851 "Can't malloc memory to read file");
1852 goto fail0;
1853 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001854
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001855 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 PyErr_SetString(PySSLErrorObject,
1857 "Can't open file");
1858 goto fail0;
1859 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001860
Alex Gaynor40dad952019-08-15 08:31:28 -04001861 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 if (x == NULL) {
1863 PyErr_SetString(PySSLErrorObject,
1864 "Error decoding PEM-encoded file");
1865 goto fail0;
1866 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867
Antoine Pitroufb046912010-11-09 20:21:19 +00001868 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001869 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001870
1871 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001872 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 if (cert != NULL) BIO_free(cert);
1874 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001875}
1876
1877
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001878/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001879_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001880 der as binary_mode: bool = False
1881 /
1882
1883Returns the certificate for the peer.
1884
1885If no certificate was provided, returns None. If a certificate was
1886provided, but not validated, returns an empty dictionary. Otherwise
1887returns a dict containing information about the peer certificate.
1888
1889If the optional argument is True, returns a DER-encoded copy of the
1890peer certificate, or None if no certificate was provided. This will
1891return the certificate even if it wasn't validated.
1892[clinic start generated code]*/
1893
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001894static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001895_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1896/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001897{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001899 X509 *peer_cert;
1900 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001901
Christian Heimes66dc33b2017-05-23 16:02:02 -07001902 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001903 PyErr_SetString(PyExc_ValueError,
1904 "handshake not done yet");
1905 return NULL;
1906 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001907 peer_cert = SSL_get_peer_certificate(self->ssl);
1908 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001910
Antoine Pitrou721738f2012-08-15 23:20:39 +02001911 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001912 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001913 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001915 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001917 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001919 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001921 X509_free(peer_cert);
1922 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001923}
1924
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001925static PyObject *
1926cipher_to_tuple(const SSL_CIPHER *cipher)
1927{
1928 const char *cipher_name, *cipher_protocol;
1929 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001930 if (retval == NULL)
1931 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001932
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001933 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001935 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 PyTuple_SET_ITEM(retval, 0, Py_None);
1937 } else {
1938 v = PyUnicode_FromString(cipher_name);
1939 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001940 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 PyTuple_SET_ITEM(retval, 0, v);
1942 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001943
1944 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001946 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001947 PyTuple_SET_ITEM(retval, 1, Py_None);
1948 } else {
1949 v = PyUnicode_FromString(cipher_protocol);
1950 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001951 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001952 PyTuple_SET_ITEM(retval, 1, v);
1953 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001954
1955 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001956 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001957 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001959
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001961
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001962 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001963 Py_DECREF(retval);
1964 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001965}
1966
Christian Heimes25bfcd52016-09-06 00:04:45 +02001967#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1968static PyObject *
1969cipher_to_dict(const SSL_CIPHER *cipher)
1970{
1971 const char *cipher_name, *cipher_protocol;
1972
1973 unsigned long cipher_id;
1974 int alg_bits, strength_bits, len;
1975 char buf[512] = {0};
1976#if OPENSSL_VERSION_1_1
1977 int aead, nid;
1978 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1979#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001980
1981 /* can be NULL */
1982 cipher_name = SSL_CIPHER_get_name(cipher);
1983 cipher_protocol = SSL_CIPHER_get_version(cipher);
1984 cipher_id = SSL_CIPHER_get_id(cipher);
1985 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001986 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1987 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001988 if (len > 1 && buf[len-1] == '\n')
1989 buf[len-1] = '\0';
1990 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1991
1992#if OPENSSL_VERSION_1_1
1993 aead = SSL_CIPHER_is_aead(cipher);
1994 nid = SSL_CIPHER_get_cipher_nid(cipher);
1995 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1996 nid = SSL_CIPHER_get_digest_nid(cipher);
1997 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1998 nid = SSL_CIPHER_get_kx_nid(cipher);
1999 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2000 nid = SSL_CIPHER_get_auth_nid(cipher);
2001 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
2002#endif
2003
Victor Stinner410b9882016-09-12 12:00:23 +02002004 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02002005 "{sksssssssisi"
2006#if OPENSSL_VERSION_1_1
2007 "sOssssssss"
2008#endif
2009 "}",
2010 "id", cipher_id,
2011 "name", cipher_name,
2012 "protocol", cipher_protocol,
2013 "description", buf,
2014 "strength_bits", strength_bits,
2015 "alg_bits", alg_bits
2016#if OPENSSL_VERSION_1_1
2017 ,"aead", aead ? Py_True : Py_False,
2018 "symmetric", skcipher,
2019 "digest", digest,
2020 "kea", kx,
2021 "auth", auth
2022#endif
2023 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02002024}
2025#endif
2026
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002027/*[clinic input]
2028_ssl._SSLSocket.shared_ciphers
2029[clinic start generated code]*/
2030
2031static PyObject *
2032_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
2033/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002034{
2035 STACK_OF(SSL_CIPHER) *ciphers;
2036 int i;
2037 PyObject *res;
2038
Christian Heimes598894f2016-09-05 23:19:05 +02002039 ciphers = SSL_get_ciphers(self->ssl);
2040 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002041 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002042 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2043 if (!res)
2044 return NULL;
2045 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2046 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2047 if (!tup) {
2048 Py_DECREF(res);
2049 return NULL;
2050 }
2051 PyList_SET_ITEM(res, i, tup);
2052 }
2053 return res;
2054}
2055
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002056/*[clinic input]
2057_ssl._SSLSocket.cipher
2058[clinic start generated code]*/
2059
2060static PyObject *
2061_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2062/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002063{
2064 const SSL_CIPHER *current;
2065
2066 if (self->ssl == NULL)
2067 Py_RETURN_NONE;
2068 current = SSL_get_current_cipher(self->ssl);
2069 if (current == NULL)
2070 Py_RETURN_NONE;
2071 return cipher_to_tuple(current);
2072}
2073
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002074/*[clinic input]
2075_ssl._SSLSocket.version
2076[clinic start generated code]*/
2077
2078static PyObject *
2079_ssl__SSLSocket_version_impl(PySSLSocket *self)
2080/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002081{
2082 const char *version;
2083
2084 if (self->ssl == NULL)
2085 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002086 if (!SSL_is_init_finished(self->ssl)) {
2087 /* handshake not finished */
2088 Py_RETURN_NONE;
2089 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002090 version = SSL_get_version(self->ssl);
2091 if (!strcmp(version, "unknown"))
2092 Py_RETURN_NONE;
2093 return PyUnicode_FromString(version);
2094}
2095
Christian Heimes29eab552018-02-25 12:31:33 +01002096#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002097/*[clinic input]
2098_ssl._SSLSocket.selected_npn_protocol
2099[clinic start generated code]*/
2100
2101static PyObject *
2102_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2103/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2104{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002105 const unsigned char *out;
2106 unsigned int outlen;
2107
Victor Stinner4569cd52013-06-23 14:58:43 +02002108 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002109 &out, &outlen);
2110
2111 if (out == NULL)
2112 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002113 return PyUnicode_FromStringAndSize((char *)out, outlen);
2114}
2115#endif
2116
Christian Heimes29eab552018-02-25 12:31:33 +01002117#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002118/*[clinic input]
2119_ssl._SSLSocket.selected_alpn_protocol
2120[clinic start generated code]*/
2121
2122static PyObject *
2123_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2124/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2125{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002126 const unsigned char *out;
2127 unsigned int outlen;
2128
2129 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2130
2131 if (out == NULL)
2132 Py_RETURN_NONE;
2133 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002134}
2135#endif
2136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002137/*[clinic input]
2138_ssl._SSLSocket.compression
2139[clinic start generated code]*/
2140
2141static PyObject *
2142_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2143/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2144{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002145#ifdef OPENSSL_NO_COMP
2146 Py_RETURN_NONE;
2147#else
2148 const COMP_METHOD *comp_method;
2149 const char *short_name;
2150
2151 if (self->ssl == NULL)
2152 Py_RETURN_NONE;
2153 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002154 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002155 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002156 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002157 if (short_name == NULL)
2158 Py_RETURN_NONE;
2159 return PyUnicode_DecodeFSDefault(short_name);
2160#endif
2161}
2162
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002163static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2164 Py_INCREF(self->ctx);
2165 return self->ctx;
2166}
2167
2168static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2169 void *closure) {
2170
2171 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002172#if !HAVE_SNI
2173 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2174 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002175 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002176#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002177 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002178 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002179 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002180#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002181 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002182 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002183 return -1;
2184 }
2185
2186 return 0;
2187}
2188
2189PyDoc_STRVAR(PySSL_set_context_doc,
2190"_setter_context(ctx)\n\
2191\
2192This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002193used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002194on the SSLContext to change the certificate information associated with the\n\
2195SSLSocket before the cryptographic exchange handshake messages\n");
2196
2197
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198static PyObject *
2199PySSL_get_server_side(PySSLSocket *self, void *c)
2200{
2201 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2202}
2203
2204PyDoc_STRVAR(PySSL_get_server_side_doc,
2205"Whether this is a server-side socket.");
2206
2207static PyObject *
2208PySSL_get_server_hostname(PySSLSocket *self, void *c)
2209{
2210 if (self->server_hostname == NULL)
2211 Py_RETURN_NONE;
2212 Py_INCREF(self->server_hostname);
2213 return self->server_hostname;
2214}
2215
2216PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2217"The currently set server hostname (for SNI).");
2218
2219static PyObject *
2220PySSL_get_owner(PySSLSocket *self, void *c)
2221{
2222 PyObject *owner;
2223
2224 if (self->owner == NULL)
2225 Py_RETURN_NONE;
2226
2227 owner = PyWeakref_GetObject(self->owner);
2228 Py_INCREF(owner);
2229 return owner;
2230}
2231
2232static int
2233PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2234{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002235 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002236 if (self->owner == NULL)
2237 return -1;
2238 return 0;
2239}
2240
2241PyDoc_STRVAR(PySSL_get_owner_doc,
2242"The Python-level owner of this object.\
2243Passed as \"self\" in servername callback.");
2244
Christian Heimesc7f70692019-05-31 11:44:05 +02002245static int
2246PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2247{
2248 Py_VISIT(self->exc_type);
2249 Py_VISIT(self->exc_value);
2250 Py_VISIT(self->exc_tb);
2251 return 0;
2252}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002253
Christian Heimesc7f70692019-05-31 11:44:05 +02002254static int
2255PySSL_clear(PySSLSocket *self)
2256{
2257 Py_CLEAR(self->exc_type);
2258 Py_CLEAR(self->exc_value);
2259 Py_CLEAR(self->exc_tb);
2260 return 0;
2261}
2262
2263static void
2264PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002265{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 if (self->ssl)
2267 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002269 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002270 Py_XDECREF(self->server_hostname);
2271 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002273}
2274
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002275/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002276 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002277 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002278 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002279
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002280static int
Victor Stinner14690702015-04-06 22:46:13 +02002281PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002282{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002283 int rc;
2284#ifdef HAVE_POLL
2285 struct pollfd pollfd;
2286 _PyTime_t ms;
2287#else
2288 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 fd_set fds;
2290 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002291#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002294 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002296 else if (timeout < 0) {
2297 if (s->sock_timeout > 0)
2298 return SOCKET_HAS_TIMED_OUT;
2299 else
2300 return SOCKET_IS_BLOCKING;
2301 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002304 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002306
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002307 /* Prefer poll, if available, since you can poll() any fd
2308 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002309#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002310 pollfd.fd = s->sock_fd;
2311 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002312
Victor Stinner14690702015-04-06 22:46:13 +02002313 /* timeout is in seconds, poll() uses milliseconds */
2314 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002315 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002316
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002317 PySSL_BEGIN_ALLOW_THREADS
2318 rc = poll(&pollfd, 1, (int)ms);
2319 PySSL_END_ALLOW_THREADS
2320#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002322 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002324
Victor Stinner14690702015-04-06 22:46:13 +02002325 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002326
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002327 FD_ZERO(&fds);
2328 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002329
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002330 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002332 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002334 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002336 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002338#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2341 (when we are able to write or when there's something to read) */
2342 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002343}
2344
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002345/*[clinic input]
2346_ssl._SSLSocket.write
2347 b: Py_buffer
2348 /
2349
2350Writes the bytes-like object b into the SSL object.
2351
2352Returns the number of bytes written.
2353[clinic start generated code]*/
2354
2355static PyObject *
2356_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2357/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002358{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 int len;
2360 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002361 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002362 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002363 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002364 _PyTime_t timeout, deadline = 0;
2365 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002366
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002367 if (sock != NULL) {
2368 if (((PyObject*)sock) == Py_None) {
2369 _setSSLError("Underlying socket connection gone",
2370 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2371 return NULL;
2372 }
2373 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 }
2375
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002376 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002377 PyErr_Format(PyExc_OverflowError,
2378 "string longer than %d bytes", INT_MAX);
2379 goto error;
2380 }
2381
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002382 if (sock != NULL) {
2383 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002384 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002385 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2386 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2387 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388
Victor Stinner14690702015-04-06 22:46:13 +02002389 timeout = GET_SOCKET_TIMEOUT(sock);
2390 has_timeout = (timeout > 0);
2391 if (has_timeout)
2392 deadline = _PyTime_GetMonotonicClock() + timeout;
2393
2394 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002395 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002396 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397 "The write operation timed out");
2398 goto error;
2399 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2400 PyErr_SetString(PySSLErrorObject,
2401 "Underlying socket has been closed.");
2402 goto error;
2403 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2404 PyErr_SetString(PySSLErrorObject,
2405 "Underlying socket too large for select().");
2406 goto error;
2407 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002409 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002411 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002412 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002414 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002415
2416 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002418
Victor Stinner14690702015-04-06 22:46:13 +02002419 if (has_timeout)
2420 timeout = deadline - _PyTime_GetMonotonicClock();
2421
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002422 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002423 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002424 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002425 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 } else {
2427 sockstate = SOCKET_OPERATION_OK;
2428 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002431 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 "The write operation timed out");
2433 goto error;
2434 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2435 PyErr_SetString(PySSLErrorObject,
2436 "Underlying socket has been closed.");
2437 goto error;
2438 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2439 break;
2440 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002441 } while (err.ssl == SSL_ERROR_WANT_READ ||
2442 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002443
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002444 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002445 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002447 if (PySSL_ChainExceptions(self) < 0)
2448 return NULL;
2449 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002450error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002451 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002452 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002454}
2455
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002456/*[clinic input]
2457_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002458
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002459Returns the number of already decrypted bytes available for read, pending on the connection.
2460[clinic start generated code]*/
2461
2462static PyObject *
2463_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2464/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002465{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002467 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002469 PySSL_BEGIN_ALLOW_THREADS
2470 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002471 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002473 self->err = err;
2474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 if (count < 0)
2476 return PySSL_SetError(self, count, __FILE__, __LINE__);
2477 else
2478 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002479}
2480
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002481/*[clinic input]
2482_ssl._SSLSocket.read
2483 size as len: int
2484 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002485 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002486 ]
2487 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002489Read up to size bytes from the SSL socket.
2490[clinic start generated code]*/
2491
2492static PyObject *
2493_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2494 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002495/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002496{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002498 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002499 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002501 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002502 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002503 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002504 _PyTime_t timeout, deadline = 0;
2505 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002506
Martin Panter5503d472016-03-27 05:35:19 +00002507 if (!group_right_1 && len < 0) {
2508 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2509 return NULL;
2510 }
2511
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002512 if (sock != NULL) {
2513 if (((PyObject*)sock) == Py_None) {
2514 _setSSLError("Underlying socket connection gone",
2515 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2516 return NULL;
2517 }
2518 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519 }
2520
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002521 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002522 dest = PyBytes_FromStringAndSize(NULL, len);
2523 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002524 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002525 if (len == 0) {
2526 Py_XDECREF(sock);
2527 return dest;
2528 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002529 mem = PyBytes_AS_STRING(dest);
2530 }
2531 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002532 mem = buffer->buf;
2533 if (len <= 0 || len > buffer->len) {
2534 len = (int) buffer->len;
2535 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002536 PyErr_SetString(PyExc_OverflowError,
2537 "maximum length can't fit in a C 'int'");
2538 goto error;
2539 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002540 if (len == 0) {
2541 count = 0;
2542 goto done;
2543 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002544 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 }
2546
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002547 if (sock != NULL) {
2548 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002549 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002550 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2551 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2552 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553
Victor Stinner14690702015-04-06 22:46:13 +02002554 timeout = GET_SOCKET_TIMEOUT(sock);
2555 has_timeout = (timeout > 0);
2556 if (has_timeout)
2557 deadline = _PyTime_GetMonotonicClock() + timeout;
2558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 PySSL_BEGIN_ALLOW_THREADS
2561 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002562 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002564 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002565
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002566 if (PyErr_CheckSignals())
2567 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002568
Victor Stinner14690702015-04-06 22:46:13 +02002569 if (has_timeout)
2570 timeout = deadline - _PyTime_GetMonotonicClock();
2571
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002572 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002573 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002574 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002575 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002576 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002577 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002578 {
2579 count = 0;
2580 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002582 else
2583 sockstate = SOCKET_OPERATION_OK;
2584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002586 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002587 "The read operation timed out");
2588 goto error;
2589 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2590 break;
2591 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002592 } while (err.ssl == SSL_ERROR_WANT_READ ||
2593 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002594
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002595 if (count <= 0) {
2596 PySSL_SetError(self, count, __FILE__, __LINE__);
2597 goto error;
2598 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002599 if (self->exc_type != NULL)
2600 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002601
2602done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002603 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002604 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002605 _PyBytes_Resize(&dest, count);
2606 return dest;
2607 }
2608 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002609 return PyLong_FromLong(count);
2610 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002611
2612error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002613 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002614 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002615 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002616 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002617 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002618}
2619
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002620/*[clinic input]
2621_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002622
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002623Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002624[clinic start generated code]*/
2625
2626static PyObject *
2627_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002628/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002629{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002630 _PySSLError err;
2631 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002632 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002633 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002634 _PyTime_t timeout, deadline = 0;
2635 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002636
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002637 if (sock != NULL) {
2638 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002639 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002640 _setSSLError("Underlying socket connection gone",
2641 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2642 return NULL;
2643 }
2644 Py_INCREF(sock);
2645
2646 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002647 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002648 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2649 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002650 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002651
Victor Stinner14690702015-04-06 22:46:13 +02002652 timeout = GET_SOCKET_TIMEOUT(sock);
2653 has_timeout = (timeout > 0);
2654 if (has_timeout)
2655 deadline = _PyTime_GetMonotonicClock() + timeout;
2656
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002657 while (1) {
2658 PySSL_BEGIN_ALLOW_THREADS
2659 /* Disable read-ahead so that unwrap can work correctly.
2660 * Otherwise OpenSSL might read in too much data,
2661 * eating clear text data that happens to be
2662 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002663 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002664 * function is used and the shutdown_seen_zero != 0
2665 * condition is met.
2666 */
2667 if (self->shutdown_seen_zero)
2668 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002669 ret = SSL_shutdown(self->ssl);
2670 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002671 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002672 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002674 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002675 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002676 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002677 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002678 /* Don't loop endlessly; instead preserve legacy
2679 behaviour of trying SSL_shutdown() only twice.
2680 This looks necessary for OpenSSL < 0.9.8m */
2681 if (++zeros > 1)
2682 break;
2683 /* Shutdown was sent, now try receiving */
2684 self->shutdown_seen_zero = 1;
2685 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002686 }
2687
Victor Stinner14690702015-04-06 22:46:13 +02002688 if (has_timeout)
2689 timeout = deadline - _PyTime_GetMonotonicClock();
2690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002691 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002692 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002693 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002694 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002695 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002696 else
2697 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002699 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002700 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002701 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002702 "The read operation timed out");
2703 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002704 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002705 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002706 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002707 }
2708 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2709 PyErr_SetString(PySSLErrorObject,
2710 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002711 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002712 }
2713 else if (sockstate != SOCKET_OPERATION_OK)
2714 /* Retain the SSL error code */
2715 break;
2716 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002717 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002718 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002719 PySSL_SetError(self, ret, __FILE__, __LINE__);
2720 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002721 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002722 if (self->exc_type != NULL)
2723 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002724 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002725 /* It's already INCREF'ed */
2726 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002727 else
2728 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002729
2730error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002731 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002732 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002733 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002734}
2735
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002736/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002737_ssl._SSLSocket.get_channel_binding
2738 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002739
Christian Heimes141c5e82018-02-24 21:10:57 +01002740Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002741
Christian Heimes141c5e82018-02-24 21:10:57 +01002742Raise ValueError if the requested `cb_type` is not supported. Return bytes
2743of the data or None if the data is not available (e.g. before the handshake).
2744Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002745[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002746
Antoine Pitroud6494802011-07-21 01:11:30 +02002747static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002748_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2749 const char *cb_type)
2750/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002751{
Antoine Pitroud6494802011-07-21 01:11:30 +02002752 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002753 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002754
Christian Heimes141c5e82018-02-24 21:10:57 +01002755 if (strcmp(cb_type, "tls-unique") == 0) {
2756 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2757 /* if session is resumed XOR we are the client */
2758 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2759 }
2760 else {
2761 /* if a new session XOR we are the server */
2762 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2763 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002764 }
2765 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002766 PyErr_Format(
2767 PyExc_ValueError,
2768 "'%s' channel binding type not implemented",
2769 cb_type
2770 );
2771 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002772 }
2773
2774 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002775 if (len == 0)
2776 Py_RETURN_NONE;
2777
Christian Heimes141c5e82018-02-24 21:10:57 +01002778 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002779}
2780
Christian Heimes9fb051f2018-09-23 08:32:31 +02002781/*[clinic input]
2782_ssl._SSLSocket.verify_client_post_handshake
2783
2784Initiate TLS 1.3 post-handshake authentication
2785[clinic start generated code]*/
2786
2787static PyObject *
2788_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2789/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2790{
2791#ifdef TLS1_3_VERSION
2792 int err = SSL_verify_client_post_handshake(self->ssl);
2793 if (err == 0)
2794 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2795 else
2796 Py_RETURN_NONE;
2797#else
2798 PyErr_SetString(PyExc_NotImplementedError,
2799 "Post-handshake auth is not supported by your "
2800 "OpenSSL version.");
2801 return NULL;
2802#endif
2803}
2804
Christian Heimes99a65702016-09-10 23:44:53 +02002805#ifdef OPENSSL_VERSION_1_1
2806
2807static SSL_SESSION*
2808_ssl_session_dup(SSL_SESSION *session) {
2809 SSL_SESSION *newsession = NULL;
2810 int slen;
2811 unsigned char *senc = NULL, *p;
2812 const unsigned char *const_p;
2813
2814 if (session == NULL) {
2815 PyErr_SetString(PyExc_ValueError, "Invalid session");
2816 goto error;
2817 }
2818
2819 /* get length */
2820 slen = i2d_SSL_SESSION(session, NULL);
2821 if (slen == 0 || slen > 0xFF00) {
2822 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2823 goto error;
2824 }
2825 if ((senc = PyMem_Malloc(slen)) == NULL) {
2826 PyErr_NoMemory();
2827 goto error;
2828 }
2829 p = senc;
2830 if (!i2d_SSL_SESSION(session, &p)) {
2831 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2832 goto error;
2833 }
2834 const_p = senc;
2835 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2836 if (session == NULL) {
2837 goto error;
2838 }
2839 PyMem_Free(senc);
2840 return newsession;
2841 error:
2842 if (senc != NULL) {
2843 PyMem_Free(senc);
2844 }
2845 return NULL;
2846}
2847#endif
2848
2849static PyObject *
2850PySSL_get_session(PySSLSocket *self, void *closure) {
2851 /* get_session can return sessions from a server-side connection,
2852 * it does not check for handshake done or client socket. */
2853 PySSLSession *pysess;
2854 SSL_SESSION *session;
2855
2856#ifdef OPENSSL_VERSION_1_1
2857 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2858 * https://github.com/openssl/openssl/issues/1550 */
2859 session = SSL_get0_session(self->ssl); /* borrowed reference */
2860 if (session == NULL) {
2861 Py_RETURN_NONE;
2862 }
2863 if ((session = _ssl_session_dup(session)) == NULL) {
2864 return NULL;
2865 }
2866#else
2867 session = SSL_get1_session(self->ssl);
2868 if (session == NULL) {
2869 Py_RETURN_NONE;
2870 }
2871#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002872 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002873 if (pysess == NULL) {
2874 SSL_SESSION_free(session);
2875 return NULL;
2876 }
2877
2878 assert(self->ctx);
2879 pysess->ctx = self->ctx;
2880 Py_INCREF(pysess->ctx);
2881 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002882 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002883 return (PyObject *)pysess;
2884}
2885
2886static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2887 void *closure)
2888 {
2889 PySSLSession *pysess;
2890#ifdef OPENSSL_VERSION_1_1
2891 SSL_SESSION *session;
2892#endif
2893 int result;
2894
2895 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002896 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002897 return -1;
2898 }
2899 pysess = (PySSLSession *)value;
2900
2901 if (self->ctx->ctx != pysess->ctx->ctx) {
2902 PyErr_SetString(PyExc_ValueError,
2903 "Session refers to a different SSLContext.");
2904 return -1;
2905 }
2906 if (self->socket_type != PY_SSL_CLIENT) {
2907 PyErr_SetString(PyExc_ValueError,
2908 "Cannot set session for server-side SSLSocket.");
2909 return -1;
2910 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002911 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002912 PyErr_SetString(PyExc_ValueError,
2913 "Cannot set session after handshake.");
2914 return -1;
2915 }
2916#ifdef OPENSSL_VERSION_1_1
2917 /* duplicate session */
2918 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2919 return -1;
2920 }
2921 result = SSL_set_session(self->ssl, session);
2922 /* free duplicate, SSL_set_session() bumps ref count */
2923 SSL_SESSION_free(session);
2924#else
2925 result = SSL_set_session(self->ssl, pysess->session);
2926#endif
2927 if (result == 0) {
2928 _setSSLError(NULL, 0, __FILE__, __LINE__);
2929 return -1;
2930 }
2931 return 0;
2932}
2933
2934PyDoc_STRVAR(PySSL_set_session_doc,
2935"_setter_session(session)\n\
2936\
2937Get / set SSLSession.");
2938
2939static PyObject *
2940PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2941 if (SSL_session_reused(self->ssl)) {
2942 Py_RETURN_TRUE;
2943 } else {
2944 Py_RETURN_FALSE;
2945 }
2946}
2947
2948PyDoc_STRVAR(PySSL_get_session_reused_doc,
2949"Was the client session reused during handshake?");
2950
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002951static PyGetSetDef ssl_getsetlist[] = {
2952 {"context", (getter) PySSL_get_context,
2953 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002954 {"server_side", (getter) PySSL_get_server_side, NULL,
2955 PySSL_get_server_side_doc},
2956 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2957 PySSL_get_server_hostname_doc},
2958 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2959 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002960 {"session", (getter) PySSL_get_session,
2961 (setter) PySSL_set_session, PySSL_set_session_doc},
2962 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2963 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002964 {NULL}, /* sentinel */
2965};
2966
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002967static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002968 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2969 _SSL__SSLSOCKET_WRITE_METHODDEF
2970 _SSL__SSLSOCKET_READ_METHODDEF
2971 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002972 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2973 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002974 _SSL__SSLSOCKET_CIPHER_METHODDEF
2975 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2976 _SSL__SSLSOCKET_VERSION_METHODDEF
2977 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2978 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2979 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2980 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002981 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002982 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002983};
2984
Antoine Pitrou152efa22010-05-16 18:19:27 +00002985static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002986 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002987 "_ssl._SSLSocket", /*tp_name*/
2988 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002989 0, /*tp_itemsize*/
2990 /* methods */
2991 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002992 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002993 0, /*tp_getattr*/
2994 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002995 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002996 0, /*tp_repr*/
2997 0, /*tp_as_number*/
2998 0, /*tp_as_sequence*/
2999 0, /*tp_as_mapping*/
3000 0, /*tp_hash*/
3001 0, /*tp_call*/
3002 0, /*tp_str*/
3003 0, /*tp_getattro*/
3004 0, /*tp_setattro*/
3005 0, /*tp_as_buffer*/
3006 Py_TPFLAGS_DEFAULT, /*tp_flags*/
3007 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02003008 (traverseproc) PySSL_traverse, /*tp_traverse*/
3009 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00003010 0, /*tp_richcompare*/
3011 0, /*tp_weaklistoffset*/
3012 0, /*tp_iter*/
3013 0, /*tp_iternext*/
3014 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003015 0, /*tp_members*/
3016 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00003017};
3018
Antoine Pitrou152efa22010-05-16 18:19:27 +00003019
3020/*
3021 * _SSLContext objects
3022 */
3023
Christian Heimes5fe668c2016-09-12 00:01:11 +02003024static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02003025_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02003026{
3027 int mode;
3028 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3029
3030 switch(n) {
3031 case PY_SSL_CERT_NONE:
3032 mode = SSL_VERIFY_NONE;
3033 break;
3034 case PY_SSL_CERT_OPTIONAL:
3035 mode = SSL_VERIFY_PEER;
3036 break;
3037 case PY_SSL_CERT_REQUIRED:
3038 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3039 break;
3040 default:
3041 PyErr_SetString(PyExc_ValueError,
3042 "invalid value for verify_mode");
3043 return -1;
3044 }
Christian Heimesf0f59302019-07-01 08:29:17 +02003045
3046 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3047 * server sockets and SSL_set_post_handshake_auth() for client. */
3048
Christian Heimes5fe668c2016-09-12 00:01:11 +02003049 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003050 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3051 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003052 return 0;
3053}
3054
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003055/*[clinic input]
3056@classmethod
3057_ssl._SSLContext.__new__
3058 protocol as proto_version: int
3059 /
3060[clinic start generated code]*/
3061
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003063_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3064/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003065{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003066 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003067 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003068 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003069 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003070 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003071#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003072 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003073#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003074
Antoine Pitrou152efa22010-05-16 18:19:27 +00003075 PySSL_BEGIN_ALLOW_THREADS
Christian Heimes6e8cda92020-05-16 03:33:05 +02003076 switch(proto_version) {
3077#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
3078 case PY_SSL_VERSION_SSL3:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003079 ctx = SSL_CTX_new(SSLv3_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003080 break;
Benjamin Petersone32467c2014-12-05 21:59:35 -05003081#endif
Christian Heimes6e8cda92020-05-16 03:33:05 +02003082#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
3083 case PY_SSL_VERSION_TLS1:
3084 ctx = SSL_CTX_new(TLSv1_method());
3085 break;
Victor Stinner3de49192011-05-09 00:42:58 +02003086#endif
Christian Heimes6e8cda92020-05-16 03:33:05 +02003087#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
3088 case PY_SSL_VERSION_TLS1_1:
3089 ctx = SSL_CTX_new(TLSv1_1_method());
3090 break;
3091#endif
3092#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
3093 case PY_SSL_VERSION_TLS1_2:
3094 ctx = SSL_CTX_new(TLSv1_2_method());
3095 break;
3096#endif
3097 case PY_SSL_VERSION_TLS:
3098 /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003099 ctx = SSL_CTX_new(TLS_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003100 break;
3101 case PY_SSL_VERSION_TLS_CLIENT:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003102 ctx = SSL_CTX_new(TLS_client_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003103 break;
3104 case PY_SSL_VERSION_TLS_SERVER:
Christian Heimes5fe668c2016-09-12 00:01:11 +02003105 ctx = SSL_CTX_new(TLS_server_method());
Christian Heimes6e8cda92020-05-16 03:33:05 +02003106 break;
3107 default:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003108 proto_version = -1;
Christian Heimes6e8cda92020-05-16 03:33:05 +02003109 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003110 PySSL_END_ALLOW_THREADS
3111
3112 if (proto_version == -1) {
3113 PyErr_SetString(PyExc_ValueError,
Christian Heimes6e8cda92020-05-16 03:33:05 +02003114 "invalid or unsupported protocol version");
Antoine Pitrou152efa22010-05-16 18:19:27 +00003115 return NULL;
3116 }
3117 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003118 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003119 return NULL;
3120 }
3121
3122 assert(type != NULL && type->tp_alloc != NULL);
3123 self = (PySSLContext *) type->tp_alloc(type, 0);
3124 if (self == NULL) {
3125 SSL_CTX_free(ctx);
3126 return NULL;
3127 }
3128 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003129 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003130 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003131 self->msg_cb = NULL;
3132#ifdef HAVE_OPENSSL_KEYLOG
3133 self->keylog_filename = NULL;
3134 self->keylog_bio = NULL;
3135#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003136#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003137 self->npn_protocols = NULL;
3138#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003139#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003140 self->alpn_protocols = NULL;
3141#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003142#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003143 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003144#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003145 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003146 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3147 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003148 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003149 Py_DECREF(self);
3150 return NULL;
3151 }
3152 } else {
3153 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003154 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003155 Py_DECREF(self);
3156 return NULL;
3157 }
3158 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003159 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003160 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3161 if (proto_version != PY_SSL_VERSION_SSL2)
3162 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003163 if (proto_version != PY_SSL_VERSION_SSL3)
3164 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003165 /* Minimal security flags for server and client side context.
3166 * Client sockets ignore server-side parameters. */
3167#ifdef SSL_OP_NO_COMPRESSION
3168 options |= SSL_OP_NO_COMPRESSION;
3169#endif
3170#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3171 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3172#endif
3173#ifdef SSL_OP_SINGLE_DH_USE
3174 options |= SSL_OP_SINGLE_DH_USE;
3175#endif
3176#ifdef SSL_OP_SINGLE_ECDH_USE
3177 options |= SSL_OP_SINGLE_ECDH_USE;
3178#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003179 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003180
Semen Zhydenko1295e112017-10-15 21:28:31 +02003181 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003182 * It's far from perfect but gives users a better head start. */
3183 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003184#if PY_SSL_DEFAULT_CIPHERS == 2
3185 /* stick to OpenSSL's default settings */
3186 result = 1;
3187#else
3188 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3189#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003190 } else {
3191 /* SSLv2 needs MD5 */
3192 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3193 }
3194 if (result == 0) {
3195 Py_DECREF(self);
3196 ERR_clear_error();
3197 PyErr_SetString(PySSLErrorObject,
3198 "No cipher can be selected.");
3199 return NULL;
3200 }
3201
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003202#if defined(SSL_MODE_RELEASE_BUFFERS)
3203 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3204 usage for no cost at all. However, don't do this for OpenSSL versions
3205 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3206 2014-0198. I can't find exactly which beta fixed this CVE, so be
3207 conservative and assume it wasn't fixed until release. We do this check
3208 at runtime to avoid problems from the dynamic linker.
3209 See #25672 for more on this. */
3210 libver = SSLeay();
3211 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3212 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3213 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3214 }
3215#endif
3216
3217
Donald Stufft8ae264c2017-03-02 11:45:29 -05003218#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003219 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3220 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003221 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3222 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003223#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003224 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3225#else
3226 {
3227 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3228 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3229 EC_KEY_free(key);
3230 }
3231#endif
3232#endif
3233
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003234#define SID_CTX "Python"
3235 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3236 sizeof(SID_CTX));
3237#undef SID_CTX
3238
Christian Heimes61d478c2018-01-27 15:51:38 +01003239 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003240#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003241 /* Improve trust chain building when cross-signed intermediate
3242 certificates are present. See https://bugs.python.org/issue23476. */
3243 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003244#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003245 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003246
Christian Heimes9fb051f2018-09-23 08:32:31 +02003247#ifdef TLS1_3_VERSION
3248 self->post_handshake_auth = 0;
3249 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3250#endif
3251
Antoine Pitrou152efa22010-05-16 18:19:27 +00003252 return (PyObject *)self;
3253}
3254
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003255static int
3256context_traverse(PySSLContext *self, visitproc visit, void *arg)
3257{
3258#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003259 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003260#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003261 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003262 return 0;
3263}
3264
3265static int
3266context_clear(PySSLContext *self)
3267{
3268#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003269 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003270#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003271 Py_CLEAR(self->msg_cb);
3272#ifdef HAVE_OPENSSL_KEYLOG
3273 Py_CLEAR(self->keylog_filename);
3274 if (self->keylog_bio != NULL) {
3275 PySSL_BEGIN_ALLOW_THREADS
3276 BIO_free_all(self->keylog_bio);
3277 PySSL_END_ALLOW_THREADS
3278 self->keylog_bio = NULL;
3279 }
3280#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003281 return 0;
3282}
3283
Antoine Pitrou152efa22010-05-16 18:19:27 +00003284static void
3285context_dealloc(PySSLContext *self)
3286{
INADA Naokia6296d32017-08-24 14:55:17 +09003287 /* bpo-31095: UnTrack is needed before calling any callbacks */
3288 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003289 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003290 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003291#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003292 PyMem_FREE(self->npn_protocols);
3293#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003294#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003295 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003296#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003297 Py_TYPE(self)->tp_free(self);
3298}
3299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003300/*[clinic input]
3301_ssl._SSLContext.set_ciphers
3302 cipherlist: str
3303 /
3304[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003305
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003306static PyObject *
3307_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3308/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3309{
3310 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003311 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003312 /* Clearing the error queue is necessary on some OpenSSL versions,
3313 otherwise the error will be reported again when another SSL call
3314 is done. */
3315 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316 PyErr_SetString(PySSLErrorObject,
3317 "No cipher can be selected.");
3318 return NULL;
3319 }
3320 Py_RETURN_NONE;
3321}
3322
Christian Heimes25bfcd52016-09-06 00:04:45 +02003323#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3324/*[clinic input]
3325_ssl._SSLContext.get_ciphers
3326[clinic start generated code]*/
3327
3328static PyObject *
3329_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3330/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3331{
3332 SSL *ssl = NULL;
3333 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003334 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003335 int i=0;
3336 PyObject *result = NULL, *dct;
3337
3338 ssl = SSL_new(self->ctx);
3339 if (ssl == NULL) {
3340 _setSSLError(NULL, 0, __FILE__, __LINE__);
3341 goto exit;
3342 }
3343 sk = SSL_get_ciphers(ssl);
3344
3345 result = PyList_New(sk_SSL_CIPHER_num(sk));
3346 if (result == NULL) {
3347 goto exit;
3348 }
3349
3350 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3351 cipher = sk_SSL_CIPHER_value(sk, i);
3352 dct = cipher_to_dict(cipher);
3353 if (dct == NULL) {
3354 Py_CLEAR(result);
3355 goto exit;
3356 }
3357 PyList_SET_ITEM(result, i, dct);
3358 }
3359
3360 exit:
3361 if (ssl != NULL)
3362 SSL_free(ssl);
3363 return result;
3364
3365}
3366#endif
3367
3368
Christian Heimes29eab552018-02-25 12:31:33 +01003369#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003370static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003371do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3372 const unsigned char *server_protocols, unsigned int server_protocols_len,
3373 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003374{
Benjamin Peterson88615022015-01-23 17:30:26 -05003375 int ret;
3376 if (client_protocols == NULL) {
3377 client_protocols = (unsigned char *)"";
3378 client_protocols_len = 0;
3379 }
3380 if (server_protocols == NULL) {
3381 server_protocols = (unsigned char *)"";
3382 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003383 }
3384
Benjamin Peterson88615022015-01-23 17:30:26 -05003385 ret = SSL_select_next_proto(out, outlen,
3386 server_protocols, server_protocols_len,
3387 client_protocols, client_protocols_len);
3388 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3389 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003390
3391 return SSL_TLSEXT_ERR_OK;
3392}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003393#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003394
Christian Heimes29eab552018-02-25 12:31:33 +01003395#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003396/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3397static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003398_advertiseNPN_cb(SSL *s,
3399 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003400 void *args)
3401{
3402 PySSLContext *ssl_ctx = (PySSLContext *) args;
3403
3404 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003405 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003406 *len = 0;
3407 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003408 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003409 *len = ssl_ctx->npn_protocols_len;
3410 }
3411
3412 return SSL_TLSEXT_ERR_OK;
3413}
3414/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3415static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003416_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003417 unsigned char **out, unsigned char *outlen,
3418 const unsigned char *server, unsigned int server_len,
3419 void *args)
3420{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003421 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003422 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003423 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003424}
3425#endif
3426
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003427/*[clinic input]
3428_ssl._SSLContext._set_npn_protocols
3429 protos: Py_buffer
3430 /
3431[clinic start generated code]*/
3432
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003433static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003434_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3435 Py_buffer *protos)
3436/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003437{
Christian Heimes29eab552018-02-25 12:31:33 +01003438#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003439 PyMem_Free(self->npn_protocols);
3440 self->npn_protocols = PyMem_Malloc(protos->len);
3441 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003442 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003443 memcpy(self->npn_protocols, protos->buf, protos->len);
3444 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003445
3446 /* set both server and client callbacks, because the context can
3447 * be used to create both types of sockets */
3448 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3449 _advertiseNPN_cb,
3450 self);
3451 SSL_CTX_set_next_proto_select_cb(self->ctx,
3452 _selectNPN_cb,
3453 self);
3454
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003455 Py_RETURN_NONE;
3456#else
3457 PyErr_SetString(PyExc_NotImplementedError,
3458 "The NPN extension requires OpenSSL 1.0.1 or later.");
3459 return NULL;
3460#endif
3461}
3462
Christian Heimes29eab552018-02-25 12:31:33 +01003463#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003464static int
3465_selectALPN_cb(SSL *s,
3466 const unsigned char **out, unsigned char *outlen,
3467 const unsigned char *client_protocols, unsigned int client_protocols_len,
3468 void *args)
3469{
3470 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003471 return do_protocol_selection(1, (unsigned char **)out, outlen,
3472 ctx->alpn_protocols, ctx->alpn_protocols_len,
3473 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003474}
3475#endif
3476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003477/*[clinic input]
3478_ssl._SSLContext._set_alpn_protocols
3479 protos: Py_buffer
3480 /
3481[clinic start generated code]*/
3482
Benjamin Petersoncca27322015-01-23 16:35:37 -05003483static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003484_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3485 Py_buffer *protos)
3486/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003487{
Christian Heimes29eab552018-02-25 12:31:33 +01003488#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003489 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003490 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003491 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003492 return NULL;
3493 }
3494
Benjamin Petersoncca27322015-01-23 16:35:37 -05003495 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003496 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003497 if (!self->alpn_protocols)
3498 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003499 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003500 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003501
3502 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3503 return PyErr_NoMemory();
3504 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3505
Benjamin Petersoncca27322015-01-23 16:35:37 -05003506 Py_RETURN_NONE;
3507#else
3508 PyErr_SetString(PyExc_NotImplementedError,
3509 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3510 return NULL;
3511#endif
3512}
3513
Antoine Pitrou152efa22010-05-16 18:19:27 +00003514static PyObject *
3515get_verify_mode(PySSLContext *self, void *c)
3516{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003517 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3518 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3519 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3520 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003521 case SSL_VERIFY_NONE:
3522 return PyLong_FromLong(PY_SSL_CERT_NONE);
3523 case SSL_VERIFY_PEER:
3524 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3525 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3526 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3527 }
3528 PyErr_SetString(PySSLErrorObject,
3529 "invalid return value from SSL_CTX_get_verify_mode");
3530 return NULL;
3531}
3532
3533static int
3534set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3535{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003536 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003537 if (!PyArg_Parse(arg, "i", &n))
3538 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003539 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003540 PyErr_SetString(PyExc_ValueError,
3541 "Cannot set verify_mode to CERT_NONE when "
3542 "check_hostname is enabled.");
3543 return -1;
3544 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003545 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546}
3547
3548static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003549get_verify_flags(PySSLContext *self, void *c)
3550{
Christian Heimes598894f2016-09-05 23:19:05 +02003551 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003552 unsigned long flags;
3553
Christian Heimes61d478c2018-01-27 15:51:38 +01003554 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003555 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003556 return PyLong_FromUnsignedLong(flags);
3557}
3558
3559static int
3560set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3561{
Christian Heimes598894f2016-09-05 23:19:05 +02003562 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003563 unsigned long new_flags, flags, set, clear;
3564
3565 if (!PyArg_Parse(arg, "k", &new_flags))
3566 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003567 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003568 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003569 clear = flags & ~new_flags;
3570 set = ~flags & new_flags;
3571 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003572 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003573 _setSSLError(NULL, 0, __FILE__, __LINE__);
3574 return -1;
3575 }
3576 }
3577 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003578 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003579 _setSSLError(NULL, 0, __FILE__, __LINE__);
3580 return -1;
3581 }
3582 }
3583 return 0;
3584}
3585
Christian Heimes698dde12018-02-27 11:54:43 +01003586/* Getter and setter for protocol version */
3587#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3588
3589
3590static int
3591set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3592{
3593 long v;
3594 int result;
3595
3596 if (!PyArg_Parse(arg, "l", &v))
3597 return -1;
3598 if (v > INT_MAX) {
3599 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3600 return -1;
3601 }
3602
3603 switch(self->protocol) {
3604 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3605 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3606 case PY_SSL_VERSION_TLS:
3607 break;
3608 default:
3609 PyErr_SetString(
3610 PyExc_ValueError,
3611 "The context's protocol doesn't support modification of "
3612 "highest and lowest version."
3613 );
3614 return -1;
3615 }
3616
3617 if (what == 0) {
3618 switch(v) {
3619 case PY_PROTO_MINIMUM_SUPPORTED:
3620 v = 0;
3621 break;
3622 case PY_PROTO_MAXIMUM_SUPPORTED:
3623 /* Emulate max for set_min_proto_version */
3624 v = PY_PROTO_MAXIMUM_AVAILABLE;
3625 break;
3626 default:
3627 break;
3628 }
3629 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3630 }
3631 else {
3632 switch(v) {
3633 case PY_PROTO_MAXIMUM_SUPPORTED:
3634 v = 0;
3635 break;
3636 case PY_PROTO_MINIMUM_SUPPORTED:
3637 /* Emulate max for set_min_proto_version */
3638 v = PY_PROTO_MINIMUM_AVAILABLE;
3639 break;
3640 default:
3641 break;
3642 }
3643 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3644 }
3645 if (result == 0) {
3646 PyErr_Format(PyExc_ValueError,
3647 "Unsupported protocol version 0x%x", v);
3648 return -1;
3649 }
3650 return 0;
3651}
3652
3653static PyObject *
3654get_minimum_version(PySSLContext *self, void *c)
3655{
3656 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3657 if (v == 0) {
3658 v = PY_PROTO_MINIMUM_SUPPORTED;
3659 }
3660 return PyLong_FromLong(v);
3661}
3662
3663static int
3664set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3665{
3666 return set_min_max_proto_version(self, arg, 0);
3667}
3668
3669static PyObject *
3670get_maximum_version(PySSLContext *self, void *c)
3671{
3672 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3673 if (v == 0) {
3674 v = PY_PROTO_MAXIMUM_SUPPORTED;
3675 }
3676 return PyLong_FromLong(v);
3677}
3678
3679static int
3680set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3681{
3682 return set_min_max_proto_version(self, arg, 1);
3683}
3684#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3685
Christian Heimes78c7d522019-06-03 21:00:10 +02003686#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3687static PyObject *
3688get_num_tickets(PySSLContext *self, void *c)
3689{
Victor Stinner76611c72019-07-09 13:30:52 +02003690 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003691}
3692
3693static int
3694set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3695{
3696 long num;
3697 if (!PyArg_Parse(arg, "l", &num))
3698 return -1;
3699 if (num < 0) {
3700 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3701 return -1;
3702 }
3703 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3704 PyErr_SetString(PyExc_ValueError,
3705 "SSLContext is not a server context.");
3706 return -1;
3707 }
3708 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3709 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3710 return -1;
3711 }
3712 return 0;
3713}
3714
3715PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3716"Control the number of TLSv1.3 session tickets");
3717#endif /* OpenSSL 1.1.1 */
3718
Christian Heimes22587792013-11-21 23:56:13 +01003719static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003720get_options(PySSLContext *self, void *c)
3721{
3722 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3723}
3724
3725static int
3726set_options(PySSLContext *self, PyObject *arg, void *c)
3727{
3728 long new_opts, opts, set, clear;
3729 if (!PyArg_Parse(arg, "l", &new_opts))
3730 return -1;
3731 opts = SSL_CTX_get_options(self->ctx);
3732 clear = opts & ~new_opts;
3733 set = ~opts & new_opts;
3734 if (clear) {
3735#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3736 SSL_CTX_clear_options(self->ctx, clear);
3737#else
3738 PyErr_SetString(PyExc_ValueError,
3739 "can't clear options before OpenSSL 0.9.8m");
3740 return -1;
3741#endif
3742 }
3743 if (set)
3744 SSL_CTX_set_options(self->ctx, set);
3745 return 0;
3746}
3747
Christian Heimes1aa9a752013-12-02 02:41:19 +01003748static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003749get_host_flags(PySSLContext *self, void *c)
3750{
3751 return PyLong_FromUnsignedLong(self->hostflags);
3752}
3753
3754static int
3755set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3756{
3757 X509_VERIFY_PARAM *param;
3758 unsigned int new_flags = 0;
3759
3760 if (!PyArg_Parse(arg, "I", &new_flags))
3761 return -1;
3762
3763 param = SSL_CTX_get0_param(self->ctx);
3764 self->hostflags = new_flags;
3765 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3766 return 0;
3767}
3768
3769static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003770get_check_hostname(PySSLContext *self, void *c)
3771{
3772 return PyBool_FromLong(self->check_hostname);
3773}
3774
3775static int
3776set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3777{
3778 int check_hostname;
3779 if (!PyArg_Parse(arg, "p", &check_hostname))
3780 return -1;
3781 if (check_hostname &&
3782 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003783 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003784 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003785 return -1;
3786 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003787 }
3788 self->check_hostname = check_hostname;
3789 return 0;
3790}
3791
Christian Heimes11a14932018-02-24 02:35:08 +01003792static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003793get_post_handshake_auth(PySSLContext *self, void *c) {
3794#if TLS1_3_VERSION
3795 return PyBool_FromLong(self->post_handshake_auth);
3796#else
3797 Py_RETURN_NONE;
3798#endif
3799}
3800
3801#if TLS1_3_VERSION
3802static int
3803set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003804 if (arg == NULL) {
3805 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3806 return -1;
3807 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003808 int pha = PyObject_IsTrue(arg);
3809
3810 if (pha == -1) {
3811 return -1;
3812 }
3813 self->post_handshake_auth = pha;
3814
Christian Heimesf0f59302019-07-01 08:29:17 +02003815 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3816 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003817
3818 return 0;
3819}
3820#endif
3821
3822static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003823get_protocol(PySSLContext *self, void *c) {
3824 return PyLong_FromLong(self->protocol);
3825}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003826
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003827typedef struct {
3828 PyThreadState *thread_state;
3829 PyObject *callable;
3830 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003831 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003832 int error;
3833} _PySSLPasswordInfo;
3834
3835static int
3836_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3837 const char *bad_type_error)
3838{
3839 /* Set the password and size fields of a _PySSLPasswordInfo struct
3840 from a unicode, bytes, or byte array object.
3841 The password field will be dynamically allocated and must be freed
3842 by the caller */
3843 PyObject *password_bytes = NULL;
3844 const char *data = NULL;
3845 Py_ssize_t size;
3846
3847 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003848 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003849 if (!password_bytes) {
3850 goto error;
3851 }
3852 data = PyBytes_AS_STRING(password_bytes);
3853 size = PyBytes_GET_SIZE(password_bytes);
3854 } else if (PyBytes_Check(password)) {
3855 data = PyBytes_AS_STRING(password);
3856 size = PyBytes_GET_SIZE(password);
3857 } else if (PyByteArray_Check(password)) {
3858 data = PyByteArray_AS_STRING(password);
3859 size = PyByteArray_GET_SIZE(password);
3860 } else {
3861 PyErr_SetString(PyExc_TypeError, bad_type_error);
3862 goto error;
3863 }
3864
Victor Stinner9ee02032013-06-23 15:08:23 +02003865 if (size > (Py_ssize_t)INT_MAX) {
3866 PyErr_Format(PyExc_ValueError,
3867 "password cannot be longer than %d bytes", INT_MAX);
3868 goto error;
3869 }
3870
Victor Stinner11ebff22013-07-07 17:07:52 +02003871 PyMem_Free(pw_info->password);
3872 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003873 if (!pw_info->password) {
3874 PyErr_SetString(PyExc_MemoryError,
3875 "unable to allocate password buffer");
3876 goto error;
3877 }
3878 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003879 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003880
3881 Py_XDECREF(password_bytes);
3882 return 1;
3883
3884error:
3885 Py_XDECREF(password_bytes);
3886 return 0;
3887}
3888
3889static int
3890_password_callback(char *buf, int size, int rwflag, void *userdata)
3891{
3892 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3893 PyObject *fn_ret = NULL;
3894
3895 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3896
3897 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003898 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003899 if (!fn_ret) {
3900 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3901 core python API, so we could use it to add a frame here */
3902 goto error;
3903 }
3904
3905 if (!_pwinfo_set(pw_info, fn_ret,
3906 "password callback must return a string")) {
3907 goto error;
3908 }
3909 Py_CLEAR(fn_ret);
3910 }
3911
3912 if (pw_info->size > size) {
3913 PyErr_Format(PyExc_ValueError,
3914 "password cannot be longer than %d bytes", size);
3915 goto error;
3916 }
3917
3918 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3919 memcpy(buf, pw_info->password, pw_info->size);
3920 return pw_info->size;
3921
3922error:
3923 Py_XDECREF(fn_ret);
3924 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3925 pw_info->error = 1;
3926 return -1;
3927}
3928
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003929/*[clinic input]
3930_ssl._SSLContext.load_cert_chain
3931 certfile: object
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003932 keyfile: object = None
3933 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003934
3935[clinic start generated code]*/
3936
Antoine Pitroub5218772010-05-21 09:56:06 +00003937static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003938_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3939 PyObject *keyfile, PyObject *password)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003940/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003941{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003942 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003943 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3944 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003945 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003946 int r;
3947
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003948 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003949 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003950 if (keyfile == Py_None)
3951 keyfile = NULL;
3952 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003953 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3954 PyErr_SetString(PyExc_TypeError,
3955 "certfile should be a valid filesystem path");
3956 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003957 return NULL;
3958 }
3959 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003960 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3961 PyErr_SetString(PyExc_TypeError,
3962 "keyfile should be a valid filesystem path");
3963 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003964 goto error;
3965 }
Serhiy Storchaka279f4462019-09-14 12:24:05 +03003966 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003967 if (PyCallable_Check(password)) {
3968 pw_info.callable = password;
3969 } else if (!_pwinfo_set(&pw_info, password,
3970 "password should be a string or callable")) {
3971 goto error;
3972 }
3973 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3974 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3975 }
3976 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003977 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3978 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003979 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003980 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003981 if (pw_info.error) {
3982 ERR_clear_error();
3983 /* the password callback has already set the error information */
3984 }
3985 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003986 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003987 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003988 }
3989 else {
3990 _setSSLError(NULL, 0, __FILE__, __LINE__);
3991 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003992 goto error;
3993 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003994 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003995 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003996 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3997 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003998 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3999 Py_CLEAR(keyfile_bytes);
4000 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004001 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004002 if (pw_info.error) {
4003 ERR_clear_error();
4004 /* the password callback has already set the error information */
4005 }
4006 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00004007 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004008 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004009 }
4010 else {
4011 _setSSLError(NULL, 0, __FILE__, __LINE__);
4012 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004013 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004014 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004015 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004016 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004017 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004018 if (r != 1) {
4019 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004020 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004022 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4023 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004024 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004025 Py_RETURN_NONE;
4026
4027error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02004028 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
4029 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02004030 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031 Py_XDECREF(keyfile_bytes);
4032 Py_XDECREF(certfile_bytes);
4033 return NULL;
4034}
4035
Christian Heimesefff7062013-11-21 03:35:02 +01004036/* internal helper function, returns -1 on error
4037 */
4038static int
Serhiy Storchaka8f87eef2020-04-12 14:58:27 +03004039_add_ca_certs(PySSLContext *self, const void *data, Py_ssize_t len,
Christian Heimesefff7062013-11-21 03:35:02 +01004040 int filetype)
4041{
4042 BIO *biobuf = NULL;
4043 X509_STORE *store;
4044 int retval = 0, err, loaded = 0;
4045
4046 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4047
4048 if (len <= 0) {
4049 PyErr_SetString(PyExc_ValueError,
4050 "Empty certificate data");
4051 return -1;
4052 } else if (len > INT_MAX) {
4053 PyErr_SetString(PyExc_OverflowError,
4054 "Certificate data is too long.");
4055 return -1;
4056 }
4057
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004058 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004059 if (biobuf == NULL) {
4060 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4061 return -1;
4062 }
4063
4064 store = SSL_CTX_get_cert_store(self->ctx);
4065 assert(store != NULL);
4066
4067 while (1) {
4068 X509 *cert = NULL;
4069 int r;
4070
4071 if (filetype == SSL_FILETYPE_ASN1) {
4072 cert = d2i_X509_bio(biobuf, NULL);
4073 } else {
4074 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004075 SSL_CTX_get_default_passwd_cb(self->ctx),
4076 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4077 );
Christian Heimesefff7062013-11-21 03:35:02 +01004078 }
4079 if (cert == NULL) {
4080 break;
4081 }
4082 r = X509_STORE_add_cert(store, cert);
4083 X509_free(cert);
4084 if (!r) {
4085 err = ERR_peek_last_error();
4086 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4087 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4088 /* cert already in hash table, not an error */
4089 ERR_clear_error();
4090 } else {
4091 break;
4092 }
4093 }
4094 loaded++;
4095 }
4096
4097 err = ERR_peek_last_error();
4098 if ((filetype == SSL_FILETYPE_ASN1) &&
4099 (loaded > 0) &&
4100 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4101 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4102 /* EOF ASN1 file, not an error */
4103 ERR_clear_error();
4104 retval = 0;
4105 } else if ((filetype == SSL_FILETYPE_PEM) &&
4106 (loaded > 0) &&
4107 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4108 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4109 /* EOF PEM file, not an error */
4110 ERR_clear_error();
4111 retval = 0;
4112 } else {
4113 _setSSLError(NULL, 0, __FILE__, __LINE__);
4114 retval = -1;
4115 }
4116
4117 BIO_free(biobuf);
4118 return retval;
4119}
4120
4121
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004122/*[clinic input]
4123_ssl._SSLContext.load_verify_locations
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004124 cafile: object = None
4125 capath: object = None
4126 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004127
4128[clinic start generated code]*/
4129
Antoine Pitrou152efa22010-05-16 18:19:27 +00004130static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004131_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4132 PyObject *cafile,
4133 PyObject *capath,
4134 PyObject *cadata)
Serhiy Storchaka279f4462019-09-14 12:24:05 +03004135/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004136{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004137 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4138 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004139 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004140
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004141 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004142 if (cafile == Py_None)
4143 cafile = NULL;
4144 if (capath == Py_None)
4145 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004146 if (cadata == Py_None)
4147 cadata = NULL;
4148
4149 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004150 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004151 "cafile, capath and cadata cannot be all omitted");
4152 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004153 }
4154 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004155 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4156 PyErr_SetString(PyExc_TypeError,
4157 "cafile should be a valid filesystem path");
4158 }
Christian Heimesefff7062013-11-21 03:35:02 +01004159 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004160 }
4161 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004162 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4163 PyErr_SetString(PyExc_TypeError,
4164 "capath should be a valid filesystem path");
4165 }
Christian Heimesefff7062013-11-21 03:35:02 +01004166 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004167 }
Christian Heimesefff7062013-11-21 03:35:02 +01004168
4169 /* validata cadata type and load cadata */
4170 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004171 if (PyUnicode_Check(cadata)) {
4172 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4173 if (cadata_ascii == NULL) {
4174 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4175 goto invalid_cadata;
4176 }
4177 goto error;
4178 }
4179 r = _add_ca_certs(self,
4180 PyBytes_AS_STRING(cadata_ascii),
4181 PyBytes_GET_SIZE(cadata_ascii),
4182 SSL_FILETYPE_PEM);
4183 Py_DECREF(cadata_ascii);
4184 if (r == -1) {
4185 goto error;
4186 }
4187 }
4188 else if (PyObject_CheckBuffer(cadata)) {
4189 Py_buffer buf;
4190 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4191 goto error;
4192 }
Christian Heimesefff7062013-11-21 03:35:02 +01004193 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4194 PyBuffer_Release(&buf);
4195 PyErr_SetString(PyExc_TypeError,
4196 "cadata should be a contiguous buffer with "
4197 "a single dimension");
4198 goto error;
4199 }
4200 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4201 PyBuffer_Release(&buf);
4202 if (r == -1) {
4203 goto error;
4204 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004205 }
4206 else {
4207 invalid_cadata:
4208 PyErr_SetString(PyExc_TypeError,
4209 "cadata should be an ASCII string or a "
4210 "bytes-like object");
4211 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004212 }
4213 }
4214
4215 /* load cafile or capath */
4216 if (cafile || capath) {
4217 if (cafile)
4218 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4219 if (capath)
4220 capath_buf = PyBytes_AS_STRING(capath_bytes);
4221 PySSL_BEGIN_ALLOW_THREADS
4222 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4223 PySSL_END_ALLOW_THREADS
4224 if (r != 1) {
Christian Heimesefff7062013-11-21 03:35:02 +01004225 if (errno != 0) {
4226 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004227 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004228 }
4229 else {
4230 _setSSLError(NULL, 0, __FILE__, __LINE__);
4231 }
4232 goto error;
4233 }
4234 }
4235 goto end;
4236
4237 error:
4238 ok = 0;
4239 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004240 Py_XDECREF(cafile_bytes);
4241 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004242 if (ok) {
4243 Py_RETURN_NONE;
4244 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004245 return NULL;
4246 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004247}
4248
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004249/*[clinic input]
4250_ssl._SSLContext.load_dh_params
4251 path as filepath: object
4252 /
4253
4254[clinic start generated code]*/
4255
Antoine Pitrou152efa22010-05-16 18:19:27 +00004256static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004257_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4258/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004259{
4260 FILE *f;
4261 DH *dh;
4262
Victor Stinnerdaf45552013-08-28 00:53:59 +02004263 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004264 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004265 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004266
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004267 errno = 0;
4268 PySSL_BEGIN_ALLOW_THREADS
4269 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004270 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004271 PySSL_END_ALLOW_THREADS
4272 if (dh == NULL) {
4273 if (errno != 0) {
4274 ERR_clear_error();
4275 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4276 }
4277 else {
4278 _setSSLError(NULL, 0, __FILE__, __LINE__);
4279 }
4280 return NULL;
4281 }
4282 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4283 _setSSLError(NULL, 0, __FILE__, __LINE__);
4284 DH_free(dh);
4285 Py_RETURN_NONE;
4286}
4287
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004288/*[clinic input]
4289_ssl._SSLContext._wrap_socket
4290 sock: object(subclass_of="PySocketModule.Sock_Type")
4291 server_side: int
4292 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004293 *
4294 owner: object = None
4295 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004296
4297[clinic start generated code]*/
4298
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004299static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004300_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004301 int server_side, PyObject *hostname_obj,
4302 PyObject *owner, PyObject *session)
4303/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004304{
Antoine Pitroud5323212010-10-22 18:19:07 +00004305 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004306 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004307
Antoine Pitroud5323212010-10-22 18:19:07 +00004308 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004309 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004310 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004311 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004312 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004313 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004314
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004315 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4316 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004317 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004318 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004319 if (hostname != NULL)
4320 PyMem_Free(hostname);
4321 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004322}
4323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004324/*[clinic input]
4325_ssl._SSLContext._wrap_bio
4326 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4327 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4328 server_side: int
4329 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004330 *
4331 owner: object = None
4332 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004333
4334[clinic start generated code]*/
4335
Antoine Pitroub0182c82010-10-12 20:09:02 +00004336static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004337_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4338 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004339 PyObject *hostname_obj, PyObject *owner,
4340 PyObject *session)
4341/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004342{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004343 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004344 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004345
4346 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004347 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004348 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004349 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004350 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004351 }
4352
4353 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004354 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004355 incoming, outgoing);
4356
4357 PyMem_Free(hostname);
4358 return res;
4359}
4360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004361/*[clinic input]
4362_ssl._SSLContext.session_stats
4363[clinic start generated code]*/
4364
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004365static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004366_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4367/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004368{
4369 int r;
4370 PyObject *value, *stats = PyDict_New();
4371 if (!stats)
4372 return NULL;
4373
4374#define ADD_STATS(SSL_NAME, KEY_NAME) \
4375 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4376 if (value == NULL) \
4377 goto error; \
4378 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4379 Py_DECREF(value); \
4380 if (r < 0) \
4381 goto error;
4382
4383 ADD_STATS(number, "number");
4384 ADD_STATS(connect, "connect");
4385 ADD_STATS(connect_good, "connect_good");
4386 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4387 ADD_STATS(accept, "accept");
4388 ADD_STATS(accept_good, "accept_good");
4389 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4390 ADD_STATS(accept, "accept");
4391 ADD_STATS(hits, "hits");
4392 ADD_STATS(misses, "misses");
4393 ADD_STATS(timeouts, "timeouts");
4394 ADD_STATS(cache_full, "cache_full");
4395
4396#undef ADD_STATS
4397
4398 return stats;
4399
4400error:
4401 Py_DECREF(stats);
4402 return NULL;
4403}
4404
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004405/*[clinic input]
4406_ssl._SSLContext.set_default_verify_paths
4407[clinic start generated code]*/
4408
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004409static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004410_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4411/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004412{
4413 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4414 _setSSLError(NULL, 0, __FILE__, __LINE__);
4415 return NULL;
4416 }
4417 Py_RETURN_NONE;
4418}
4419
Antoine Pitrou501da612011-12-21 09:27:41 +01004420#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004421/*[clinic input]
4422_ssl._SSLContext.set_ecdh_curve
4423 name: object
4424 /
4425
4426[clinic start generated code]*/
4427
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004428static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004429_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4430/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004431{
4432 PyObject *name_bytes;
4433 int nid;
4434 EC_KEY *key;
4435
4436 if (!PyUnicode_FSConverter(name, &name_bytes))
4437 return NULL;
4438 assert(PyBytes_Check(name_bytes));
4439 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4440 Py_DECREF(name_bytes);
4441 if (nid == 0) {
4442 PyErr_Format(PyExc_ValueError,
4443 "unknown elliptic curve name %R", name);
4444 return NULL;
4445 }
4446 key = EC_KEY_new_by_curve_name(nid);
4447 if (key == NULL) {
4448 _setSSLError(NULL, 0, __FILE__, __LINE__);
4449 return NULL;
4450 }
4451 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4452 EC_KEY_free(key);
4453 Py_RETURN_NONE;
4454}
Antoine Pitrou501da612011-12-21 09:27:41 +01004455#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004456
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004457#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004458static int
4459_servername_callback(SSL *s, int *al, void *args)
4460{
4461 int ret;
4462 PySSLContext *ssl_ctx = (PySSLContext *) args;
4463 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004464 PyObject *result;
4465 /* The high-level ssl.SSLSocket object */
4466 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004467 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004468 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004469
Christian Heimes11a14932018-02-24 02:35:08 +01004470 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004471 /* remove race condition in this the call back while if removing the
4472 * callback is in progress */
4473 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004474 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004475 }
4476
4477 ssl = SSL_get_app_data(s);
4478 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004479
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004480 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004481 * SSL connection and that has a .context attribute that can be changed to
4482 * identify the requested hostname. Since the official API is the Python
4483 * level API we want to pass the callback a Python level object rather than
4484 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4485 * SSLObject) that will be passed. Otherwise if there's a socket then that
4486 * will be passed. If both do not exist only then the C-level object is
4487 * passed. */
4488 if (ssl->owner)
4489 ssl_socket = PyWeakref_GetObject(ssl->owner);
4490 else if (ssl->Socket)
4491 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4492 else
4493 ssl_socket = (PyObject *) ssl;
4494
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004495 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004496 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004497 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004498
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004499 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004500 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004501 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004502 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004503 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004504 PyObject *servername_bytes;
4505 PyObject *servername_str;
4506
4507 servername_bytes = PyBytes_FromString(servername);
4508 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004509 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4510 goto error;
4511 }
Christian Heimes11a14932018-02-24 02:35:08 +01004512 /* server_hostname was encoded to an A-label by our caller; put it
4513 * back into a str object, but still as an A-label (bpo-28414)
4514 */
4515 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4516 Py_DECREF(servername_bytes);
4517 if (servername_str == NULL) {
4518 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004519 goto error;
4520 }
Christian Heimes11a14932018-02-24 02:35:08 +01004521 result = PyObject_CallFunctionObjArgs(
4522 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4523 ssl_ctx, NULL);
4524 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004525 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004526 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004527
4528 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004529 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004530 *al = SSL_AD_HANDSHAKE_FAILURE;
4531 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4532 }
4533 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004534 /* Result may be None, a SSLContext or an integer
4535 * None and SSLContext are OK, integer or other values are an error.
4536 */
4537 if (result == Py_None) {
4538 ret = SSL_TLSEXT_ERR_OK;
4539 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004540 *al = (int) PyLong_AsLong(result);
4541 if (PyErr_Occurred()) {
4542 PyErr_WriteUnraisable(result);
4543 *al = SSL_AD_INTERNAL_ERROR;
4544 }
4545 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4546 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004547 Py_DECREF(result);
4548 }
4549
4550 PyGILState_Release(gstate);
4551 return ret;
4552
4553error:
4554 Py_DECREF(ssl_socket);
4555 *al = SSL_AD_INTERNAL_ERROR;
4556 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4557 PyGILState_Release(gstate);
4558 return ret;
4559}
Antoine Pitroua5963382013-03-30 16:39:00 +01004560#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004561
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004562static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004563get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004564{
Christian Heimes11a14932018-02-24 02:35:08 +01004565 PyObject *cb = self->set_sni_cb;
4566 if (cb == NULL) {
4567 Py_RETURN_NONE;
4568 }
4569 Py_INCREF(cb);
4570 return cb;
4571}
4572
4573static int
4574set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4575{
4576 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4577 PyErr_SetString(PyExc_ValueError,
4578 "sni_callback cannot be set on TLS_CLIENT context");
4579 return -1;
4580 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004581#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004582 Py_CLEAR(self->set_sni_cb);
4583 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004584 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4585 }
4586 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004587 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004588 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4589 PyErr_SetString(PyExc_TypeError,
4590 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004591 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004592 }
Christian Heimes11a14932018-02-24 02:35:08 +01004593 Py_INCREF(arg);
4594 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004595 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4596 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4597 }
Christian Heimes11a14932018-02-24 02:35:08 +01004598 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004599#else
4600 PyErr_SetString(PyExc_NotImplementedError,
4601 "The TLS extension servername callback, "
4602 "SSL_CTX_set_tlsext_servername_callback, "
4603 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004604 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004605#endif
4606}
4607
Christian Heimes11a14932018-02-24 02:35:08 +01004608PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4609"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4610\n\
4611If the argument is None then the callback is disabled. The method is called\n\
4612with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4613See RFC 6066 for details of the SNI extension.");
4614
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004615/*[clinic input]
4616_ssl._SSLContext.cert_store_stats
4617
4618Returns quantities of loaded X.509 certificates.
4619
4620X.509 certificates with a CA extension and certificate revocation lists
4621inside the context's cert store.
4622
4623NOTE: Certificates in a capath directory aren't loaded unless they have
4624been used at least once.
4625[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004626
4627static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004628_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4629/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004630{
4631 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004632 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004633 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004634 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004635
4636 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004637 objs = X509_STORE_get0_objects(store);
4638 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4639 obj = sk_X509_OBJECT_value(objs, i);
4640 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004641 case X509_LU_X509:
4642 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004643 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004644 ca++;
4645 }
4646 break;
4647 case X509_LU_CRL:
4648 crl++;
4649 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004650 default:
4651 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4652 * As far as I can tell they are internal states and never
4653 * stored in a cert store */
4654 break;
4655 }
4656 }
4657 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4658 "x509_ca", ca);
4659}
4660
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004661/*[clinic input]
4662_ssl._SSLContext.get_ca_certs
4663 binary_form: bool = False
4664
4665Returns a list of dicts with information of loaded CA certs.
4666
4667If the optional argument is True, returns a DER-encoded copy of the CA
4668certificate.
4669
4670NOTE: Certificates in a capath directory aren't loaded unless they have
4671been used at least once.
4672[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004673
4674static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004675_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4676/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004677{
4678 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004679 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004680 PyObject *ci = NULL, *rlist = NULL;
4681 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004682
4683 if ((rlist = PyList_New(0)) == NULL) {
4684 return NULL;
4685 }
4686
4687 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004688 objs = X509_STORE_get0_objects(store);
4689 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004690 X509_OBJECT *obj;
4691 X509 *cert;
4692
Christian Heimes598894f2016-09-05 23:19:05 +02004693 obj = sk_X509_OBJECT_value(objs, i);
4694 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004695 /* not a x509 cert */
4696 continue;
4697 }
4698 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004699 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004700 if (!X509_check_ca(cert)) {
4701 continue;
4702 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004703 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004704 ci = _certificate_to_der(cert);
4705 } else {
4706 ci = _decode_certificate(cert);
4707 }
4708 if (ci == NULL) {
4709 goto error;
4710 }
4711 if (PyList_Append(rlist, ci) == -1) {
4712 goto error;
4713 }
4714 Py_CLEAR(ci);
4715 }
4716 return rlist;
4717
4718 error:
4719 Py_XDECREF(ci);
4720 Py_XDECREF(rlist);
4721 return NULL;
4722}
4723
4724
Antoine Pitrou152efa22010-05-16 18:19:27 +00004725static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004726 {"check_hostname", (getter) get_check_hostname,
4727 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004728 {"_host_flags", (getter) get_host_flags,
4729 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004730#if SSL_CTRL_GET_MAX_PROTO_VERSION
4731 {"minimum_version", (getter) get_minimum_version,
4732 (setter) set_minimum_version, NULL},
4733 {"maximum_version", (getter) get_maximum_version,
4734 (setter) set_maximum_version, NULL},
4735#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004736#ifdef HAVE_OPENSSL_KEYLOG
4737 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4738 (setter) _PySSLContext_set_keylog_filename, NULL},
4739#endif
4740 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4741 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004742 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004743 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004744#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4745 {"num_tickets", (getter) get_num_tickets,
4746 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4747#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004748 {"options", (getter) get_options,
4749 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004750 {"post_handshake_auth", (getter) get_post_handshake_auth,
4751#ifdef TLS1_3_VERSION
4752 (setter) set_post_handshake_auth,
4753#else
4754 NULL,
4755#endif
4756 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004757 {"protocol", (getter) get_protocol,
4758 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004759 {"verify_flags", (getter) get_verify_flags,
4760 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004761 {"verify_mode", (getter) get_verify_mode,
4762 (setter) set_verify_mode, NULL},
4763 {NULL}, /* sentinel */
4764};
4765
4766static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004767 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4768 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4769 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4770 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4771 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4772 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4773 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4774 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4775 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4776 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4777 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004778 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4779 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004780 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004781 {NULL, NULL} /* sentinel */
4782};
4783
4784static PyTypeObject PySSLContext_Type = {
4785 PyVarObject_HEAD_INIT(NULL, 0)
4786 "_ssl._SSLContext", /*tp_name*/
4787 sizeof(PySSLContext), /*tp_basicsize*/
4788 0, /*tp_itemsize*/
4789 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004790 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004791 0, /*tp_getattr*/
4792 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004793 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004794 0, /*tp_repr*/
4795 0, /*tp_as_number*/
4796 0, /*tp_as_sequence*/
4797 0, /*tp_as_mapping*/
4798 0, /*tp_hash*/
4799 0, /*tp_call*/
4800 0, /*tp_str*/
4801 0, /*tp_getattro*/
4802 0, /*tp_setattro*/
4803 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004804 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004805 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004806 (traverseproc) context_traverse, /*tp_traverse*/
4807 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004808 0, /*tp_richcompare*/
4809 0, /*tp_weaklistoffset*/
4810 0, /*tp_iter*/
4811 0, /*tp_iternext*/
4812 context_methods, /*tp_methods*/
4813 0, /*tp_members*/
4814 context_getsetlist, /*tp_getset*/
4815 0, /*tp_base*/
4816 0, /*tp_dict*/
4817 0, /*tp_descr_get*/
4818 0, /*tp_descr_set*/
4819 0, /*tp_dictoffset*/
4820 0, /*tp_init*/
4821 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004822 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004823};
4824
4825
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004826/*
4827 * MemoryBIO objects
4828 */
4829
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004830/*[clinic input]
4831@classmethod
4832_ssl.MemoryBIO.__new__
4833
4834[clinic start generated code]*/
4835
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004836static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004837_ssl_MemoryBIO_impl(PyTypeObject *type)
4838/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004839{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004840 BIO *bio;
4841 PySSLMemoryBIO *self;
4842
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004843 bio = BIO_new(BIO_s_mem());
4844 if (bio == NULL) {
4845 PyErr_SetString(PySSLErrorObject,
4846 "failed to allocate BIO");
4847 return NULL;
4848 }
4849 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4850 * just that no data is currently available. The SSL routines should retry
4851 * the read, which we can achieve by calling BIO_set_retry_read(). */
4852 BIO_set_retry_read(bio);
4853 BIO_set_mem_eof_return(bio, -1);
4854
4855 assert(type != NULL && type->tp_alloc != NULL);
4856 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4857 if (self == NULL) {
4858 BIO_free(bio);
4859 return NULL;
4860 }
4861 self->bio = bio;
4862 self->eof_written = 0;
4863
4864 return (PyObject *) self;
4865}
4866
4867static void
4868memory_bio_dealloc(PySSLMemoryBIO *self)
4869{
4870 BIO_free(self->bio);
4871 Py_TYPE(self)->tp_free(self);
4872}
4873
4874static PyObject *
4875memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4876{
Segev Finer5cff6372017-07-27 01:19:17 +03004877 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004878}
4879
4880PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4881"The number of bytes pending in the memory BIO.");
4882
4883static PyObject *
4884memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4885{
4886 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4887 && self->eof_written);
4888}
4889
4890PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4891"Whether the memory BIO is at EOF.");
4892
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004893/*[clinic input]
4894_ssl.MemoryBIO.read
4895 size as len: int = -1
4896 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004897
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004898Read up to size bytes from the memory BIO.
4899
4900If size is not specified, read the entire buffer.
4901If the return value is an empty bytes instance, this means either
4902EOF or that no data is available. Use the "eof" property to
4903distinguish between the two.
4904[clinic start generated code]*/
4905
4906static PyObject *
4907_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4908/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4909{
4910 int avail, nbytes;
4911 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004912
Segev Finer5cff6372017-07-27 01:19:17 +03004913 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004914 if ((len < 0) || (len > avail))
4915 len = avail;
4916
4917 result = PyBytes_FromStringAndSize(NULL, len);
4918 if ((result == NULL) || (len == 0))
4919 return result;
4920
4921 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004922 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004923 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004924 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004925 return NULL;
4926 }
4927
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004928 /* There should never be any short reads but check anyway. */
4929 if (nbytes < len) {
4930 _PyBytes_Resize(&result, nbytes);
4931 }
4932
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004933 return result;
4934}
4935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004936/*[clinic input]
4937_ssl.MemoryBIO.write
4938 b: Py_buffer
4939 /
4940
4941Writes the bytes b into the memory BIO.
4942
4943Returns the number of bytes written.
4944[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004945
4946static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004947_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4948/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004949{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004950 int nbytes;
4951
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004952 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004953 PyErr_Format(PyExc_OverflowError,
4954 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004955 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004956 }
4957
4958 if (self->eof_written) {
4959 PyErr_SetString(PySSLErrorObject,
4960 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004961 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004962 }
4963
Segev Finer5cff6372017-07-27 01:19:17 +03004964 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004965 if (nbytes < 0) {
4966 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004967 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004968 }
4969
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004970 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971}
4972
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004973/*[clinic input]
4974_ssl.MemoryBIO.write_eof
4975
4976Write an EOF marker to the memory BIO.
4977
4978When all data has been read, the "eof" property will be True.
4979[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004980
4981static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004982_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4983/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004984{
4985 self->eof_written = 1;
4986 /* After an EOF is written, a zero return from read() should be a real EOF
4987 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4988 BIO_clear_retry_flags(self->bio);
4989 BIO_set_mem_eof_return(self->bio, 0);
4990
4991 Py_RETURN_NONE;
4992}
4993
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004994static PyGetSetDef memory_bio_getsetlist[] = {
4995 {"pending", (getter) memory_bio_get_pending, NULL,
4996 PySSL_memory_bio_pending_doc},
4997 {"eof", (getter) memory_bio_get_eof, NULL,
4998 PySSL_memory_bio_eof_doc},
4999 {NULL}, /* sentinel */
5000};
5001
5002static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005003 _SSL_MEMORYBIO_READ_METHODDEF
5004 _SSL_MEMORYBIO_WRITE_METHODDEF
5005 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005006 {NULL, NULL} /* sentinel */
5007};
5008
5009static PyTypeObject PySSLMemoryBIO_Type = {
5010 PyVarObject_HEAD_INIT(NULL, 0)
5011 "_ssl.MemoryBIO", /*tp_name*/
5012 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
5013 0, /*tp_itemsize*/
5014 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005015 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005016 0, /*tp_getattr*/
5017 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005018 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005019 0, /*tp_repr*/
5020 0, /*tp_as_number*/
5021 0, /*tp_as_sequence*/
5022 0, /*tp_as_mapping*/
5023 0, /*tp_hash*/
5024 0, /*tp_call*/
5025 0, /*tp_str*/
5026 0, /*tp_getattro*/
5027 0, /*tp_setattro*/
5028 0, /*tp_as_buffer*/
5029 Py_TPFLAGS_DEFAULT, /*tp_flags*/
5030 0, /*tp_doc*/
5031 0, /*tp_traverse*/
5032 0, /*tp_clear*/
5033 0, /*tp_richcompare*/
5034 0, /*tp_weaklistoffset*/
5035 0, /*tp_iter*/
5036 0, /*tp_iternext*/
5037 memory_bio_methods, /*tp_methods*/
5038 0, /*tp_members*/
5039 memory_bio_getsetlist, /*tp_getset*/
5040 0, /*tp_base*/
5041 0, /*tp_dict*/
5042 0, /*tp_descr_get*/
5043 0, /*tp_descr_set*/
5044 0, /*tp_dictoffset*/
5045 0, /*tp_init*/
5046 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005047 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005048};
5049
Antoine Pitrou152efa22010-05-16 18:19:27 +00005050
Christian Heimes99a65702016-09-10 23:44:53 +02005051/*
5052 * SSL Session object
5053 */
5054
5055static void
5056PySSLSession_dealloc(PySSLSession *self)
5057{
INADA Naokia6296d32017-08-24 14:55:17 +09005058 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005059 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005060 Py_XDECREF(self->ctx);
5061 if (self->session != NULL) {
5062 SSL_SESSION_free(self->session);
5063 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005064 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005065}
5066
5067static PyObject *
5068PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5069{
5070 int result;
5071
5072 if (left == NULL || right == NULL) {
5073 PyErr_BadInternalCall();
5074 return NULL;
5075 }
5076
5077 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5078 Py_RETURN_NOTIMPLEMENTED;
5079 }
5080
5081 if (left == right) {
5082 result = 0;
5083 } else {
5084 const unsigned char *left_id, *right_id;
5085 unsigned int left_len, right_len;
5086 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5087 &left_len);
5088 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5089 &right_len);
5090 if (left_len == right_len) {
5091 result = memcmp(left_id, right_id, left_len);
5092 } else {
5093 result = 1;
5094 }
5095 }
5096
5097 switch (op) {
5098 case Py_EQ:
5099 if (result == 0) {
5100 Py_RETURN_TRUE;
5101 } else {
5102 Py_RETURN_FALSE;
5103 }
5104 break;
5105 case Py_NE:
5106 if (result != 0) {
5107 Py_RETURN_TRUE;
5108 } else {
5109 Py_RETURN_FALSE;
5110 }
5111 break;
5112 case Py_LT:
5113 case Py_LE:
5114 case Py_GT:
5115 case Py_GE:
5116 Py_RETURN_NOTIMPLEMENTED;
5117 break;
5118 default:
5119 PyErr_BadArgument();
5120 return NULL;
5121 }
5122}
5123
5124static int
5125PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5126{
5127 Py_VISIT(self->ctx);
5128 return 0;
5129}
5130
5131static int
5132PySSLSession_clear(PySSLSession *self)
5133{
5134 Py_CLEAR(self->ctx);
5135 return 0;
5136}
5137
5138
5139static PyObject *
5140PySSLSession_get_time(PySSLSession *self, void *closure) {
5141 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5142}
5143
5144PyDoc_STRVAR(PySSLSession_get_time_doc,
5145"Session creation time (seconds since epoch).");
5146
5147
5148static PyObject *
5149PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5150 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5151}
5152
5153PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5154"Session timeout (delta in seconds).");
5155
5156
5157static PyObject *
5158PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5159 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5160 return PyLong_FromUnsignedLong(hint);
5161}
5162
5163PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5164"Ticket life time hint.");
5165
5166
5167static PyObject *
5168PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5169 const unsigned char *id;
5170 unsigned int len;
5171 id = SSL_SESSION_get_id(self->session, &len);
5172 return PyBytes_FromStringAndSize((const char *)id, len);
5173}
5174
5175PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5176"Session id");
5177
5178
5179static PyObject *
5180PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5181 if (SSL_SESSION_has_ticket(self->session)) {
5182 Py_RETURN_TRUE;
5183 } else {
5184 Py_RETURN_FALSE;
5185 }
5186}
5187
5188PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5189"Does the session contain a ticket?");
5190
5191
5192static PyGetSetDef PySSLSession_getsetlist[] = {
5193 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5194 PySSLSession_get_has_ticket_doc},
5195 {"id", (getter) PySSLSession_get_session_id, NULL,
5196 PySSLSession_get_session_id_doc},
5197 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5198 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5199 {"time", (getter) PySSLSession_get_time, NULL,
5200 PySSLSession_get_time_doc},
5201 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5202 PySSLSession_get_timeout_doc},
5203 {NULL}, /* sentinel */
5204};
5205
5206static PyTypeObject PySSLSession_Type = {
5207 PyVarObject_HEAD_INIT(NULL, 0)
5208 "_ssl.Session", /*tp_name*/
5209 sizeof(PySSLSession), /*tp_basicsize*/
5210 0, /*tp_itemsize*/
5211 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005212 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005213 0, /*tp_getattr*/
5214 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005215 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005216 0, /*tp_repr*/
5217 0, /*tp_as_number*/
5218 0, /*tp_as_sequence*/
5219 0, /*tp_as_mapping*/
5220 0, /*tp_hash*/
5221 0, /*tp_call*/
5222 0, /*tp_str*/
5223 0, /*tp_getattro*/
5224 0, /*tp_setattro*/
5225 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005226 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005227 0, /*tp_doc*/
5228 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5229 (inquiry)PySSLSession_clear, /*tp_clear*/
5230 PySSLSession_richcompare, /*tp_richcompare*/
5231 0, /*tp_weaklistoffset*/
5232 0, /*tp_iter*/
5233 0, /*tp_iternext*/
5234 0, /*tp_methods*/
5235 0, /*tp_members*/
5236 PySSLSession_getsetlist, /*tp_getset*/
5237};
5238
5239
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005240/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005241/*[clinic input]
5242_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005243 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005244 entropy: double
5245 /
5246
5247Mix string into the OpenSSL PRNG state.
5248
5249entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305250string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005251[clinic start generated code]*/
5252
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005253static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005254_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005255/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005256{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005257 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005258 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005259
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005260 buf = (const char *)view->buf;
5261 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005262 do {
5263 written = Py_MIN(len, INT_MAX);
5264 RAND_add(buf, (int)written, entropy);
5265 buf += written;
5266 len -= written;
5267 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005268 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005269}
5270
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005271static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005272PySSL_RAND(int len, int pseudo)
5273{
5274 int ok;
5275 PyObject *bytes;
5276 unsigned long err;
5277 const char *errstr;
5278 PyObject *v;
5279
Victor Stinner1e81a392013-12-19 16:47:04 +01005280 if (len < 0) {
5281 PyErr_SetString(PyExc_ValueError, "num must be positive");
5282 return NULL;
5283 }
5284
Victor Stinner99c8b162011-05-24 12:05:19 +02005285 bytes = PyBytes_FromStringAndSize(NULL, len);
5286 if (bytes == NULL)
5287 return NULL;
5288 if (pseudo) {
5289 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5290 if (ok == 0 || ok == 1)
5291 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5292 }
5293 else {
5294 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5295 if (ok == 1)
5296 return bytes;
5297 }
5298 Py_DECREF(bytes);
5299
5300 err = ERR_get_error();
5301 errstr = ERR_reason_error_string(err);
5302 v = Py_BuildValue("(ks)", err, errstr);
5303 if (v != NULL) {
5304 PyErr_SetObject(PySSLErrorObject, v);
5305 Py_DECREF(v);
5306 }
5307 return NULL;
5308}
5309
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005310/*[clinic input]
5311_ssl.RAND_bytes
5312 n: int
5313 /
5314
5315Generate n cryptographically strong pseudo-random bytes.
5316[clinic start generated code]*/
5317
Victor Stinner99c8b162011-05-24 12:05:19 +02005318static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005319_ssl_RAND_bytes_impl(PyObject *module, int n)
5320/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005321{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005322 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005323}
5324
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005325/*[clinic input]
5326_ssl.RAND_pseudo_bytes
5327 n: int
5328 /
5329
5330Generate n pseudo-random bytes.
5331
5332Return a pair (bytes, is_cryptographic). is_cryptographic is True
5333if the bytes generated are cryptographically strong.
5334[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005335
5336static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005337_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5338/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005339{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005340 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005341}
5342
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005343/*[clinic input]
5344_ssl.RAND_status
5345
5346Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5347
5348It is necessary to seed the PRNG with RAND_add() on some platforms before
5349using the ssl() function.
5350[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005351
5352static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005353_ssl_RAND_status_impl(PyObject *module)
5354/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005355{
Christian Heimes217cfd12007-12-02 14:31:20 +00005356 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005357}
5358
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005359#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005360/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005361/*[clinic input]
5362_ssl.RAND_egd
5363 path: object(converter="PyUnicode_FSConverter")
5364 /
5365
5366Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5367
5368Returns number of bytes read. Raises SSLError if connection to EGD
5369fails or if it does not provide enough data to seed PRNG.
5370[clinic start generated code]*/
5371
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005372static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005373_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5374/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005375{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005376 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005377 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005378 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005379 PyErr_SetString(PySSLErrorObject,
5380 "EGD connection failed or EGD did not return "
5381 "enough data to seed the PRNG");
5382 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005383 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005384 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005385}
Christian Heimesa5d07652016-09-24 10:48:05 +02005386/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005387#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005388
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005389
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005390
5391/*[clinic input]
5392_ssl.get_default_verify_paths
5393
5394Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5395
5396The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5397[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005398
5399static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005400_ssl_get_default_verify_paths_impl(PyObject *module)
5401/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005402{
5403 PyObject *ofile_env = NULL;
5404 PyObject *ofile = NULL;
5405 PyObject *odir_env = NULL;
5406 PyObject *odir = NULL;
5407
Benjamin Petersond113c962015-07-18 10:59:13 -07005408#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005409 const char *tmp = (info); \
5410 target = NULL; \
5411 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5412 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5413 target = PyBytes_FromString(tmp); } \
5414 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005415 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005416
Benjamin Petersond113c962015-07-18 10:59:13 -07005417 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5418 CONVERT(X509_get_default_cert_file(), ofile);
5419 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5420 CONVERT(X509_get_default_cert_dir(), odir);
5421#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005422
Christian Heimes200bb1b2013-06-14 15:14:29 +02005423 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005424
5425 error:
5426 Py_XDECREF(ofile_env);
5427 Py_XDECREF(ofile);
5428 Py_XDECREF(odir_env);
5429 Py_XDECREF(odir);
5430 return NULL;
5431}
5432
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005433static PyObject*
5434asn1obj2py(ASN1_OBJECT *obj)
5435{
5436 int nid;
5437 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005438
5439 nid = OBJ_obj2nid(obj);
5440 if (nid == NID_undef) {
5441 PyErr_Format(PyExc_ValueError, "Unknown object");
5442 return NULL;
5443 }
5444 sn = OBJ_nid2sn(nid);
5445 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005446 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005447}
5448
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005449/*[clinic input]
5450_ssl.txt2obj
5451 txt: str
5452 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005453
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005454Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5455
5456By default objects are looked up by OID. With name=True short and
5457long name are also matched.
5458[clinic start generated code]*/
5459
5460static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005461_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5462/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005463{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005464 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005465 ASN1_OBJECT *obj;
5466
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005467 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5468 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005469 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005470 return NULL;
5471 }
5472 result = asn1obj2py(obj);
5473 ASN1_OBJECT_free(obj);
5474 return result;
5475}
5476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005477/*[clinic input]
5478_ssl.nid2obj
5479 nid: int
5480 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005481
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005482Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5483[clinic start generated code]*/
5484
5485static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005486_ssl_nid2obj_impl(PyObject *module, int nid)
5487/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005488{
5489 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005490 ASN1_OBJECT *obj;
5491
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005492 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005493 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005494 return NULL;
5495 }
5496 obj = OBJ_nid2obj(nid);
5497 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005498 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005499 return NULL;
5500 }
5501 result = asn1obj2py(obj);
5502 ASN1_OBJECT_free(obj);
5503 return result;
5504}
5505
Christian Heimes46bebee2013-06-09 19:03:31 +02005506#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005507
5508static PyObject*
5509certEncodingType(DWORD encodingType)
5510{
5511 static PyObject *x509_asn = NULL;
5512 static PyObject *pkcs_7_asn = NULL;
5513
5514 if (x509_asn == NULL) {
5515 x509_asn = PyUnicode_InternFromString("x509_asn");
5516 if (x509_asn == NULL)
5517 return NULL;
5518 }
5519 if (pkcs_7_asn == NULL) {
5520 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5521 if (pkcs_7_asn == NULL)
5522 return NULL;
5523 }
5524 switch(encodingType) {
5525 case X509_ASN_ENCODING:
5526 Py_INCREF(x509_asn);
5527 return x509_asn;
5528 case PKCS_7_ASN_ENCODING:
5529 Py_INCREF(pkcs_7_asn);
5530 return pkcs_7_asn;
5531 default:
5532 return PyLong_FromLong(encodingType);
5533 }
5534}
5535
5536static PyObject*
5537parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5538{
5539 CERT_ENHKEY_USAGE *usage;
5540 DWORD size, error, i;
5541 PyObject *retval;
5542
5543 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5544 error = GetLastError();
5545 if (error == CRYPT_E_NOT_FOUND) {
5546 Py_RETURN_TRUE;
5547 }
5548 return PyErr_SetFromWindowsErr(error);
5549 }
5550
5551 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5552 if (usage == NULL) {
5553 return PyErr_NoMemory();
5554 }
5555
5556 /* Now get the actual enhanced usage property */
5557 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5558 PyMem_Free(usage);
5559 error = GetLastError();
5560 if (error == CRYPT_E_NOT_FOUND) {
5561 Py_RETURN_TRUE;
5562 }
5563 return PyErr_SetFromWindowsErr(error);
5564 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005565 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005566 if (retval == NULL) {
5567 goto error;
5568 }
5569 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5570 if (usage->rgpszUsageIdentifier[i]) {
5571 PyObject *oid;
5572 int err;
5573 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5574 if (oid == NULL) {
5575 Py_CLEAR(retval);
5576 goto error;
5577 }
5578 err = PySet_Add(retval, oid);
5579 Py_DECREF(oid);
5580 if (err == -1) {
5581 Py_CLEAR(retval);
5582 goto error;
5583 }
5584 }
5585 }
5586 error:
5587 PyMem_Free(usage);
5588 return retval;
5589}
5590
kctherookied93fbbf2019-03-29 00:59:06 +07005591static HCERTSTORE
5592ssl_collect_certificates(const char *store_name)
5593{
5594/* this function collects the system certificate stores listed in
5595 * system_stores into a collection certificate store for being
5596 * enumerated. The store must be readable to be added to the
5597 * store collection.
5598 */
5599
5600 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5601 static DWORD system_stores[] = {
5602 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5603 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5604 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5605 CERT_SYSTEM_STORE_CURRENT_USER,
5606 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5607 CERT_SYSTEM_STORE_SERVICES,
5608 CERT_SYSTEM_STORE_USERS};
5609 size_t i, storesAdded;
5610 BOOL result;
5611
5612 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5613 (HCRYPTPROV)NULL, 0, NULL);
5614 if (!hCollectionStore) {
5615 return NULL;
5616 }
5617 storesAdded = 0;
5618 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5619 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5620 (HCRYPTPROV)NULL,
5621 CERT_STORE_READONLY_FLAG |
5622 system_stores[i], store_name);
5623 if (hSystemStore) {
5624 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5625 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5626 if (result) {
5627 ++storesAdded;
5628 }
neoneneed701292019-09-09 21:33:43 +09005629 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005630 }
5631 }
5632 if (storesAdded == 0) {
5633 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5634 return NULL;
5635 }
5636
5637 return hCollectionStore;
5638}
5639
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005640/*[clinic input]
5641_ssl.enum_certificates
5642 store_name: str
5643
5644Retrieve certificates from Windows' cert store.
5645
5646store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5647more cert storages, too. The function returns a list of (bytes,
5648encoding_type, trust) tuples. The encoding_type flag can be interpreted
5649with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5650a set of OIDs or the boolean True.
5651[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005652
Christian Heimes46bebee2013-06-09 19:03:31 +02005653static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005654_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5655/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005656{
kctherookied93fbbf2019-03-29 00:59:06 +07005657 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005658 PCCERT_CONTEXT pCertCtx = NULL;
5659 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005660 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005661
Christian Heimes915cd3f2019-09-09 18:06:55 +02005662 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005663 if (result == NULL) {
5664 return NULL;
5665 }
kctherookied93fbbf2019-03-29 00:59:06 +07005666 hCollectionStore = ssl_collect_certificates(store_name);
5667 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005668 Py_DECREF(result);
5669 return PyErr_SetFromWindowsErr(GetLastError());
5670 }
5671
kctherookied93fbbf2019-03-29 00:59:06 +07005672 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005673 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5674 pCertCtx->cbCertEncoded);
5675 if (!cert) {
5676 Py_CLEAR(result);
5677 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005678 }
Christian Heimes44109d72013-11-22 01:51:30 +01005679 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5680 Py_CLEAR(result);
5681 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005682 }
Christian Heimes44109d72013-11-22 01:51:30 +01005683 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5684 if (keyusage == Py_True) {
5685 Py_DECREF(keyusage);
5686 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005687 }
Christian Heimes44109d72013-11-22 01:51:30 +01005688 if (keyusage == NULL) {
5689 Py_CLEAR(result);
5690 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005691 }
Christian Heimes44109d72013-11-22 01:51:30 +01005692 if ((tup = PyTuple_New(3)) == NULL) {
5693 Py_CLEAR(result);
5694 break;
5695 }
5696 PyTuple_SET_ITEM(tup, 0, cert);
5697 cert = NULL;
5698 PyTuple_SET_ITEM(tup, 1, enc);
5699 enc = NULL;
5700 PyTuple_SET_ITEM(tup, 2, keyusage);
5701 keyusage = NULL;
Christian Heimes915cd3f2019-09-09 18:06:55 +02005702 if (PySet_Add(result, tup) == -1) {
5703 Py_CLEAR(result);
5704 Py_CLEAR(tup);
5705 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005706 }
5707 Py_CLEAR(tup);
5708 }
5709 if (pCertCtx) {
5710 /* loop ended with an error, need to clean up context manually */
5711 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005712 }
5713
5714 /* In error cases cert, enc and tup may not be NULL */
5715 Py_XDECREF(cert);
5716 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005717 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005718 Py_XDECREF(tup);
5719
kctherookied93fbbf2019-03-29 00:59:06 +07005720 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5721 associated with the store, in this case our collection store and the
5722 associated system stores. */
5723 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005724 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005725 Py_XDECREF(result);
5726 return PyErr_SetFromWindowsErr(GetLastError());
5727 }
kctherookied93fbbf2019-03-29 00:59:06 +07005728
Christian Heimes915cd3f2019-09-09 18:06:55 +02005729 /* convert set to list */
5730 if (result == NULL) {
5731 return NULL;
5732 } else {
5733 PyObject *lst = PySequence_List(result);
5734 Py_DECREF(result);
5735 return lst;
5736 }
Christian Heimes44109d72013-11-22 01:51:30 +01005737}
5738
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005739/*[clinic input]
5740_ssl.enum_crls
5741 store_name: str
5742
5743Retrieve CRLs from Windows' cert store.
5744
5745store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5746more cert storages, too. The function returns a list of (bytes,
5747encoding_type) tuples. The encoding_type flag can be interpreted with
5748X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5749[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005750
5751static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005752_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5753/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005754{
kctherookied93fbbf2019-03-29 00:59:06 +07005755 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005756 PCCRL_CONTEXT pCrlCtx = NULL;
5757 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5758 PyObject *result = NULL;
5759
Christian Heimes915cd3f2019-09-09 18:06:55 +02005760 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005761 if (result == NULL) {
5762 return NULL;
5763 }
kctherookied93fbbf2019-03-29 00:59:06 +07005764 hCollectionStore = ssl_collect_certificates(store_name);
5765 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005766 Py_DECREF(result);
5767 return PyErr_SetFromWindowsErr(GetLastError());
5768 }
Christian Heimes44109d72013-11-22 01:51:30 +01005769
kctherookied93fbbf2019-03-29 00:59:06 +07005770 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005771 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5772 pCrlCtx->cbCrlEncoded);
5773 if (!crl) {
5774 Py_CLEAR(result);
5775 break;
5776 }
5777 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5778 Py_CLEAR(result);
5779 break;
5780 }
5781 if ((tup = PyTuple_New(2)) == NULL) {
5782 Py_CLEAR(result);
5783 break;
5784 }
5785 PyTuple_SET_ITEM(tup, 0, crl);
5786 crl = NULL;
5787 PyTuple_SET_ITEM(tup, 1, enc);
5788 enc = NULL;
5789
Christian Heimes915cd3f2019-09-09 18:06:55 +02005790 if (PySet_Add(result, tup) == -1) {
5791 Py_CLEAR(result);
5792 Py_CLEAR(tup);
5793 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005794 }
5795 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005796 }
Christian Heimes44109d72013-11-22 01:51:30 +01005797 if (pCrlCtx) {
5798 /* loop ended with an error, need to clean up context manually */
5799 CertFreeCRLContext(pCrlCtx);
5800 }
5801
5802 /* In error cases cert, enc and tup may not be NULL */
5803 Py_XDECREF(crl);
5804 Py_XDECREF(enc);
5805 Py_XDECREF(tup);
5806
kctherookied93fbbf2019-03-29 00:59:06 +07005807 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5808 associated with the store, in this case our collection store and the
5809 associated system stores. */
5810 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005811 /* This error case might shadow another exception.*/
5812 Py_XDECREF(result);
5813 return PyErr_SetFromWindowsErr(GetLastError());
5814 }
Christian Heimes915cd3f2019-09-09 18:06:55 +02005815 /* convert set to list */
5816 if (result == NULL) {
5817 return NULL;
5818 } else {
5819 PyObject *lst = PySequence_List(result);
5820 Py_DECREF(result);
5821 return lst;
5822 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005823}
Christian Heimes44109d72013-11-22 01:51:30 +01005824
5825#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005826
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005827/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005828static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005829 _SSL__TEST_DECODE_CERT_METHODDEF
5830 _SSL_RAND_ADD_METHODDEF
5831 _SSL_RAND_BYTES_METHODDEF
5832 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5833 _SSL_RAND_EGD_METHODDEF
5834 _SSL_RAND_STATUS_METHODDEF
5835 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5836 _SSL_ENUM_CERTIFICATES_METHODDEF
5837 _SSL_ENUM_CRLS_METHODDEF
5838 _SSL_TXT2OBJ_METHODDEF
5839 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005840 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005841};
5842
5843
Christian Heimes598894f2016-09-05 23:19:05 +02005844#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005845
5846/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005847 * of the Python C thread library
5848 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5849 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005850
5851static PyThread_type_lock *_ssl_locks = NULL;
5852
Christian Heimes4d98ca92013-08-19 17:36:29 +02005853#if OPENSSL_VERSION_NUMBER >= 0x10000000
5854/* use new CRYPTO_THREADID API. */
5855static void
5856_ssl_threadid_callback(CRYPTO_THREADID *id)
5857{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005858 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005859}
5860#else
5861/* deprecated CRYPTO_set_id_callback() API. */
5862static unsigned long
5863_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005864 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005865}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005866#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005867
Bill Janssen6e027db2007-11-15 22:23:56 +00005868static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005869 (int mode, int n, const char *file, int line) {
5870 /* this function is needed to perform locking on shared data
5871 structures. (Note that OpenSSL uses a number of global data
5872 structures that will be implicitly shared whenever multiple
5873 threads use OpenSSL.) Multi-threaded applications will
5874 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005875
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005876 locking_function() must be able to handle up to
5877 CRYPTO_num_locks() different mutex locks. It sets the n-th
5878 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005880 file and line are the file number of the function setting the
5881 lock. They can be useful for debugging.
5882 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005883
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005884 if ((_ssl_locks == NULL) ||
5885 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5886 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005887
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005888 if (mode & CRYPTO_LOCK) {
5889 PyThread_acquire_lock(_ssl_locks[n], 1);
5890 } else {
5891 PyThread_release_lock(_ssl_locks[n]);
5892 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005893}
5894
5895static int _setup_ssl_threads(void) {
5896
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005897 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005898
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005899 if (_ssl_locks == NULL) {
5900 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005901 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5902 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005903 if (_ssl_locks == NULL) {
5904 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005905 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005906 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005907 for (i = 0; i < _ssl_locks_count; i++) {
5908 _ssl_locks[i] = PyThread_allocate_lock();
5909 if (_ssl_locks[i] == NULL) {
5910 unsigned int j;
5911 for (j = 0; j < i; j++) {
5912 PyThread_free_lock(_ssl_locks[j]);
5913 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005914 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005915 return 0;
5916 }
5917 }
5918 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005919#if OPENSSL_VERSION_NUMBER >= 0x10000000
5920 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5921#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005922 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005923#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005924 }
5925 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005926}
5927
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005928#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005929
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005930PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005931"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005932for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005933
Martin v. Löwis1a214512008-06-11 05:26:20 +00005934
5935static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005936 PyModuleDef_HEAD_INIT,
5937 "_ssl",
5938 module_doc,
5939 -1,
5940 PySSL_methods,
5941 NULL,
5942 NULL,
5943 NULL,
5944 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005945};
5946
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005947
5948static void
5949parse_openssl_version(unsigned long libver,
5950 unsigned int *major, unsigned int *minor,
5951 unsigned int *fix, unsigned int *patch,
5952 unsigned int *status)
5953{
5954 *status = libver & 0xF;
5955 libver >>= 4;
5956 *patch = libver & 0xFF;
5957 libver >>= 8;
5958 *fix = libver & 0xFF;
5959 libver >>= 8;
5960 *minor = libver & 0xFF;
5961 libver >>= 8;
5962 *major = libver & 0xFF;
5963}
5964
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005965PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005966PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005967{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005968 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005969 unsigned long libver;
5970 unsigned int major, minor, fix, patch, status;
5971 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005972 struct py_ssl_error_code *errcode;
5973 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005974
Antoine Pitrou152efa22010-05-16 18:19:27 +00005975 if (PyType_Ready(&PySSLContext_Type) < 0)
5976 return NULL;
5977 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005978 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005979 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5980 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005981 if (PyType_Ready(&PySSLSession_Type) < 0)
5982 return NULL;
5983
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005985 m = PyModule_Create(&_sslmodule);
5986 if (m == NULL)
5987 return NULL;
5988 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005989
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005990 /* Load _socket module and its C API */
5991 socket_api = PySocketModule_ImportModuleAndAPI();
5992 if (!socket_api)
5993 return NULL;
5994 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005995
Christian Heimesc941e622017-09-05 15:47:11 +02005996#ifndef OPENSSL_VERSION_1_1
5997 /* Load all algorithms and initialize cpuid */
5998 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005999 /* Init OpenSSL */
6000 SSL_load_error_strings();
6001 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02006002#endif
6003
Christian Heimes598894f2016-09-05 23:19:05 +02006004#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006005 /* note that this will start threading if not already started */
6006 if (!_setup_ssl_threads()) {
6007 return NULL;
6008 }
Christian Heimesc087a262020-05-15 20:55:25 +02006009#elif OPENSSL_VERSION_1_1
Christian Heimes598894f2016-09-05 23:19:05 +02006010 /* OpenSSL 1.1.0 builtin thread support is enabled */
6011 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00006012#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006013
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006014 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006015 sslerror_type_slots[0].pfunc = PyExc_OSError;
6016 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006017 if (PySSLErrorObject == NULL)
6018 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006019
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006020 /* ssl.CertificateError used to be a subclass of ValueError */
6021 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
6022 if (bases == NULL)
6023 return NULL;
6024 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
6025 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
6026 bases, NULL);
6027 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02006028 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
6029 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
6030 PySSLErrorObject, NULL);
6031 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
6032 "ssl.SSLWantReadError", SSLWantReadError_doc,
6033 PySSLErrorObject, NULL);
6034 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
6035 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
6036 PySSLErrorObject, NULL);
6037 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
6038 "ssl.SSLSyscallError", SSLSyscallError_doc,
6039 PySSLErrorObject, NULL);
6040 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
6041 "ssl.SSLEOFError", SSLEOFError_doc,
6042 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006043 if (PySSLCertVerificationErrorObject == NULL
6044 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006045 || PySSLWantReadErrorObject == NULL
6046 || PySSLWantWriteErrorObject == NULL
6047 || PySSLSyscallErrorObject == NULL
6048 || PySSLEOFErrorObject == NULL)
6049 return NULL;
6050 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006051 || PyDict_SetItemString(d, "SSLCertVerificationError",
6052 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006053 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6054 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6055 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6056 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6057 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006058 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006059 if (PyDict_SetItemString(d, "_SSLContext",
6060 (PyObject *)&PySSLContext_Type) != 0)
6061 return NULL;
6062 if (PyDict_SetItemString(d, "_SSLSocket",
6063 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006064 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006065 if (PyDict_SetItemString(d, "MemoryBIO",
6066 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6067 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006068 if (PyDict_SetItemString(d, "SSLSession",
6069 (PyObject *)&PySSLSession_Type) != 0)
6070 return NULL;
6071
Christian Heimes892d66e2018-01-29 14:10:18 +01006072 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6073 PY_SSL_DEFAULT_CIPHER_STRING);
6074
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006075 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6076 PY_SSL_ERROR_ZERO_RETURN);
6077 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6078 PY_SSL_ERROR_WANT_READ);
6079 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6080 PY_SSL_ERROR_WANT_WRITE);
6081 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6082 PY_SSL_ERROR_WANT_X509_LOOKUP);
6083 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6084 PY_SSL_ERROR_SYSCALL);
6085 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6086 PY_SSL_ERROR_SSL);
6087 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6088 PY_SSL_ERROR_WANT_CONNECT);
6089 /* non ssl.h errorcodes */
6090 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6091 PY_SSL_ERROR_EOF);
6092 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6093 PY_SSL_ERROR_INVALID_ERROR_CODE);
6094 /* cert requirements */
6095 PyModule_AddIntConstant(m, "CERT_NONE",
6096 PY_SSL_CERT_NONE);
6097 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6098 PY_SSL_CERT_OPTIONAL);
6099 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6100 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006101 /* CRL verification for verification_flags */
6102 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6103 0);
6104 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6105 X509_V_FLAG_CRL_CHECK);
6106 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6107 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6108 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6109 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006110#ifdef X509_V_FLAG_TRUSTED_FIRST
6111 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6112 X509_V_FLAG_TRUSTED_FIRST);
6113#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006114
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006115 /* Alert Descriptions from ssl.h */
6116 /* note RESERVED constants no longer intended for use have been removed */
6117 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6118
6119#define ADD_AD_CONSTANT(s) \
6120 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6121 SSL_AD_##s)
6122
6123 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6124 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6125 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6126 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6127 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6128 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6129 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6130 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6131 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6132 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6133 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6134 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6135 ADD_AD_CONSTANT(UNKNOWN_CA);
6136 ADD_AD_CONSTANT(ACCESS_DENIED);
6137 ADD_AD_CONSTANT(DECODE_ERROR);
6138 ADD_AD_CONSTANT(DECRYPT_ERROR);
6139 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6140 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6141 ADD_AD_CONSTANT(INTERNAL_ERROR);
6142 ADD_AD_CONSTANT(USER_CANCELLED);
6143 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006144 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006145#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6146 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6147#endif
6148#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6149 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6150#endif
6151#ifdef SSL_AD_UNRECOGNIZED_NAME
6152 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6153#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006154#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6155 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6156#endif
6157#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6158 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6159#endif
6160#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6161 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6162#endif
6163
6164#undef ADD_AD_CONSTANT
6165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006166 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006167#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006168 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6169 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006170#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006171#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006172 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6173 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006174#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006175 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006176 PY_SSL_VERSION_TLS);
6177 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6178 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006179 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6180 PY_SSL_VERSION_TLS_CLIENT);
6181 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6182 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006183 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6184 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006185 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6186 PY_SSL_VERSION_TLS1_1);
6187 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6188 PY_SSL_VERSION_TLS1_2);
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006189
Antoine Pitroub5218772010-05-21 09:56:06 +00006190 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006191 PyModule_AddIntConstant(m, "OP_ALL",
6192 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006193 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6194 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6195 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006196 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6197 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006198#ifdef SSL_OP_NO_TLSv1_3
6199 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6200#else
6201 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6202#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006203 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6204 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006205 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006206 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006207#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006208 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006209#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006210#ifdef SSL_OP_NO_COMPRESSION
6211 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6212 SSL_OP_NO_COMPRESSION);
6213#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006214#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6215 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6216 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6217#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006218#ifdef SSL_OP_NO_RENEGOTIATION
6219 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6220 SSL_OP_NO_RENEGOTIATION);
6221#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006222
Christian Heimes61d478c2018-01-27 15:51:38 +01006223#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6224 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6225 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6226#endif
6227#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6228 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6229 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6230#endif
6231#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6232 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6233 X509_CHECK_FLAG_NO_WILDCARDS);
6234#endif
6235#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6236 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6237 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6238#endif
6239#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6240 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6241 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6242#endif
6243#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6244 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6245 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6246#endif
6247
Christian Heimes698dde12018-02-27 11:54:43 +01006248 /* protocol versions */
6249 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6250 PY_PROTO_MINIMUM_SUPPORTED);
6251 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6252 PY_PROTO_MAXIMUM_SUPPORTED);
6253 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6254 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6255 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6256 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6257 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006258
Victor Stinnerb37672d2018-11-22 03:37:50 +01006259#define addbool(m, key, value) \
6260 do { \
6261 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6262 Py_INCREF(bool_obj); \
6263 PyModule_AddObject((m), (key), bool_obj); \
6264 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006265
6266#if HAVE_SNI
6267 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006268#else
Christian Heimes698dde12018-02-27 11:54:43 +01006269 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006270#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006271
6272 addbool(m, "HAS_TLS_UNIQUE", 1);
6273
6274#ifndef OPENSSL_NO_ECDH
6275 addbool(m, "HAS_ECDH", 1);
6276#else
6277 addbool(m, "HAS_ECDH", 0);
6278#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006279
Christian Heimes29eab552018-02-25 12:31:33 +01006280#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006281 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006282#else
Christian Heimes698dde12018-02-27 11:54:43 +01006283 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006284#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006285
Christian Heimes29eab552018-02-25 12:31:33 +01006286#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006287 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006288#else
Christian Heimes698dde12018-02-27 11:54:43 +01006289 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006290#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006291
6292#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6293 addbool(m, "HAS_SSLv2", 1);
6294#else
6295 addbool(m, "HAS_SSLv2", 0);
6296#endif
6297
6298#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6299 addbool(m, "HAS_SSLv3", 1);
6300#else
6301 addbool(m, "HAS_SSLv3", 0);
6302#endif
6303
6304#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6305 addbool(m, "HAS_TLSv1", 1);
6306#else
6307 addbool(m, "HAS_TLSv1", 0);
6308#endif
6309
6310#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6311 addbool(m, "HAS_TLSv1_1", 1);
6312#else
6313 addbool(m, "HAS_TLSv1_1", 0);
6314#endif
6315
6316#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6317 addbool(m, "HAS_TLSv1_2", 1);
6318#else
6319 addbool(m, "HAS_TLSv1_2", 0);
6320#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006321
Christian Heimescb5b68a2017-09-07 18:07:00 -07006322#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006323 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006324#else
Christian Heimes698dde12018-02-27 11:54:43 +01006325 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006326#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006327
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006328 /* Mappings for error codes */
6329 err_codes_to_names = PyDict_New();
6330 err_names_to_codes = PyDict_New();
6331 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6332 return NULL;
6333 errcode = error_codes;
6334 while (errcode->mnemonic != NULL) {
6335 PyObject *mnemo, *key;
6336 mnemo = PyUnicode_FromString(errcode->mnemonic);
6337 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6338 if (mnemo == NULL || key == NULL)
6339 return NULL;
6340 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6341 return NULL;
6342 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6343 return NULL;
6344 Py_DECREF(key);
6345 Py_DECREF(mnemo);
6346 errcode++;
6347 }
6348 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6349 return NULL;
6350 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6351 return NULL;
6352
6353 lib_codes_to_names = PyDict_New();
6354 if (lib_codes_to_names == NULL)
6355 return NULL;
6356 libcode = library_codes;
6357 while (libcode->library != NULL) {
6358 PyObject *mnemo, *key;
6359 key = PyLong_FromLong(libcode->code);
6360 mnemo = PyUnicode_FromString(libcode->library);
6361 if (key == NULL || mnemo == NULL)
6362 return NULL;
6363 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6364 return NULL;
6365 Py_DECREF(key);
6366 Py_DECREF(mnemo);
6367 libcode++;
6368 }
6369 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6370 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006372 /* OpenSSL version */
6373 /* SSLeay() gives us the version of the library linked against,
6374 which could be different from the headers version.
6375 */
6376 libver = SSLeay();
6377 r = PyLong_FromUnsignedLong(libver);
6378 if (r == NULL)
6379 return NULL;
6380 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6381 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006382 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006383 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6384 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6385 return NULL;
6386 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6387 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6388 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006389
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006390 libver = OPENSSL_VERSION_NUMBER;
6391 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6392 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6393 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6394 return NULL;
6395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006396 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006397}