blob: f40127d3d932bbaaa918d32007b9ef59368122c7 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010078/* SSL error object */
79static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070080static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010081static PyObject *PySSLZeroReturnErrorObject;
82static PyObject *PySSLWantReadErrorObject;
83static PyObject *PySSLWantWriteErrorObject;
84static PyObject *PySSLSyscallErrorObject;
85static PyObject *PySSLEOFErrorObject;
86
87/* Error mappings */
88static PyObject *err_codes_to_names;
89static PyObject *err_names_to_codes;
90static PyObject *lib_codes_to_names;
91
92struct py_ssl_error_code {
93 const char *mnemonic;
94 int library, reason;
95};
96struct py_ssl_library_code {
97 const char *library;
98 int code;
99};
100
Steve Dower68d663c2017-07-17 11:15:48 +0200101#if defined(MS_WINDOWS) && defined(Py_DEBUG)
102/* Debug builds on Windows rely on getting errno directly from OpenSSL.
103 * However, because it uses a different CRT, we need to transfer the
104 * value of errno from OpenSSL into our debug CRT.
105 *
106 * Don't be fooled - this is horribly ugly code. The only reasonable
107 * alternative is to do both debug and release builds of OpenSSL, which
108 * requires much uglier code to transform their automatically generated
109 * makefile. This is the lesser of all the evils.
110 */
111
112static void _PySSLFixErrno(void) {
113 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
114 if (!ucrtbase) {
115 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
116 * have a catastrophic failure, but this function is not the
117 * place to raise it. */
118 return;
119 }
120
121 typedef int *(__stdcall *errno_func)(void);
122 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
123 if (ssl_errno) {
124 errno = *ssl_errno();
125 *ssl_errno() = 0;
126 } else {
127 errno = ENOTRECOVERABLE;
128 }
129}
130
131#undef _PySSL_FIX_ERRNO
132#define _PySSL_FIX_ERRNO _PySSLFixErrno()
133#endif
134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135/* Include generated data (error codes) */
136#include "_ssl_data.h"
137
Christian Heimes598894f2016-09-05 23:19:05 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
139# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100140# define PY_OPENSSL_1_1_API 1
141#endif
142
143/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
144#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
145# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200146#endif
147
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
149 http://www.openssl.org/news/changelog.html
150 */
151#if OPENSSL_VERSION_NUMBER >= 0x10001000L
152# define HAVE_TLSv1_2 1
153#else
154# define HAVE_TLSv1_2 0
155#endif
156
Christian Heimes470fba12013-11-28 15:12:15 +0100157/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100158 * This includes the SSL_set_SSL_CTX() function.
159 */
160#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
161# define HAVE_SNI 1
162#else
163# define HAVE_SNI 0
164#endif
165
Benjamin Petersond3308222015-09-27 00:09:02 -0700166#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Christian Heimes6cdb7952018-02-24 22:12:40 +0100172/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
173 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
174 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
175 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100182#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100183# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100184#else
Christian Heimes29eab552018-02-25 12:31:33 +0100185# define HAVE_NPN 0
186#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100187
Christian Heimesc7f70692019-05-31 11:44:05 +0200188#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
189#define HAVE_OPENSSL_KEYLOG 1
190#endif
191
Victor Stinner524714e2016-07-22 17:43:59 +0200192#ifndef INVALID_SOCKET /* MS defines this */
193#define INVALID_SOCKET (-1)
194#endif
195
Christian Heimes4ca07392018-03-24 15:41:37 +0100196/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
197#ifndef OPENSSL_VERSION_1_1
198#define HAVE_OPENSSL_CRYPTO_LOCK
199#endif
200
201#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200202#define OPENSSL_NO_SSL2
203#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100204
205#ifndef PY_OPENSSL_1_1_API
206/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200209#define TLS_client_method SSLv23_client_method
210#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200211
212static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
213{
214 return ne->set;
215}
216
217#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200218/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200219static int COMP_get_type(const COMP_METHOD *meth)
220{
221 return meth->type;
222}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200223/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200224#endif
225
226static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
227{
228 return ctx->default_passwd_callback;
229}
230
231static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
232{
233 return ctx->default_passwd_callback_userdata;
234}
235
236static int X509_OBJECT_get_type(X509_OBJECT *x)
237{
238 return x->type;
239}
240
241static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
242{
243 return x->data.x509;
244}
245
246static int BIO_up_ref(BIO *b)
247{
248 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
249 return 1;
250}
251
252static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
253 return store->objs;
254}
255
Christian Heimes99a65702016-09-10 23:44:53 +0200256static int
257SSL_SESSION_has_ticket(const SSL_SESSION *s)
258{
259 return (s->tlsext_ticklen > 0) ? 1 : 0;
260}
261
262static unsigned long
263SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
264{
265 return s->tlsext_tick_lifetime_hint;
266}
267
Christian Heimes4ca07392018-03-24 15:41:37 +0100268#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200269
Christian Heimes892d66e2018-01-29 14:10:18 +0100270/* Default cipher suites */
271#ifndef PY_SSL_DEFAULT_CIPHERS
272#define PY_SSL_DEFAULT_CIPHERS 1
273#endif
274
275#if PY_SSL_DEFAULT_CIPHERS == 0
276 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
277 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
278 #endif
279#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200280/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100281 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
282 * !aNULL:!eNULL: really no NULL ciphers
283 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
284 * !aDSS: no authentication with discrete logarithm DSA algorithm
285 * !SRP:!PSK: no secure remote password or pre-shared key authentication
286 */
287 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
288#elif PY_SSL_DEFAULT_CIPHERS == 2
289/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
290 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
291#else
292 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
293#endif
294
Christian Heimes598894f2016-09-05 23:19:05 +0200295
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000296enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 /* these mirror ssl.h */
298 PY_SSL_ERROR_NONE,
299 PY_SSL_ERROR_SSL,
300 PY_SSL_ERROR_WANT_READ,
301 PY_SSL_ERROR_WANT_WRITE,
302 PY_SSL_ERROR_WANT_X509_LOOKUP,
303 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
304 PY_SSL_ERROR_ZERO_RETURN,
305 PY_SSL_ERROR_WANT_CONNECT,
306 /* start of non ssl.h errorcodes */
307 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
308 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
309 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000310};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311
Thomas Woutersed03b412007-08-28 21:37:11 +0000312enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 PY_SSL_CLIENT,
314 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000315};
316
317enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000318 PY_SSL_CERT_NONE,
319 PY_SSL_CERT_OPTIONAL,
320 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000321};
322
323enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000324 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200325 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#if HAVE_TLSv1_2
328 PY_SSL_VERSION_TLS1,
329 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100331#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200332 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000333#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200334 PY_SSL_VERSION_TLS_CLIENT=0x10,
335 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100336};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200337
Christian Heimes698dde12018-02-27 11:54:43 +0100338enum py_proto_version {
339 PY_PROTO_MINIMUM_SUPPORTED = -2,
340 PY_PROTO_SSLv3 = SSL3_VERSION,
341 PY_PROTO_TLSv1 = TLS1_VERSION,
342 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
343 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
344#ifdef TLS1_3_VERSION
345 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
346#else
347 PY_PROTO_TLSv1_3 = 0x304,
348#endif
349 PY_PROTO_MAXIMUM_SUPPORTED = -1,
350
351/* OpenSSL has no dedicated API to set the minimum version to the maximum
352 * available version, and the other way around. We have to figure out the
353 * minimum and maximum available version on our own and hope for the best.
354 */
355#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
357#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
359#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
361#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
362 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
363#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
364 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
365#else
366 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
367#endif
368
369#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
371#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
373#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
375#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
376 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
377#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
378 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
379#else
380 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
381#endif
382};
383
384
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000385/* serves as a flag to see whether we've initialized the SSL thread support. */
386/* 0 means no, greater than 0 means yes */
387
388static unsigned int _ssl_locks_count = 0;
389
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000390/* SSL socket object */
391
392#define X509_NAME_MAXLEN 256
393
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000394/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
395 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
396 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
397#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000398# define HAVE_SSL_CTX_CLEAR_OPTIONS
399#else
400# undef HAVE_SSL_CTX_CLEAR_OPTIONS
401#endif
402
Antoine Pitroud6494802011-07-21 01:11:30 +0200403/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
404 * older SSL, but let's be safe */
405#define PySSL_CB_MAXLEN 128
406
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100407
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000410 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100411#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100413 int npn_protocols_len;
414#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100415#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500416 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300417 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500418#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100419#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100420 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100421#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100422 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100423 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
424 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
425 */
426 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100427 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200428#ifdef TLS1_3_VERSION
429 int post_handshake_auth;
430#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200431 PyObject *msg_cb;
432#ifdef HAVE_OPENSSL_KEYLOG
433 PyObject *keylog_filename;
434 BIO *keylog_bio;
435#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000436} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700439 int ssl; /* last seen error from SSL */
440 int c; /* last seen error from libc */
441#ifdef MS_WINDOWS
442 int ws; /* last seen error from winsock */
443#endif
444} _PySSLError;
445
446typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447 PyObject_HEAD
448 PyObject *Socket; /* weakref to socket on which we're layered */
449 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100450 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200451 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200452 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200453 PyObject *owner; /* Python level "owner" passed to servername callback */
454 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700455 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200456 /* Some SSL callbacks don't have error reporting. Callback wrappers
457 * store exception information on the socket. The handshake, read, write,
458 * and shutdown methods check for chained exceptions.
459 */
460 PyObject *exc_type;
461 PyObject *exc_value;
462 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000463} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000464
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200465typedef struct {
466 PyObject_HEAD
467 BIO *bio;
468 int eof_written;
469} PySSLMemoryBIO;
470
Christian Heimes99a65702016-09-10 23:44:53 +0200471typedef struct {
472 PyObject_HEAD
473 SSL_SESSION *session;
474 PySSLContext *ctx;
475} PySSLSession;
476
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477static PyTypeObject PySSLContext_Type;
478static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200479static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200480static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700482static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
483{
484 _PySSLError err = { 0 };
485 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700486#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700487 err.ws = WSAGetLastError();
488 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700489#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700490 err.c = errno;
491 err.ssl = SSL_get_error(ssl, retcode);
492 }
493 return err;
494}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300496/*[clinic input]
497module _ssl
498class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
499class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
500class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200501class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300502[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200503/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300504
505#include "clinic/_ssl.c.h"
506
Victor Stinner14690702015-04-06 22:46:13 +0200507static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000508
Christian Heimes141c5e82018-02-24 21:10:57 +0100509static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
510static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000511#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200513#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000514
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000515typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 SOCKET_IS_NONBLOCKING,
517 SOCKET_IS_BLOCKING,
518 SOCKET_HAS_TIMED_OUT,
519 SOCKET_HAS_BEEN_CLOSED,
520 SOCKET_TOO_LARGE_FOR_SELECT,
521 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000522} timeout_state;
523
Thomas Woutersed03b412007-08-28 21:37:11 +0000524/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000525#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200526#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000527
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200528/* Get the socket from a PySSLSocket, if it has one */
529#define GET_SOCKET(obj) ((obj)->Socket ? \
530 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200531
Victor Stinner14690702015-04-06 22:46:13 +0200532/* If sock is NULL, use a timeout of 0 second */
533#define GET_SOCKET_TIMEOUT(sock) \
534 ((sock != NULL) ? (sock)->sock_timeout : 0)
535
Christian Heimesc7f70692019-05-31 11:44:05 +0200536#include "_ssl/debughelpers.c"
537
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200538/*
539 * SSL errors.
540 */
541
542PyDoc_STRVAR(SSLError_doc,
543"An error occurred in the SSL implementation.");
544
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700545PyDoc_STRVAR(SSLCertVerificationError_doc,
546"A certificate could not be verified.");
547
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200548PyDoc_STRVAR(SSLZeroReturnError_doc,
549"SSL/TLS session closed cleanly.");
550
551PyDoc_STRVAR(SSLWantReadError_doc,
552"Non-blocking SSL socket needs to read more data\n"
553"before the requested operation can be completed.");
554
555PyDoc_STRVAR(SSLWantWriteError_doc,
556"Non-blocking SSL socket needs to write more data\n"
557"before the requested operation can be completed.");
558
559PyDoc_STRVAR(SSLSyscallError_doc,
560"System error when attempting SSL operation.");
561
562PyDoc_STRVAR(SSLEOFError_doc,
563"SSL/TLS connection terminated abruptly.");
564
565static PyObject *
566SSLError_str(PyOSErrorObject *self)
567{
568 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
569 Py_INCREF(self->strerror);
570 return self->strerror;
571 }
572 else
573 return PyObject_Str(self->args);
574}
575
576static PyType_Slot sslerror_type_slots[] = {
577 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900578 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 {Py_tp_str, SSLError_str},
580 {0, 0},
581};
582
583static PyType_Spec sslerror_type_spec = {
584 "ssl.SSLError",
585 sizeof(PyOSErrorObject),
586 0,
587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
588 sslerror_type_slots
589};
590
591static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700592fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
593 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594{
595 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700596 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 PyObject *init_value, *msg, *key;
598 _Py_IDENTIFIER(reason);
599 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700600 _Py_IDENTIFIER(verify_message);
601 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200602
603 if (errcode != 0) {
604 int lib, reason;
605
606 lib = ERR_GET_LIB(errcode);
607 reason = ERR_GET_REASON(errcode);
608 key = Py_BuildValue("ii", lib, reason);
609 if (key == NULL)
610 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300611 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300613 if (reason_obj == NULL && PyErr_Occurred()) {
614 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200615 }
616 key = PyLong_FromLong(lib);
617 if (key == NULL)
618 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300619 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200620 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300621 if (lib_obj == NULL && PyErr_Occurred()) {
622 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200623 }
624 if (errstr == NULL)
625 errstr = ERR_reason_error_string(errcode);
626 }
627 if (errstr == NULL)
628 errstr = "unknown error";
629
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700630 /* verify code for cert validation error */
631 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
632 const char *verify_str = NULL;
633 long verify_code;
634
635 verify_code = SSL_get_verify_result(sslsock->ssl);
636 verify_code_obj = PyLong_FromLong(verify_code);
637 if (verify_code_obj == NULL) {
638 goto fail;
639 }
640
641 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700642#ifdef X509_V_ERR_HOSTNAME_MISMATCH
643 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700644 case X509_V_ERR_HOSTNAME_MISMATCH:
645 verify_obj = PyUnicode_FromFormat(
646 "Hostname mismatch, certificate is not valid for '%S'.",
647 sslsock->server_hostname
648 );
649 break;
Christian Heimes09153602017-09-08 14:47:58 -0700650#endif
651#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700652 case X509_V_ERR_IP_ADDRESS_MISMATCH:
653 verify_obj = PyUnicode_FromFormat(
654 "IP address mismatch, certificate is not valid for '%S'.",
655 sslsock->server_hostname
656 );
657 break;
Christian Heimes09153602017-09-08 14:47:58 -0700658#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 default:
660 verify_str = X509_verify_cert_error_string(verify_code);
661 if (verify_str != NULL) {
662 verify_obj = PyUnicode_FromString(verify_str);
663 } else {
664 verify_obj = Py_None;
665 Py_INCREF(verify_obj);
666 }
667 break;
668 }
669 if (verify_obj == NULL) {
670 goto fail;
671 }
672 }
673
674 if (verify_obj && reason_obj && lib_obj)
675 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
676 lib_obj, reason_obj, errstr, verify_obj,
677 lineno);
678 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200679 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
680 lib_obj, reason_obj, errstr, lineno);
681 else if (lib_obj)
682 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
683 lib_obj, errstr, lineno);
684 else
685 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 if (msg == NULL)
687 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100688
Paul Monsonfb7e7502019-05-15 15:38:55 -0700689 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100690 if (init_value == NULL)
691 goto fail;
692
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200693 err_value = PyObject_CallObject(type, init_value);
694 Py_DECREF(init_value);
695 if (err_value == NULL)
696 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100697
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200698 if (reason_obj == NULL)
699 reason_obj = Py_None;
700 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
701 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700702
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200703 if (lib_obj == NULL)
704 lib_obj = Py_None;
705 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
706 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700707
708 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
709 /* Only set verify code / message for SSLCertVerificationError */
710 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
711 verify_code_obj))
712 goto fail;
713 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
714 goto fail;
715 }
716
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200717 PyErr_SetObject(type, err_value);
718fail:
719 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700720 Py_XDECREF(verify_code_obj);
721 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200722}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000723
Christian Heimesc7f70692019-05-31 11:44:05 +0200724static int
725PySSL_ChainExceptions(PySSLSocket *sslsock) {
726 if (sslsock->exc_type == NULL)
727 return 0;
728
729 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
730 sslsock->exc_type = NULL;
731 sslsock->exc_value = NULL;
732 sslsock->exc_tb = NULL;
733 return -1;
734}
735
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700737PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000738{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200739 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200740 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700741 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200743 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200746 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000747
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700748 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700749 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000750
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700751 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200753 errstr = "TLS/SSL connection has been closed (EOF)";
754 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 p = PY_SSL_ERROR_ZERO_RETURN;
756 break;
757 case SSL_ERROR_WANT_READ:
758 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200759 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 p = PY_SSL_ERROR_WANT_READ;
761 break;
762 case SSL_ERROR_WANT_WRITE:
763 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200764 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 errstr = "The operation did not complete (write)";
766 break;
767 case SSL_ERROR_WANT_X509_LOOKUP:
768 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000769 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 break;
771 case SSL_ERROR_WANT_CONNECT:
772 p = PY_SSL_ERROR_WANT_CONNECT;
773 errstr = "The operation did not complete (connect)";
774 break;
775 case SSL_ERROR_SYSCALL:
776 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700778 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000780 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200781 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200783 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000785 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700786#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700787 if (err.ws) {
788 return PyErr_SetFromWindowsErr(err.ws);
789 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700790#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700791 if (err.c) {
792 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700793 return PyErr_SetFromErrno(PyExc_OSError);
794 }
795 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200796 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000797 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200798 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000800 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200801 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000802 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 }
804 } else {
805 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 }
807 break;
808 }
809 case SSL_ERROR_SSL:
810 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700812 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200813 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000814 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700815 }
816 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
817 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
818 type = PySSLCertVerificationErrorObject;
819 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 break;
821 }
822 default:
823 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
824 errstr = "Invalid error code";
825 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700827 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000828 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200829 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000831}
832
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200834_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200836 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200838 else
839 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700840 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000841 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843}
844
Christian Heimes61d478c2018-01-27 15:51:38 +0100845/*
846 * SSL objects
847 */
848
849static int
850_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
851{
852 int retval = -1;
853 ASN1_OCTET_STRING *ip;
854 PyObject *hostname;
855 size_t len;
856
857 assert(server_hostname);
858
859 /* Disable OpenSSL's special mode with leading dot in hostname:
860 * When name starts with a dot (e.g ".example.com"), it will be
861 * matched by a certificate valid for any sub-domain of name.
862 */
863 len = strlen(server_hostname);
864 if (len == 0 || *server_hostname == '.') {
865 PyErr_SetString(
866 PyExc_ValueError,
867 "server_hostname cannot be an empty string or start with a "
868 "leading dot.");
869 return retval;
870 }
871
872 /* inet_pton is not available on all platforms. */
873 ip = a2i_IPADDRESS(server_hostname);
874 if (ip == NULL) {
875 ERR_clear_error();
876 }
877
Christian Heimes11a14932018-02-24 02:35:08 +0100878 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100879 if (hostname == NULL) {
880 goto error;
881 }
882 self->server_hostname = hostname;
883
884 /* Only send SNI extension for non-IP hostnames */
885 if (ip == NULL) {
886 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
887 _setSSLError(NULL, 0, __FILE__, __LINE__);
888 }
889 }
890 if (self->ctx->check_hostname) {
891 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
892 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200893 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
894 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100895 _setSSLError(NULL, 0, __FILE__, __LINE__);
896 goto error;
897 }
898 } else {
899 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
900 ASN1_STRING_length(ip))) {
901 _setSSLError(NULL, 0, __FILE__, __LINE__);
902 goto error;
903 }
904 }
905 }
906 retval = 0;
907 error:
908 if (ip != NULL) {
909 ASN1_OCTET_STRING_free(ip);
910 }
911 return retval;
912}
913
Antoine Pitrou152efa22010-05-16 18:19:27 +0000914static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100915newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000916 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200917 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100918 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000920{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000921 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100922 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700923 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000924
Antoine Pitrou152efa22010-05-16 18:19:27 +0000925 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 if (self == NULL)
927 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100931 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700932 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200933 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200934 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700935 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700936 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200937 self->exc_type = NULL;
938 self->exc_value = NULL;
939 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000945 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700947 if (self->ssl == NULL) {
948 Py_DECREF(self);
949 _setSSLError(NULL, 0, __FILE__, __LINE__);
950 return NULL;
951 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200952 SSL_set_app_data(self->ssl, self);
953 if (sock) {
954 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
955 } else {
956 /* BIOs are reference counted and SSL_set_bio borrows our reference.
957 * To prevent a double free in memory_bio_dealloc() we need to take an
958 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200959 BIO_up_ref(inbio->bio);
960 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200961 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
962 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400963 SSL_set_mode(self->ssl,
964 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000965
Christian Heimes61d478c2018-01-27 15:51:38 +0100966 if (server_hostname != NULL) {
967 if (_ssl_configure_hostname(self, server_hostname) < 0) {
968 Py_DECREF(self);
969 return NULL;
970 }
971 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 /* If the socket is in non-blocking mode or timeout mode, set the BIO
973 * to non-blocking mode (blocking is the default)
974 */
Victor Stinnere2452312015-03-28 03:00:46 +0100975 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
977 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
978 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 PySSL_BEGIN_ALLOW_THREADS
981 if (socket_type == PY_SSL_CLIENT)
982 SSL_set_connect_state(self->ssl);
983 else
984 SSL_set_accept_state(self->ssl);
985 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000986
Antoine Pitroud6494802011-07-21 01:11:30 +0200987 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200988 if (sock != NULL) {
989 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
990 if (self->Socket == NULL) {
991 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200992 return NULL;
993 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100994 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100995 if (owner && owner != Py_None) {
996 if (PySSL_set_owner(self, owner, NULL) == -1) {
997 Py_DECREF(self);
998 return NULL;
999 }
1000 }
1001 if (session && session != Py_None) {
1002 if (PySSL_set_session(self, session, NULL) == -1) {
1003 Py_DECREF(self);
1004 return NULL;
1005 }
1006 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001008}
1009
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001010/* SSL object methods */
1011
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001012/*[clinic input]
1013_ssl._SSLSocket.do_handshake
1014[clinic start generated code]*/
1015
1016static PyObject *
1017_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1018/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001019{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001021 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001023 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001024 _PyTime_t timeout, deadline = 0;
1025 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001026
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001027 if (sock) {
1028 if (((PyObject*)sock) == Py_None) {
1029 _setSSLError("Underlying socket connection gone",
1030 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1031 return NULL;
1032 }
1033 Py_INCREF(sock);
1034
1035 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001036 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001037 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1038 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001040
Victor Stinner14690702015-04-06 22:46:13 +02001041 timeout = GET_SOCKET_TIMEOUT(sock);
1042 has_timeout = (timeout > 0);
1043 if (has_timeout)
1044 deadline = _PyTime_GetMonotonicClock() + timeout;
1045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 /* Actually negotiate SSL connection */
1047 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001049 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001051 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001053 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001054
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001055 if (PyErr_CheckSignals())
1056 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001057
Victor Stinner14690702015-04-06 22:46:13 +02001058 if (has_timeout)
1059 timeout = deadline - _PyTime_GetMonotonicClock();
1060
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001061 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001062 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001063 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001064 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 } else {
1066 sockstate = SOCKET_OPERATION_OK;
1067 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001070 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001071 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001072 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1074 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001075 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001076 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1078 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001079 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001080 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1082 break;
1083 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001084 } while (err.ssl == SSL_ERROR_WANT_READ ||
1085 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001086 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 if (ret < 1)
1088 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001089 if (PySSL_ChainExceptions(self) < 0)
1090 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001091 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001092error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001093 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001094 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001095 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001096}
1097
Thomas Woutersed03b412007-08-28 21:37:11 +00001098static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001099_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1100{
1101 char buf[X509_NAME_MAXLEN];
1102 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001104 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001105
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001106 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 if (buflen < 0) {
1108 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001109 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001111 /* initial buffer is too small for oid + terminating null byte */
1112 if (buflen > X509_NAME_MAXLEN - 1) {
1113 /* make OBJ_obj2txt() calculate the required buflen */
1114 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1115 /* allocate len + 1 for terminating NULL byte */
1116 namebuf = PyMem_Malloc(buflen + 1);
1117 if (namebuf == NULL) {
1118 PyErr_NoMemory();
1119 return NULL;
1120 }
1121 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1122 if (buflen < 0) {
1123 _setSSLError(NULL, 0, __FILE__, __LINE__);
1124 goto done;
1125 }
1126 }
1127 if (!buflen && no_name) {
1128 Py_INCREF(Py_None);
1129 name_obj = Py_None;
1130 }
1131 else {
1132 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1133 }
1134
1135 done:
1136 if (buf != namebuf) {
1137 PyMem_Free(namebuf);
1138 }
1139 return name_obj;
1140}
1141
1142static PyObject *
1143_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1144{
1145 Py_ssize_t buflen;
1146 unsigned char *valuebuf = NULL;
1147 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1150 if (buflen < 0) {
1151 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001152 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001154 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001157}
1158
1159static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001161{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1163 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1164 PyObject *rdnt;
1165 PyObject *attr = NULL; /* tuple to hold an attribute */
1166 int entry_count = X509_NAME_entry_count(xname);
1167 X509_NAME_ENTRY *entry;
1168 ASN1_OBJECT *name;
1169 ASN1_STRING *value;
1170 int index_counter;
1171 int rdn_level = -1;
1172 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 dn = PyList_New(0);
1175 if (dn == NULL)
1176 return NULL;
1177 /* now create another tuple to hold the top-level RDN */
1178 rdn = PyList_New(0);
1179 if (rdn == NULL)
1180 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 for (index_counter = 0;
1183 index_counter < entry_count;
1184 index_counter++)
1185 {
1186 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 /* check to see if we've gotten to a new RDN */
1189 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001190 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 /* yes, new RDN */
1192 /* add old RDN to DN */
1193 rdnt = PyList_AsTuple(rdn);
1194 Py_DECREF(rdn);
1195 if (rdnt == NULL)
1196 goto fail0;
1197 retcode = PyList_Append(dn, rdnt);
1198 Py_DECREF(rdnt);
1199 if (retcode < 0)
1200 goto fail0;
1201 /* create new RDN */
1202 rdn = PyList_New(0);
1203 if (rdn == NULL)
1204 goto fail0;
1205 }
1206 }
Christian Heimes598894f2016-09-05 23:19:05 +02001207 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 /* now add this attribute to the current RDN */
1210 name = X509_NAME_ENTRY_get_object(entry);
1211 value = X509_NAME_ENTRY_get_data(entry);
1212 attr = _create_tuple_for_attribute(name, value);
1213 /*
1214 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1215 entry->set,
1216 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1217 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1218 */
1219 if (attr == NULL)
1220 goto fail1;
1221 retcode = PyList_Append(rdn, attr);
1222 Py_DECREF(attr);
1223 if (retcode < 0)
1224 goto fail1;
1225 }
1226 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001227 if (rdn != NULL) {
1228 if (PyList_GET_SIZE(rdn) > 0) {
1229 rdnt = PyList_AsTuple(rdn);
1230 Py_DECREF(rdn);
1231 if (rdnt == NULL)
1232 goto fail0;
1233 retcode = PyList_Append(dn, rdnt);
1234 Py_DECREF(rdnt);
1235 if (retcode < 0)
1236 goto fail0;
1237 }
1238 else {
1239 Py_DECREF(rdn);
1240 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 /* convert list to tuple */
1244 rdnt = PyList_AsTuple(dn);
1245 Py_DECREF(dn);
1246 if (rdnt == NULL)
1247 return NULL;
1248 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249
1250 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252
1253 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 Py_XDECREF(dn);
1255 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256}
1257
1258static PyObject *
1259_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 /* this code follows the procedure outlined in
1262 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1263 function to extract the STACK_OF(GENERAL_NAME),
1264 then iterates through the stack to add the
1265 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001266
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001267 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001269 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 GENERAL_NAMES *names = NULL;
1271 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 BIO *biobuf = NULL;
1273 char buf[2048];
1274 char *vptr;
1275 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 if (certificate == NULL)
1278 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 /* get a memory buffer */
1281 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001282 if (biobuf == NULL) {
1283 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1284 return NULL;
1285 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001287 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1288 certificate, NID_subject_alt_name, NULL, NULL);
1289 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 if (peer_alt_names == Py_None) {
1291 peer_alt_names = PyList_New(0);
1292 if (peer_alt_names == NULL)
1293 goto fail;
1294 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001298 int gntype;
1299 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001302 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001303 switch (gntype) {
1304 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 /* we special-case DirName as a tuple of
1306 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001307
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 t = PyTuple_New(2);
1309 if (t == NULL) {
1310 goto fail;
1311 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 v = PyUnicode_FromString("DirName");
1314 if (v == NULL) {
1315 Py_DECREF(t);
1316 goto fail;
1317 }
1318 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 v = _create_tuple_for_X509_NAME (name->d.dirn);
1321 if (v == NULL) {
1322 Py_DECREF(t);
1323 goto fail;
1324 }
1325 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001326 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001327
Christian Heimes824f7f32013-08-17 00:54:47 +02001328 case GEN_EMAIL:
1329 case GEN_DNS:
1330 case GEN_URI:
1331 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1332 correctly, CVE-2013-4238 */
1333 t = PyTuple_New(2);
1334 if (t == NULL)
1335 goto fail;
1336 switch (gntype) {
1337 case GEN_EMAIL:
1338 v = PyUnicode_FromString("email");
1339 as = name->d.rfc822Name;
1340 break;
1341 case GEN_DNS:
1342 v = PyUnicode_FromString("DNS");
1343 as = name->d.dNSName;
1344 break;
1345 case GEN_URI:
1346 v = PyUnicode_FromString("URI");
1347 as = name->d.uniformResourceIdentifier;
1348 break;
1349 }
1350 if (v == NULL) {
1351 Py_DECREF(t);
1352 goto fail;
1353 }
1354 PyTuple_SET_ITEM(t, 0, v);
1355 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1356 ASN1_STRING_length(as));
1357 if (v == NULL) {
1358 Py_DECREF(t);
1359 goto fail;
1360 }
1361 PyTuple_SET_ITEM(t, 1, v);
1362 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001363
Christian Heimes1c03abd2016-09-06 23:25:35 +02001364 case GEN_RID:
1365 t = PyTuple_New(2);
1366 if (t == NULL)
1367 goto fail;
1368
1369 v = PyUnicode_FromString("Registered ID");
1370 if (v == NULL) {
1371 Py_DECREF(t);
1372 goto fail;
1373 }
1374 PyTuple_SET_ITEM(t, 0, v);
1375
1376 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1377 if (len < 0) {
1378 Py_DECREF(t);
1379 _setSSLError(NULL, 0, __FILE__, __LINE__);
1380 goto fail;
1381 } else if (len >= (int)sizeof(buf)) {
1382 v = PyUnicode_FromString("<INVALID>");
1383 } else {
1384 v = PyUnicode_FromStringAndSize(buf, len);
1385 }
1386 if (v == NULL) {
1387 Py_DECREF(t);
1388 goto fail;
1389 }
1390 PyTuple_SET_ITEM(t, 1, v);
1391 break;
1392
Christian Heimes824f7f32013-08-17 00:54:47 +02001393 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001395 switch (gntype) {
1396 /* check for new general name type */
1397 case GEN_OTHERNAME:
1398 case GEN_X400:
1399 case GEN_EDIPARTY:
1400 case GEN_IPADD:
1401 case GEN_RID:
1402 break;
1403 default:
1404 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1405 "Unknown general name type %d",
1406 gntype) == -1) {
1407 goto fail;
1408 }
1409 break;
1410 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 (void) BIO_reset(biobuf);
1412 GENERAL_NAME_print(biobuf, name);
1413 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1414 if (len < 0) {
1415 _setSSLError(NULL, 0, __FILE__, __LINE__);
1416 goto fail;
1417 }
1418 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001419 if (vptr == NULL) {
1420 PyErr_Format(PyExc_ValueError,
1421 "Invalid value %.200s",
1422 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001424 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 t = PyTuple_New(2);
1426 if (t == NULL)
1427 goto fail;
1428 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1429 if (v == NULL) {
1430 Py_DECREF(t);
1431 goto fail;
1432 }
1433 PyTuple_SET_ITEM(t, 0, v);
1434 v = PyUnicode_FromStringAndSize((vptr + 1),
1435 (len - (vptr - buf + 1)));
1436 if (v == NULL) {
1437 Py_DECREF(t);
1438 goto fail;
1439 }
1440 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001441 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001442 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446 if (PyList_Append(peer_alt_names, t) < 0) {
1447 Py_DECREF(t);
1448 goto fail;
1449 }
1450 Py_DECREF(t);
1451 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001452 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 }
1454 BIO_free(biobuf);
1455 if (peer_alt_names != Py_None) {
1456 v = PyList_AsTuple(peer_alt_names);
1457 Py_DECREF(peer_alt_names);
1458 return v;
1459 } else {
1460 return peer_alt_names;
1461 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001462
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463
1464 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001465 if (biobuf != NULL)
1466 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001468 if (peer_alt_names != Py_None) {
1469 Py_XDECREF(peer_alt_names);
1470 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473}
1474
1475static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001476_get_aia_uri(X509 *certificate, int nid) {
1477 PyObject *lst = NULL, *ostr = NULL;
1478 int i, result;
1479 AUTHORITY_INFO_ACCESS *info;
1480
1481 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001482 if (info == NULL)
1483 return Py_None;
1484 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1485 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001486 return Py_None;
1487 }
1488
1489 if ((lst = PyList_New(0)) == NULL) {
1490 goto fail;
1491 }
1492
1493 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1494 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1495 ASN1_IA5STRING *uri;
1496
1497 if ((OBJ_obj2nid(ad->method) != nid) ||
1498 (ad->location->type != GEN_URI)) {
1499 continue;
1500 }
1501 uri = ad->location->d.uniformResourceIdentifier;
1502 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1503 uri->length);
1504 if (ostr == NULL) {
1505 goto fail;
1506 }
1507 result = PyList_Append(lst, ostr);
1508 Py_DECREF(ostr);
1509 if (result < 0) {
1510 goto fail;
1511 }
1512 }
1513 AUTHORITY_INFO_ACCESS_free(info);
1514
1515 /* convert to tuple or None */
1516 if (PyList_Size(lst) == 0) {
1517 Py_DECREF(lst);
1518 return Py_None;
1519 } else {
1520 PyObject *tup;
1521 tup = PyList_AsTuple(lst);
1522 Py_DECREF(lst);
1523 return tup;
1524 }
1525
1526 fail:
1527 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001528 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 return NULL;
1530}
1531
1532static PyObject *
1533_get_crl_dp(X509 *certificate) {
1534 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001535 int i, j;
1536 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001537
Christian Heimes598894f2016-09-05 23:19:05 +02001538 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001539
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001540 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001541 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001542
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001543 lst = PyList_New(0);
1544 if (lst == NULL)
1545 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001546
1547 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1548 DIST_POINT *dp;
1549 STACK_OF(GENERAL_NAME) *gns;
1550
1551 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001552 if (dp->distpoint == NULL) {
1553 /* Ignore empty DP value, CVE-2019-5010 */
1554 continue;
1555 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001556 gns = dp->distpoint->name.fullname;
1557
1558 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1559 GENERAL_NAME *gn;
1560 ASN1_IA5STRING *uri;
1561 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001562 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001563
1564 gn = sk_GENERAL_NAME_value(gns, j);
1565 if (gn->type != GEN_URI) {
1566 continue;
1567 }
1568 uri = gn->d.uniformResourceIdentifier;
1569 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1570 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001571 if (ouri == NULL)
1572 goto done;
1573
1574 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001575 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001576 if (err < 0)
1577 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001578 }
1579 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001580
1581 /* Convert to tuple. */
1582 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1583
1584 done:
1585 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001586 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001587 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001588}
1589
1590static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001591_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 PyObject *retval = NULL;
1594 BIO *biobuf = NULL;
1595 PyObject *peer;
1596 PyObject *peer_alt_names = NULL;
1597 PyObject *issuer;
1598 PyObject *version;
1599 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001600 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 ASN1_INTEGER *serialNumber;
1602 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001603 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 ASN1_TIME *notBefore, *notAfter;
1605 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 retval = PyDict_New();
1608 if (retval == NULL)
1609 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 peer = _create_tuple_for_X509_NAME(
1612 X509_get_subject_name(certificate));
1613 if (peer == NULL)
1614 goto fail0;
1615 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1616 Py_DECREF(peer);
1617 goto fail0;
1618 }
1619 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001620
Antoine Pitroufb046912010-11-09 20:21:19 +00001621 issuer = _create_tuple_for_X509_NAME(
1622 X509_get_issuer_name(certificate));
1623 if (issuer == NULL)
1624 goto fail0;
1625 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001627 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001629 Py_DECREF(issuer);
1630
1631 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001632 if (version == NULL)
1633 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001634 if (PyDict_SetItemString(retval, "version", version) < 0) {
1635 Py_DECREF(version);
1636 goto fail0;
1637 }
1638 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 /* get a memory buffer */
1641 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001642 if (biobuf == NULL) {
1643 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1644 goto fail0;
1645 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001646
Antoine Pitroufb046912010-11-09 20:21:19 +00001647 (void) BIO_reset(biobuf);
1648 serialNumber = X509_get_serialNumber(certificate);
1649 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1650 i2a_ASN1_INTEGER(biobuf, serialNumber);
1651 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1652 if (len < 0) {
1653 _setSSLError(NULL, 0, __FILE__, __LINE__);
1654 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001656 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1657 if (sn_obj == NULL)
1658 goto fail1;
1659 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1660 Py_DECREF(sn_obj);
1661 goto fail1;
1662 }
1663 Py_DECREF(sn_obj);
1664
1665 (void) BIO_reset(biobuf);
1666 notBefore = X509_get_notBefore(certificate);
1667 ASN1_TIME_print(biobuf, notBefore);
1668 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1669 if (len < 0) {
1670 _setSSLError(NULL, 0, __FILE__, __LINE__);
1671 goto fail1;
1672 }
1673 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1674 if (pnotBefore == NULL)
1675 goto fail1;
1676 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1677 Py_DECREF(pnotBefore);
1678 goto fail1;
1679 }
1680 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 (void) BIO_reset(biobuf);
1683 notAfter = X509_get_notAfter(certificate);
1684 ASN1_TIME_print(biobuf, notAfter);
1685 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1686 if (len < 0) {
1687 _setSSLError(NULL, 0, __FILE__, __LINE__);
1688 goto fail1;
1689 }
1690 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1691 if (pnotAfter == NULL)
1692 goto fail1;
1693 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1694 Py_DECREF(pnotAfter);
1695 goto fail1;
1696 }
1697 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 peer_alt_names = _get_peer_alt_names(certificate);
1702 if (peer_alt_names == NULL)
1703 goto fail1;
1704 else if (peer_alt_names != Py_None) {
1705 if (PyDict_SetItemString(retval, "subjectAltName",
1706 peer_alt_names) < 0) {
1707 Py_DECREF(peer_alt_names);
1708 goto fail1;
1709 }
1710 Py_DECREF(peer_alt_names);
1711 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001712
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001713 /* Authority Information Access: OCSP URIs */
1714 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1715 if (obj == NULL) {
1716 goto fail1;
1717 } else if (obj != Py_None) {
1718 result = PyDict_SetItemString(retval, "OCSP", obj);
1719 Py_DECREF(obj);
1720 if (result < 0) {
1721 goto fail1;
1722 }
1723 }
1724
1725 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1726 if (obj == NULL) {
1727 goto fail1;
1728 } else if (obj != Py_None) {
1729 result = PyDict_SetItemString(retval, "caIssuers", obj);
1730 Py_DECREF(obj);
1731 if (result < 0) {
1732 goto fail1;
1733 }
1734 }
1735
1736 /* CDP (CRL distribution points) */
1737 obj = _get_crl_dp(certificate);
1738 if (obj == NULL) {
1739 goto fail1;
1740 } else if (obj != Py_None) {
1741 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1742 Py_DECREF(obj);
1743 if (result < 0) {
1744 goto fail1;
1745 }
1746 }
1747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 BIO_free(biobuf);
1749 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001750
1751 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 if (biobuf != NULL)
1753 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001754 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 Py_XDECREF(retval);
1756 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001757}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758
Christian Heimes9a5395a2013-06-17 15:44:12 +02001759static PyObject *
1760_certificate_to_der(X509 *certificate)
1761{
1762 unsigned char *bytes_buf = NULL;
1763 int len;
1764 PyObject *retval;
1765
1766 bytes_buf = NULL;
1767 len = i2d_X509(certificate, &bytes_buf);
1768 if (len < 0) {
1769 _setSSLError(NULL, 0, __FILE__, __LINE__);
1770 return NULL;
1771 }
1772 /* this is actually an immutable bytes sequence */
1773 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1774 OPENSSL_free(bytes_buf);
1775 return retval;
1776}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001778/*[clinic input]
1779_ssl._test_decode_cert
1780 path: object(converter="PyUnicode_FSConverter")
1781 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001783[clinic start generated code]*/
1784
1785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001786_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1787/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001788{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 X509 *x=NULL;
1791 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1794 PyErr_SetString(PySSLErrorObject,
1795 "Can't malloc memory to read file");
1796 goto fail0;
1797 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001798
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001799 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 PyErr_SetString(PySSLErrorObject,
1801 "Can't open file");
1802 goto fail0;
1803 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1806 if (x == NULL) {
1807 PyErr_SetString(PySSLErrorObject,
1808 "Error decoding PEM-encoded file");
1809 goto fail0;
1810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001811
Antoine Pitroufb046912010-11-09 20:21:19 +00001812 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001813 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814
1815 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001816 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 if (cert != NULL) BIO_free(cert);
1818 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001819}
1820
1821
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001822/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001823_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001824 der as binary_mode: bool = False
1825 /
1826
1827Returns the certificate for the peer.
1828
1829If no certificate was provided, returns None. If a certificate was
1830provided, but not validated, returns an empty dictionary. Otherwise
1831returns a dict containing information about the peer certificate.
1832
1833If the optional argument is True, returns a DER-encoded copy of the
1834peer certificate, or None if no certificate was provided. This will
1835return the certificate even if it wasn't validated.
1836[clinic start generated code]*/
1837
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001838static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001839_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1840/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001841{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001843 X509 *peer_cert;
1844 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001845
Christian Heimes66dc33b2017-05-23 16:02:02 -07001846 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001847 PyErr_SetString(PyExc_ValueError,
1848 "handshake not done yet");
1849 return NULL;
1850 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001851 peer_cert = SSL_get_peer_certificate(self->ssl);
1852 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001854
Antoine Pitrou721738f2012-08-15 23:20:39 +02001855 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001857 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001859 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001861 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001863 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001865 X509_free(peer_cert);
1866 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867}
1868
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001869static PyObject *
1870cipher_to_tuple(const SSL_CIPHER *cipher)
1871{
1872 const char *cipher_name, *cipher_protocol;
1873 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 if (retval == NULL)
1875 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001876
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001877 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001879 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 PyTuple_SET_ITEM(retval, 0, Py_None);
1881 } else {
1882 v = PyUnicode_FromString(cipher_name);
1883 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001884 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 PyTuple_SET_ITEM(retval, 0, v);
1886 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001887
1888 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001890 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 PyTuple_SET_ITEM(retval, 1, Py_None);
1892 } else {
1893 v = PyUnicode_FromString(cipher_protocol);
1894 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001895 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 PyTuple_SET_ITEM(retval, 1, v);
1897 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001898
1899 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001901 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001902 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001905
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001906 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 Py_DECREF(retval);
1908 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001909}
1910
Christian Heimes25bfcd52016-09-06 00:04:45 +02001911#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1912static PyObject *
1913cipher_to_dict(const SSL_CIPHER *cipher)
1914{
1915 const char *cipher_name, *cipher_protocol;
1916
1917 unsigned long cipher_id;
1918 int alg_bits, strength_bits, len;
1919 char buf[512] = {0};
1920#if OPENSSL_VERSION_1_1
1921 int aead, nid;
1922 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1923#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001924
1925 /* can be NULL */
1926 cipher_name = SSL_CIPHER_get_name(cipher);
1927 cipher_protocol = SSL_CIPHER_get_version(cipher);
1928 cipher_id = SSL_CIPHER_get_id(cipher);
1929 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001930 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1931 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001932 if (len > 1 && buf[len-1] == '\n')
1933 buf[len-1] = '\0';
1934 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1935
1936#if OPENSSL_VERSION_1_1
1937 aead = SSL_CIPHER_is_aead(cipher);
1938 nid = SSL_CIPHER_get_cipher_nid(cipher);
1939 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1940 nid = SSL_CIPHER_get_digest_nid(cipher);
1941 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1942 nid = SSL_CIPHER_get_kx_nid(cipher);
1943 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1944 nid = SSL_CIPHER_get_auth_nid(cipher);
1945 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1946#endif
1947
Victor Stinner410b9882016-09-12 12:00:23 +02001948 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001949 "{sksssssssisi"
1950#if OPENSSL_VERSION_1_1
1951 "sOssssssss"
1952#endif
1953 "}",
1954 "id", cipher_id,
1955 "name", cipher_name,
1956 "protocol", cipher_protocol,
1957 "description", buf,
1958 "strength_bits", strength_bits,
1959 "alg_bits", alg_bits
1960#if OPENSSL_VERSION_1_1
1961 ,"aead", aead ? Py_True : Py_False,
1962 "symmetric", skcipher,
1963 "digest", digest,
1964 "kea", kx,
1965 "auth", auth
1966#endif
1967 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001968}
1969#endif
1970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001971/*[clinic input]
1972_ssl._SSLSocket.shared_ciphers
1973[clinic start generated code]*/
1974
1975static PyObject *
1976_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1977/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001978{
1979 STACK_OF(SSL_CIPHER) *ciphers;
1980 int i;
1981 PyObject *res;
1982
Christian Heimes598894f2016-09-05 23:19:05 +02001983 ciphers = SSL_get_ciphers(self->ssl);
1984 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001985 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001986 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1987 if (!res)
1988 return NULL;
1989 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1990 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1991 if (!tup) {
1992 Py_DECREF(res);
1993 return NULL;
1994 }
1995 PyList_SET_ITEM(res, i, tup);
1996 }
1997 return res;
1998}
1999
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000/*[clinic input]
2001_ssl._SSLSocket.cipher
2002[clinic start generated code]*/
2003
2004static PyObject *
2005_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2006/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002007{
2008 const SSL_CIPHER *current;
2009
2010 if (self->ssl == NULL)
2011 Py_RETURN_NONE;
2012 current = SSL_get_current_cipher(self->ssl);
2013 if (current == NULL)
2014 Py_RETURN_NONE;
2015 return cipher_to_tuple(current);
2016}
2017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002018/*[clinic input]
2019_ssl._SSLSocket.version
2020[clinic start generated code]*/
2021
2022static PyObject *
2023_ssl__SSLSocket_version_impl(PySSLSocket *self)
2024/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002025{
2026 const char *version;
2027
2028 if (self->ssl == NULL)
2029 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002030 if (!SSL_is_init_finished(self->ssl)) {
2031 /* handshake not finished */
2032 Py_RETURN_NONE;
2033 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002034 version = SSL_get_version(self->ssl);
2035 if (!strcmp(version, "unknown"))
2036 Py_RETURN_NONE;
2037 return PyUnicode_FromString(version);
2038}
2039
Christian Heimes29eab552018-02-25 12:31:33 +01002040#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002041/*[clinic input]
2042_ssl._SSLSocket.selected_npn_protocol
2043[clinic start generated code]*/
2044
2045static PyObject *
2046_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2047/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2048{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002049 const unsigned char *out;
2050 unsigned int outlen;
2051
Victor Stinner4569cd52013-06-23 14:58:43 +02002052 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002053 &out, &outlen);
2054
2055 if (out == NULL)
2056 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002057 return PyUnicode_FromStringAndSize((char *)out, outlen);
2058}
2059#endif
2060
Christian Heimes29eab552018-02-25 12:31:33 +01002061#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002062/*[clinic input]
2063_ssl._SSLSocket.selected_alpn_protocol
2064[clinic start generated code]*/
2065
2066static PyObject *
2067_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2068/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2069{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002070 const unsigned char *out;
2071 unsigned int outlen;
2072
2073 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2074
2075 if (out == NULL)
2076 Py_RETURN_NONE;
2077 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002078}
2079#endif
2080
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002081/*[clinic input]
2082_ssl._SSLSocket.compression
2083[clinic start generated code]*/
2084
2085static PyObject *
2086_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2087/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2088{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002089#ifdef OPENSSL_NO_COMP
2090 Py_RETURN_NONE;
2091#else
2092 const COMP_METHOD *comp_method;
2093 const char *short_name;
2094
2095 if (self->ssl == NULL)
2096 Py_RETURN_NONE;
2097 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002098 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002099 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002100 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002101 if (short_name == NULL)
2102 Py_RETURN_NONE;
2103 return PyUnicode_DecodeFSDefault(short_name);
2104#endif
2105}
2106
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002107static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2108 Py_INCREF(self->ctx);
2109 return self->ctx;
2110}
2111
2112static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2113 void *closure) {
2114
2115 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002116#if !HAVE_SNI
2117 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2118 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002119 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002120#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002121 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002122 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002123 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002124#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002125 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002126 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002127 return -1;
2128 }
2129
2130 return 0;
2131}
2132
2133PyDoc_STRVAR(PySSL_set_context_doc,
2134"_setter_context(ctx)\n\
2135\
2136This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002137used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002138on the SSLContext to change the certificate information associated with the\n\
2139SSLSocket before the cryptographic exchange handshake messages\n");
2140
2141
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002142static PyObject *
2143PySSL_get_server_side(PySSLSocket *self, void *c)
2144{
2145 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2146}
2147
2148PyDoc_STRVAR(PySSL_get_server_side_doc,
2149"Whether this is a server-side socket.");
2150
2151static PyObject *
2152PySSL_get_server_hostname(PySSLSocket *self, void *c)
2153{
2154 if (self->server_hostname == NULL)
2155 Py_RETURN_NONE;
2156 Py_INCREF(self->server_hostname);
2157 return self->server_hostname;
2158}
2159
2160PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2161"The currently set server hostname (for SNI).");
2162
2163static PyObject *
2164PySSL_get_owner(PySSLSocket *self, void *c)
2165{
2166 PyObject *owner;
2167
2168 if (self->owner == NULL)
2169 Py_RETURN_NONE;
2170
2171 owner = PyWeakref_GetObject(self->owner);
2172 Py_INCREF(owner);
2173 return owner;
2174}
2175
2176static int
2177PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2178{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002179 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002180 if (self->owner == NULL)
2181 return -1;
2182 return 0;
2183}
2184
2185PyDoc_STRVAR(PySSL_get_owner_doc,
2186"The Python-level owner of this object.\
2187Passed as \"self\" in servername callback.");
2188
Christian Heimesc7f70692019-05-31 11:44:05 +02002189static int
2190PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2191{
2192 Py_VISIT(self->exc_type);
2193 Py_VISIT(self->exc_value);
2194 Py_VISIT(self->exc_tb);
2195 return 0;
2196}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002197
Christian Heimesc7f70692019-05-31 11:44:05 +02002198static int
2199PySSL_clear(PySSLSocket *self)
2200{
2201 Py_CLEAR(self->exc_type);
2202 Py_CLEAR(self->exc_value);
2203 Py_CLEAR(self->exc_tb);
2204 return 0;
2205}
2206
2207static void
2208PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002209{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 if (self->ssl)
2211 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002213 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002214 Py_XDECREF(self->server_hostname);
2215 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002217}
2218
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002219/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002220 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002221 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002222 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002223
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002224static int
Victor Stinner14690702015-04-06 22:46:13 +02002225PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002226{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002227 int rc;
2228#ifdef HAVE_POLL
2229 struct pollfd pollfd;
2230 _PyTime_t ms;
2231#else
2232 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 fd_set fds;
2234 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002235#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002238 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002239 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002240 else if (timeout < 0) {
2241 if (s->sock_timeout > 0)
2242 return SOCKET_HAS_TIMED_OUT;
2243 else
2244 return SOCKET_IS_BLOCKING;
2245 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002248 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 /* Prefer poll, if available, since you can poll() any fd
2252 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002253#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002254 pollfd.fd = s->sock_fd;
2255 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002256
Victor Stinner14690702015-04-06 22:46:13 +02002257 /* timeout is in seconds, poll() uses milliseconds */
2258 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002259 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002260
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002261 PySSL_BEGIN_ALLOW_THREADS
2262 rc = poll(&pollfd, 1, (int)ms);
2263 PySSL_END_ALLOW_THREADS
2264#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002266 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002268
Victor Stinner14690702015-04-06 22:46:13 +02002269 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 FD_ZERO(&fds);
2272 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002273
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002274 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002276 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002278 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002280 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002282#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2285 (when we are able to write or when there's something to read) */
2286 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002287}
2288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002289/*[clinic input]
2290_ssl._SSLSocket.write
2291 b: Py_buffer
2292 /
2293
2294Writes the bytes-like object b into the SSL object.
2295
2296Returns the number of bytes written.
2297[clinic start generated code]*/
2298
2299static PyObject *
2300_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2301/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002302{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 int len;
2304 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002305 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002307 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002308 _PyTime_t timeout, deadline = 0;
2309 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002310
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002311 if (sock != NULL) {
2312 if (((PyObject*)sock) == Py_None) {
2313 _setSSLError("Underlying socket connection gone",
2314 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2315 return NULL;
2316 }
2317 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 }
2319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002320 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002321 PyErr_Format(PyExc_OverflowError,
2322 "string longer than %d bytes", INT_MAX);
2323 goto error;
2324 }
2325
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002326 if (sock != NULL) {
2327 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002328 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002329 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2330 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2331 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332
Victor Stinner14690702015-04-06 22:46:13 +02002333 timeout = GET_SOCKET_TIMEOUT(sock);
2334 has_timeout = (timeout > 0);
2335 if (has_timeout)
2336 deadline = _PyTime_GetMonotonicClock() + timeout;
2337
2338 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002340 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 "The write operation timed out");
2342 goto error;
2343 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2344 PyErr_SetString(PySSLErrorObject,
2345 "Underlying socket has been closed.");
2346 goto error;
2347 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2348 PyErr_SetString(PySSLErrorObject,
2349 "Underlying socket too large for select().");
2350 goto error;
2351 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002355 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002356 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002358 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002359
2360 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002362
Victor Stinner14690702015-04-06 22:46:13 +02002363 if (has_timeout)
2364 timeout = deadline - _PyTime_GetMonotonicClock();
2365
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002366 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002367 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002368 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002369 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 } else {
2371 sockstate = SOCKET_OPERATION_OK;
2372 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002375 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 "The write operation timed out");
2377 goto error;
2378 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2379 PyErr_SetString(PySSLErrorObject,
2380 "Underlying socket has been closed.");
2381 goto error;
2382 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2383 break;
2384 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002385 } while (err.ssl == SSL_ERROR_WANT_READ ||
2386 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002387
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002388 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002389 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002391 if (PySSL_ChainExceptions(self) < 0)
2392 return NULL;
2393 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002394error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002395 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002396 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002398}
2399
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002400/*[clinic input]
2401_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002402
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002403Returns the number of already decrypted bytes available for read, pending on the connection.
2404[clinic start generated code]*/
2405
2406static PyObject *
2407_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2408/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002409{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002411 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 PySSL_BEGIN_ALLOW_THREADS
2414 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002415 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002416 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002417 self->err = err;
2418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 if (count < 0)
2420 return PySSL_SetError(self, count, __FILE__, __LINE__);
2421 else
2422 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002423}
2424
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002425/*[clinic input]
2426_ssl._SSLSocket.read
2427 size as len: int
2428 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002429 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002430 ]
2431 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002432
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002433Read up to size bytes from the SSL socket.
2434[clinic start generated code]*/
2435
2436static PyObject *
2437_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2438 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002439/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002440{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002443 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002444 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002445 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002447 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002448 _PyTime_t timeout, deadline = 0;
2449 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002450
Martin Panter5503d472016-03-27 05:35:19 +00002451 if (!group_right_1 && len < 0) {
2452 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2453 return NULL;
2454 }
2455
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002456 if (sock != NULL) {
2457 if (((PyObject*)sock) == Py_None) {
2458 _setSSLError("Underlying socket connection gone",
2459 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2460 return NULL;
2461 }
2462 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002463 }
2464
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002465 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002466 dest = PyBytes_FromStringAndSize(NULL, len);
2467 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002468 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002469 if (len == 0) {
2470 Py_XDECREF(sock);
2471 return dest;
2472 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002473 mem = PyBytes_AS_STRING(dest);
2474 }
2475 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002476 mem = buffer->buf;
2477 if (len <= 0 || len > buffer->len) {
2478 len = (int) buffer->len;
2479 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002480 PyErr_SetString(PyExc_OverflowError,
2481 "maximum length can't fit in a C 'int'");
2482 goto error;
2483 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002484 if (len == 0) {
2485 count = 0;
2486 goto done;
2487 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002488 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002489 }
2490
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002491 if (sock != NULL) {
2492 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002493 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002494 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2495 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2496 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497
Victor Stinner14690702015-04-06 22:46:13 +02002498 timeout = GET_SOCKET_TIMEOUT(sock);
2499 has_timeout = (timeout > 0);
2500 if (has_timeout)
2501 deadline = _PyTime_GetMonotonicClock() + timeout;
2502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002503 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 PySSL_BEGIN_ALLOW_THREADS
2505 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002506 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002508 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510 if (PyErr_CheckSignals())
2511 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002512
Victor Stinner14690702015-04-06 22:46:13 +02002513 if (has_timeout)
2514 timeout = deadline - _PyTime_GetMonotonicClock();
2515
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002516 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002517 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002518 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002519 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002520 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002521 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 {
2523 count = 0;
2524 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002526 else
2527 sockstate = SOCKET_OPERATION_OK;
2528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002530 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 "The read operation timed out");
2532 goto error;
2533 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2534 break;
2535 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002536 } while (err.ssl == SSL_ERROR_WANT_READ ||
2537 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 if (count <= 0) {
2540 PySSL_SetError(self, count, __FILE__, __LINE__);
2541 goto error;
2542 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002543 if (self->exc_type != NULL)
2544 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002545
2546done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002547 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002548 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002549 _PyBytes_Resize(&dest, count);
2550 return dest;
2551 }
2552 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 return PyLong_FromLong(count);
2554 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002555
2556error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002557 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002558 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002559 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002560 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002562}
2563
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002564/*[clinic input]
2565_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002566
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002567Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002568[clinic start generated code]*/
2569
2570static PyObject *
2571_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002572/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002573{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002574 _PySSLError err;
2575 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002577 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002578 _PyTime_t timeout, deadline = 0;
2579 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002580
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002581 if (sock != NULL) {
2582 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002583 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002584 _setSSLError("Underlying socket connection gone",
2585 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2586 return NULL;
2587 }
2588 Py_INCREF(sock);
2589
2590 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002591 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002592 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2593 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002594 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002595
Victor Stinner14690702015-04-06 22:46:13 +02002596 timeout = GET_SOCKET_TIMEOUT(sock);
2597 has_timeout = (timeout > 0);
2598 if (has_timeout)
2599 deadline = _PyTime_GetMonotonicClock() + timeout;
2600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 while (1) {
2602 PySSL_BEGIN_ALLOW_THREADS
2603 /* Disable read-ahead so that unwrap can work correctly.
2604 * Otherwise OpenSSL might read in too much data,
2605 * eating clear text data that happens to be
2606 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002607 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002608 * function is used and the shutdown_seen_zero != 0
2609 * condition is met.
2610 */
2611 if (self->shutdown_seen_zero)
2612 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002613 ret = SSL_shutdown(self->ssl);
2614 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002615 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002616 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002618 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002619 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002621 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002622 /* Don't loop endlessly; instead preserve legacy
2623 behaviour of trying SSL_shutdown() only twice.
2624 This looks necessary for OpenSSL < 0.9.8m */
2625 if (++zeros > 1)
2626 break;
2627 /* Shutdown was sent, now try receiving */
2628 self->shutdown_seen_zero = 1;
2629 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002630 }
2631
Victor Stinner14690702015-04-06 22:46:13 +02002632 if (has_timeout)
2633 timeout = deadline - _PyTime_GetMonotonicClock();
2634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002636 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002637 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002638 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002639 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002640 else
2641 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002643 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002644 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002645 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002646 "The read operation timed out");
2647 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002648 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002650 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002651 }
2652 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2653 PyErr_SetString(PySSLErrorObject,
2654 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002655 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002656 }
2657 else if (sockstate != SOCKET_OPERATION_OK)
2658 /* Retain the SSL error code */
2659 break;
2660 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002661 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002662 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002663 PySSL_SetError(self, ret, __FILE__, __LINE__);
2664 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002665 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002666 if (self->exc_type != NULL)
2667 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002668 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002669 /* It's already INCREF'ed */
2670 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002671 else
2672 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002673
2674error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002675 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002676 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002677 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002678}
2679
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002680/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002681_ssl._SSLSocket.get_channel_binding
2682 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002683
Christian Heimes141c5e82018-02-24 21:10:57 +01002684Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002685
Christian Heimes141c5e82018-02-24 21:10:57 +01002686Raise ValueError if the requested `cb_type` is not supported. Return bytes
2687of the data or None if the data is not available (e.g. before the handshake).
2688Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002689[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002690
Antoine Pitroud6494802011-07-21 01:11:30 +02002691static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002692_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2693 const char *cb_type)
2694/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002695{
Antoine Pitroud6494802011-07-21 01:11:30 +02002696 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002697 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002698
Christian Heimes141c5e82018-02-24 21:10:57 +01002699 if (strcmp(cb_type, "tls-unique") == 0) {
2700 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2701 /* if session is resumed XOR we are the client */
2702 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2703 }
2704 else {
2705 /* if a new session XOR we are the server */
2706 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2707 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002708 }
2709 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002710 PyErr_Format(
2711 PyExc_ValueError,
2712 "'%s' channel binding type not implemented",
2713 cb_type
2714 );
2715 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002716 }
2717
2718 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002719 if (len == 0)
2720 Py_RETURN_NONE;
2721
Christian Heimes141c5e82018-02-24 21:10:57 +01002722 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002723}
2724
Christian Heimes9fb051f2018-09-23 08:32:31 +02002725/*[clinic input]
2726_ssl._SSLSocket.verify_client_post_handshake
2727
2728Initiate TLS 1.3 post-handshake authentication
2729[clinic start generated code]*/
2730
2731static PyObject *
2732_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2733/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2734{
2735#ifdef TLS1_3_VERSION
2736 int err = SSL_verify_client_post_handshake(self->ssl);
2737 if (err == 0)
2738 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2739 else
2740 Py_RETURN_NONE;
2741#else
2742 PyErr_SetString(PyExc_NotImplementedError,
2743 "Post-handshake auth is not supported by your "
2744 "OpenSSL version.");
2745 return NULL;
2746#endif
2747}
2748
Christian Heimes99a65702016-09-10 23:44:53 +02002749#ifdef OPENSSL_VERSION_1_1
2750
2751static SSL_SESSION*
2752_ssl_session_dup(SSL_SESSION *session) {
2753 SSL_SESSION *newsession = NULL;
2754 int slen;
2755 unsigned char *senc = NULL, *p;
2756 const unsigned char *const_p;
2757
2758 if (session == NULL) {
2759 PyErr_SetString(PyExc_ValueError, "Invalid session");
2760 goto error;
2761 }
2762
2763 /* get length */
2764 slen = i2d_SSL_SESSION(session, NULL);
2765 if (slen == 0 || slen > 0xFF00) {
2766 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2767 goto error;
2768 }
2769 if ((senc = PyMem_Malloc(slen)) == NULL) {
2770 PyErr_NoMemory();
2771 goto error;
2772 }
2773 p = senc;
2774 if (!i2d_SSL_SESSION(session, &p)) {
2775 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2776 goto error;
2777 }
2778 const_p = senc;
2779 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2780 if (session == NULL) {
2781 goto error;
2782 }
2783 PyMem_Free(senc);
2784 return newsession;
2785 error:
2786 if (senc != NULL) {
2787 PyMem_Free(senc);
2788 }
2789 return NULL;
2790}
2791#endif
2792
2793static PyObject *
2794PySSL_get_session(PySSLSocket *self, void *closure) {
2795 /* get_session can return sessions from a server-side connection,
2796 * it does not check for handshake done or client socket. */
2797 PySSLSession *pysess;
2798 SSL_SESSION *session;
2799
2800#ifdef OPENSSL_VERSION_1_1
2801 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2802 * https://github.com/openssl/openssl/issues/1550 */
2803 session = SSL_get0_session(self->ssl); /* borrowed reference */
2804 if (session == NULL) {
2805 Py_RETURN_NONE;
2806 }
2807 if ((session = _ssl_session_dup(session)) == NULL) {
2808 return NULL;
2809 }
2810#else
2811 session = SSL_get1_session(self->ssl);
2812 if (session == NULL) {
2813 Py_RETURN_NONE;
2814 }
2815#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002816 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002817 if (pysess == NULL) {
2818 SSL_SESSION_free(session);
2819 return NULL;
2820 }
2821
2822 assert(self->ctx);
2823 pysess->ctx = self->ctx;
2824 Py_INCREF(pysess->ctx);
2825 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002826 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002827 return (PyObject *)pysess;
2828}
2829
2830static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2831 void *closure)
2832 {
2833 PySSLSession *pysess;
2834#ifdef OPENSSL_VERSION_1_1
2835 SSL_SESSION *session;
2836#endif
2837 int result;
2838
2839 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002840 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002841 return -1;
2842 }
2843 pysess = (PySSLSession *)value;
2844
2845 if (self->ctx->ctx != pysess->ctx->ctx) {
2846 PyErr_SetString(PyExc_ValueError,
2847 "Session refers to a different SSLContext.");
2848 return -1;
2849 }
2850 if (self->socket_type != PY_SSL_CLIENT) {
2851 PyErr_SetString(PyExc_ValueError,
2852 "Cannot set session for server-side SSLSocket.");
2853 return -1;
2854 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002855 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002856 PyErr_SetString(PyExc_ValueError,
2857 "Cannot set session after handshake.");
2858 return -1;
2859 }
2860#ifdef OPENSSL_VERSION_1_1
2861 /* duplicate session */
2862 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2863 return -1;
2864 }
2865 result = SSL_set_session(self->ssl, session);
2866 /* free duplicate, SSL_set_session() bumps ref count */
2867 SSL_SESSION_free(session);
2868#else
2869 result = SSL_set_session(self->ssl, pysess->session);
2870#endif
2871 if (result == 0) {
2872 _setSSLError(NULL, 0, __FILE__, __LINE__);
2873 return -1;
2874 }
2875 return 0;
2876}
2877
2878PyDoc_STRVAR(PySSL_set_session_doc,
2879"_setter_session(session)\n\
2880\
2881Get / set SSLSession.");
2882
2883static PyObject *
2884PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2885 if (SSL_session_reused(self->ssl)) {
2886 Py_RETURN_TRUE;
2887 } else {
2888 Py_RETURN_FALSE;
2889 }
2890}
2891
2892PyDoc_STRVAR(PySSL_get_session_reused_doc,
2893"Was the client session reused during handshake?");
2894
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002895static PyGetSetDef ssl_getsetlist[] = {
2896 {"context", (getter) PySSL_get_context,
2897 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002898 {"server_side", (getter) PySSL_get_server_side, NULL,
2899 PySSL_get_server_side_doc},
2900 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2901 PySSL_get_server_hostname_doc},
2902 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2903 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002904 {"session", (getter) PySSL_get_session,
2905 (setter) PySSL_set_session, PySSL_set_session_doc},
2906 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2907 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002908 {NULL}, /* sentinel */
2909};
2910
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002911static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002912 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2913 _SSL__SSLSOCKET_WRITE_METHODDEF
2914 _SSL__SSLSOCKET_READ_METHODDEF
2915 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002916 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2917 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002918 _SSL__SSLSOCKET_CIPHER_METHODDEF
2919 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2920 _SSL__SSLSOCKET_VERSION_METHODDEF
2921 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2922 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2923 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2924 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002925 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002926 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002927};
2928
Antoine Pitrou152efa22010-05-16 18:19:27 +00002929static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002930 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002931 "_ssl._SSLSocket", /*tp_name*/
2932 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002933 0, /*tp_itemsize*/
2934 /* methods */
2935 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002936 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002937 0, /*tp_getattr*/
2938 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002939 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002940 0, /*tp_repr*/
2941 0, /*tp_as_number*/
2942 0, /*tp_as_sequence*/
2943 0, /*tp_as_mapping*/
2944 0, /*tp_hash*/
2945 0, /*tp_call*/
2946 0, /*tp_str*/
2947 0, /*tp_getattro*/
2948 0, /*tp_setattro*/
2949 0, /*tp_as_buffer*/
2950 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2951 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02002952 (traverseproc) PySSL_traverse, /*tp_traverse*/
2953 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002954 0, /*tp_richcompare*/
2955 0, /*tp_weaklistoffset*/
2956 0, /*tp_iter*/
2957 0, /*tp_iternext*/
2958 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002959 0, /*tp_members*/
2960 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002961};
2962
Antoine Pitrou152efa22010-05-16 18:19:27 +00002963
2964/*
2965 * _SSLContext objects
2966 */
2967
Christian Heimes5fe668c2016-09-12 00:01:11 +02002968static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002969_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002970{
2971 int mode;
2972 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2973
2974 switch(n) {
2975 case PY_SSL_CERT_NONE:
2976 mode = SSL_VERIFY_NONE;
2977 break;
2978 case PY_SSL_CERT_OPTIONAL:
2979 mode = SSL_VERIFY_PEER;
2980 break;
2981 case PY_SSL_CERT_REQUIRED:
2982 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2983 break;
2984 default:
2985 PyErr_SetString(PyExc_ValueError,
2986 "invalid value for verify_mode");
2987 return -1;
2988 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02002989#ifdef TLS1_3_VERSION
2990 if (self->post_handshake_auth)
2991 mode |= SSL_VERIFY_POST_HANDSHAKE;
2992#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002993 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002994 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2995 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002996 return 0;
2997}
2998
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002999/*[clinic input]
3000@classmethod
3001_ssl._SSLContext.__new__
3002 protocol as proto_version: int
3003 /
3004[clinic start generated code]*/
3005
Antoine Pitrou152efa22010-05-16 18:19:27 +00003006static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003007_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3008/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003010 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003011 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003012 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003013 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003014 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003015#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003016 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003017#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003018
Antoine Pitrou152efa22010-05-16 18:19:27 +00003019 PySSL_BEGIN_ALLOW_THREADS
3020 if (proto_version == PY_SSL_VERSION_TLS1)
3021 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003022#if HAVE_TLSv1_2
3023 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3024 ctx = SSL_CTX_new(TLSv1_1_method());
3025 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3026 ctx = SSL_CTX_new(TLSv1_2_method());
3027#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003028#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003029 else if (proto_version == PY_SSL_VERSION_SSL3)
3030 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003031#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003032#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033 else if (proto_version == PY_SSL_VERSION_SSL2)
3034 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003035#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003036 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003037 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003038 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3039 ctx = SSL_CTX_new(TLS_client_method());
3040 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3041 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003042 else
3043 proto_version = -1;
3044 PySSL_END_ALLOW_THREADS
3045
3046 if (proto_version == -1) {
3047 PyErr_SetString(PyExc_ValueError,
3048 "invalid protocol version");
3049 return NULL;
3050 }
3051 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003052 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003053 return NULL;
3054 }
3055
3056 assert(type != NULL && type->tp_alloc != NULL);
3057 self = (PySSLContext *) type->tp_alloc(type, 0);
3058 if (self == NULL) {
3059 SSL_CTX_free(ctx);
3060 return NULL;
3061 }
3062 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003063 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003064 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003065 self->msg_cb = NULL;
3066#ifdef HAVE_OPENSSL_KEYLOG
3067 self->keylog_filename = NULL;
3068 self->keylog_bio = NULL;
3069#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003070#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003071 self->npn_protocols = NULL;
3072#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003073#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003074 self->alpn_protocols = NULL;
3075#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003076#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003077 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003078#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003079 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003080 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3081 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003082 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003083 Py_DECREF(self);
3084 return NULL;
3085 }
3086 } else {
3087 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003088 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003089 Py_DECREF(self);
3090 return NULL;
3091 }
3092 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003093 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003094 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3095 if (proto_version != PY_SSL_VERSION_SSL2)
3096 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003097 if (proto_version != PY_SSL_VERSION_SSL3)
3098 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003099 /* Minimal security flags for server and client side context.
3100 * Client sockets ignore server-side parameters. */
3101#ifdef SSL_OP_NO_COMPRESSION
3102 options |= SSL_OP_NO_COMPRESSION;
3103#endif
3104#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3105 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3106#endif
3107#ifdef SSL_OP_SINGLE_DH_USE
3108 options |= SSL_OP_SINGLE_DH_USE;
3109#endif
3110#ifdef SSL_OP_SINGLE_ECDH_USE
3111 options |= SSL_OP_SINGLE_ECDH_USE;
3112#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003113 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003114
Semen Zhydenko1295e112017-10-15 21:28:31 +02003115 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003116 * It's far from perfect but gives users a better head start. */
3117 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003118#if PY_SSL_DEFAULT_CIPHERS == 2
3119 /* stick to OpenSSL's default settings */
3120 result = 1;
3121#else
3122 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3123#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003124 } else {
3125 /* SSLv2 needs MD5 */
3126 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3127 }
3128 if (result == 0) {
3129 Py_DECREF(self);
3130 ERR_clear_error();
3131 PyErr_SetString(PySSLErrorObject,
3132 "No cipher can be selected.");
3133 return NULL;
3134 }
3135
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003136#if defined(SSL_MODE_RELEASE_BUFFERS)
3137 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3138 usage for no cost at all. However, don't do this for OpenSSL versions
3139 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3140 2014-0198. I can't find exactly which beta fixed this CVE, so be
3141 conservative and assume it wasn't fixed until release. We do this check
3142 at runtime to avoid problems from the dynamic linker.
3143 See #25672 for more on this. */
3144 libver = SSLeay();
3145 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3146 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3147 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3148 }
3149#endif
3150
3151
Donald Stufft8ae264c2017-03-02 11:45:29 -05003152#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003153 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3154 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003155 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3156 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003157#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003158 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3159#else
3160 {
3161 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3162 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3163 EC_KEY_free(key);
3164 }
3165#endif
3166#endif
3167
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003168#define SID_CTX "Python"
3169 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3170 sizeof(SID_CTX));
3171#undef SID_CTX
3172
Christian Heimes61d478c2018-01-27 15:51:38 +01003173 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003174#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003175 /* Improve trust chain building when cross-signed intermediate
3176 certificates are present. See https://bugs.python.org/issue23476. */
3177 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003178#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003179 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003180
Christian Heimes9fb051f2018-09-23 08:32:31 +02003181#ifdef TLS1_3_VERSION
3182 self->post_handshake_auth = 0;
3183 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3184#endif
3185
Antoine Pitrou152efa22010-05-16 18:19:27 +00003186 return (PyObject *)self;
3187}
3188
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003189static int
3190context_traverse(PySSLContext *self, visitproc visit, void *arg)
3191{
3192#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003193 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003194#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003195 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003196 return 0;
3197}
3198
3199static int
3200context_clear(PySSLContext *self)
3201{
3202#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003203 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003204#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003205 Py_CLEAR(self->msg_cb);
3206#ifdef HAVE_OPENSSL_KEYLOG
3207 Py_CLEAR(self->keylog_filename);
3208 if (self->keylog_bio != NULL) {
3209 PySSL_BEGIN_ALLOW_THREADS
3210 BIO_free_all(self->keylog_bio);
3211 PySSL_END_ALLOW_THREADS
3212 self->keylog_bio = NULL;
3213 }
3214#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003215 return 0;
3216}
3217
Antoine Pitrou152efa22010-05-16 18:19:27 +00003218static void
3219context_dealloc(PySSLContext *self)
3220{
INADA Naokia6296d32017-08-24 14:55:17 +09003221 /* bpo-31095: UnTrack is needed before calling any callbacks */
3222 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003223 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003224 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003225#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226 PyMem_FREE(self->npn_protocols);
3227#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003228#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003229 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003230#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003231 Py_TYPE(self)->tp_free(self);
3232}
3233
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003234/*[clinic input]
3235_ssl._SSLContext.set_ciphers
3236 cipherlist: str
3237 /
3238[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003239
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240static PyObject *
3241_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3242/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3243{
3244 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003245 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003246 /* Clearing the error queue is necessary on some OpenSSL versions,
3247 otherwise the error will be reported again when another SSL call
3248 is done. */
3249 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003250 PyErr_SetString(PySSLErrorObject,
3251 "No cipher can be selected.");
3252 return NULL;
3253 }
3254 Py_RETURN_NONE;
3255}
3256
Christian Heimes25bfcd52016-09-06 00:04:45 +02003257#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3258/*[clinic input]
3259_ssl._SSLContext.get_ciphers
3260[clinic start generated code]*/
3261
3262static PyObject *
3263_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3264/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3265{
3266 SSL *ssl = NULL;
3267 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003268 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003269 int i=0;
3270 PyObject *result = NULL, *dct;
3271
3272 ssl = SSL_new(self->ctx);
3273 if (ssl == NULL) {
3274 _setSSLError(NULL, 0, __FILE__, __LINE__);
3275 goto exit;
3276 }
3277 sk = SSL_get_ciphers(ssl);
3278
3279 result = PyList_New(sk_SSL_CIPHER_num(sk));
3280 if (result == NULL) {
3281 goto exit;
3282 }
3283
3284 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3285 cipher = sk_SSL_CIPHER_value(sk, i);
3286 dct = cipher_to_dict(cipher);
3287 if (dct == NULL) {
3288 Py_CLEAR(result);
3289 goto exit;
3290 }
3291 PyList_SET_ITEM(result, i, dct);
3292 }
3293
3294 exit:
3295 if (ssl != NULL)
3296 SSL_free(ssl);
3297 return result;
3298
3299}
3300#endif
3301
3302
Christian Heimes29eab552018-02-25 12:31:33 +01003303#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003304static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003305do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3306 const unsigned char *server_protocols, unsigned int server_protocols_len,
3307 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003308{
Benjamin Peterson88615022015-01-23 17:30:26 -05003309 int ret;
3310 if (client_protocols == NULL) {
3311 client_protocols = (unsigned char *)"";
3312 client_protocols_len = 0;
3313 }
3314 if (server_protocols == NULL) {
3315 server_protocols = (unsigned char *)"";
3316 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003317 }
3318
Benjamin Peterson88615022015-01-23 17:30:26 -05003319 ret = SSL_select_next_proto(out, outlen,
3320 server_protocols, server_protocols_len,
3321 client_protocols, client_protocols_len);
3322 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3323 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003324
3325 return SSL_TLSEXT_ERR_OK;
3326}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003327#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003328
Christian Heimes29eab552018-02-25 12:31:33 +01003329#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003330/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3331static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003332_advertiseNPN_cb(SSL *s,
3333 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003334 void *args)
3335{
3336 PySSLContext *ssl_ctx = (PySSLContext *) args;
3337
3338 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003339 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003340 *len = 0;
3341 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003342 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003343 *len = ssl_ctx->npn_protocols_len;
3344 }
3345
3346 return SSL_TLSEXT_ERR_OK;
3347}
3348/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3349static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003350_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003351 unsigned char **out, unsigned char *outlen,
3352 const unsigned char *server, unsigned int server_len,
3353 void *args)
3354{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003355 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003356 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003357 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003358}
3359#endif
3360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003361/*[clinic input]
3362_ssl._SSLContext._set_npn_protocols
3363 protos: Py_buffer
3364 /
3365[clinic start generated code]*/
3366
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003367static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003368_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3369 Py_buffer *protos)
3370/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003371{
Christian Heimes29eab552018-02-25 12:31:33 +01003372#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003373 PyMem_Free(self->npn_protocols);
3374 self->npn_protocols = PyMem_Malloc(protos->len);
3375 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003376 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003377 memcpy(self->npn_protocols, protos->buf, protos->len);
3378 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003379
3380 /* set both server and client callbacks, because the context can
3381 * be used to create both types of sockets */
3382 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3383 _advertiseNPN_cb,
3384 self);
3385 SSL_CTX_set_next_proto_select_cb(self->ctx,
3386 _selectNPN_cb,
3387 self);
3388
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003389 Py_RETURN_NONE;
3390#else
3391 PyErr_SetString(PyExc_NotImplementedError,
3392 "The NPN extension requires OpenSSL 1.0.1 or later.");
3393 return NULL;
3394#endif
3395}
3396
Christian Heimes29eab552018-02-25 12:31:33 +01003397#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003398static int
3399_selectALPN_cb(SSL *s,
3400 const unsigned char **out, unsigned char *outlen,
3401 const unsigned char *client_protocols, unsigned int client_protocols_len,
3402 void *args)
3403{
3404 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003405 return do_protocol_selection(1, (unsigned char **)out, outlen,
3406 ctx->alpn_protocols, ctx->alpn_protocols_len,
3407 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003408}
3409#endif
3410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003411/*[clinic input]
3412_ssl._SSLContext._set_alpn_protocols
3413 protos: Py_buffer
3414 /
3415[clinic start generated code]*/
3416
Benjamin Petersoncca27322015-01-23 16:35:37 -05003417static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003418_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3419 Py_buffer *protos)
3420/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003421{
Christian Heimes29eab552018-02-25 12:31:33 +01003422#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003423 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003424 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003425 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003426 return NULL;
3427 }
3428
Benjamin Petersoncca27322015-01-23 16:35:37 -05003429 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003430 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003431 if (!self->alpn_protocols)
3432 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003433 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003434 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003435
3436 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3437 return PyErr_NoMemory();
3438 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3439
Benjamin Petersoncca27322015-01-23 16:35:37 -05003440 Py_RETURN_NONE;
3441#else
3442 PyErr_SetString(PyExc_NotImplementedError,
3443 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3444 return NULL;
3445#endif
3446}
3447
Antoine Pitrou152efa22010-05-16 18:19:27 +00003448static PyObject *
3449get_verify_mode(PySSLContext *self, void *c)
3450{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003451 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3452 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3453 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3454 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003455 case SSL_VERIFY_NONE:
3456 return PyLong_FromLong(PY_SSL_CERT_NONE);
3457 case SSL_VERIFY_PEER:
3458 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3459 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3460 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3461 }
3462 PyErr_SetString(PySSLErrorObject,
3463 "invalid return value from SSL_CTX_get_verify_mode");
3464 return NULL;
3465}
3466
3467static int
3468set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3469{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003470 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003471 if (!PyArg_Parse(arg, "i", &n))
3472 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003473 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003474 PyErr_SetString(PyExc_ValueError,
3475 "Cannot set verify_mode to CERT_NONE when "
3476 "check_hostname is enabled.");
3477 return -1;
3478 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003479 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003480}
3481
3482static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003483get_verify_flags(PySSLContext *self, void *c)
3484{
Christian Heimes598894f2016-09-05 23:19:05 +02003485 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003486 unsigned long flags;
3487
Christian Heimes61d478c2018-01-27 15:51:38 +01003488 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003489 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003490 return PyLong_FromUnsignedLong(flags);
3491}
3492
3493static int
3494set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3495{
Christian Heimes598894f2016-09-05 23:19:05 +02003496 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003497 unsigned long new_flags, flags, set, clear;
3498
3499 if (!PyArg_Parse(arg, "k", &new_flags))
3500 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003501 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003502 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003503 clear = flags & ~new_flags;
3504 set = ~flags & new_flags;
3505 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003506 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003507 _setSSLError(NULL, 0, __FILE__, __LINE__);
3508 return -1;
3509 }
3510 }
3511 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003512 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003513 _setSSLError(NULL, 0, __FILE__, __LINE__);
3514 return -1;
3515 }
3516 }
3517 return 0;
3518}
3519
Christian Heimes698dde12018-02-27 11:54:43 +01003520/* Getter and setter for protocol version */
3521#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3522
3523
3524static int
3525set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3526{
3527 long v;
3528 int result;
3529
3530 if (!PyArg_Parse(arg, "l", &v))
3531 return -1;
3532 if (v > INT_MAX) {
3533 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3534 return -1;
3535 }
3536
3537 switch(self->protocol) {
3538 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3539 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3540 case PY_SSL_VERSION_TLS:
3541 break;
3542 default:
3543 PyErr_SetString(
3544 PyExc_ValueError,
3545 "The context's protocol doesn't support modification of "
3546 "highest and lowest version."
3547 );
3548 return -1;
3549 }
3550
3551 if (what == 0) {
3552 switch(v) {
3553 case PY_PROTO_MINIMUM_SUPPORTED:
3554 v = 0;
3555 break;
3556 case PY_PROTO_MAXIMUM_SUPPORTED:
3557 /* Emulate max for set_min_proto_version */
3558 v = PY_PROTO_MAXIMUM_AVAILABLE;
3559 break;
3560 default:
3561 break;
3562 }
3563 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3564 }
3565 else {
3566 switch(v) {
3567 case PY_PROTO_MAXIMUM_SUPPORTED:
3568 v = 0;
3569 break;
3570 case PY_PROTO_MINIMUM_SUPPORTED:
3571 /* Emulate max for set_min_proto_version */
3572 v = PY_PROTO_MINIMUM_AVAILABLE;
3573 break;
3574 default:
3575 break;
3576 }
3577 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3578 }
3579 if (result == 0) {
3580 PyErr_Format(PyExc_ValueError,
3581 "Unsupported protocol version 0x%x", v);
3582 return -1;
3583 }
3584 return 0;
3585}
3586
3587static PyObject *
3588get_minimum_version(PySSLContext *self, void *c)
3589{
3590 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3591 if (v == 0) {
3592 v = PY_PROTO_MINIMUM_SUPPORTED;
3593 }
3594 return PyLong_FromLong(v);
3595}
3596
3597static int
3598set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3599{
3600 return set_min_max_proto_version(self, arg, 0);
3601}
3602
3603static PyObject *
3604get_maximum_version(PySSLContext *self, void *c)
3605{
3606 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3607 if (v == 0) {
3608 v = PY_PROTO_MAXIMUM_SUPPORTED;
3609 }
3610 return PyLong_FromLong(v);
3611}
3612
3613static int
3614set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3615{
3616 return set_min_max_proto_version(self, arg, 1);
3617}
3618#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3619
Christian Heimes22587792013-11-21 23:56:13 +01003620static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003621get_options(PySSLContext *self, void *c)
3622{
3623 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3624}
3625
3626static int
3627set_options(PySSLContext *self, PyObject *arg, void *c)
3628{
3629 long new_opts, opts, set, clear;
3630 if (!PyArg_Parse(arg, "l", &new_opts))
3631 return -1;
3632 opts = SSL_CTX_get_options(self->ctx);
3633 clear = opts & ~new_opts;
3634 set = ~opts & new_opts;
3635 if (clear) {
3636#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3637 SSL_CTX_clear_options(self->ctx, clear);
3638#else
3639 PyErr_SetString(PyExc_ValueError,
3640 "can't clear options before OpenSSL 0.9.8m");
3641 return -1;
3642#endif
3643 }
3644 if (set)
3645 SSL_CTX_set_options(self->ctx, set);
3646 return 0;
3647}
3648
Christian Heimes1aa9a752013-12-02 02:41:19 +01003649static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003650get_host_flags(PySSLContext *self, void *c)
3651{
3652 return PyLong_FromUnsignedLong(self->hostflags);
3653}
3654
3655static int
3656set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3657{
3658 X509_VERIFY_PARAM *param;
3659 unsigned int new_flags = 0;
3660
3661 if (!PyArg_Parse(arg, "I", &new_flags))
3662 return -1;
3663
3664 param = SSL_CTX_get0_param(self->ctx);
3665 self->hostflags = new_flags;
3666 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3667 return 0;
3668}
3669
3670static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003671get_check_hostname(PySSLContext *self, void *c)
3672{
3673 return PyBool_FromLong(self->check_hostname);
3674}
3675
3676static int
3677set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3678{
3679 int check_hostname;
3680 if (!PyArg_Parse(arg, "p", &check_hostname))
3681 return -1;
3682 if (check_hostname &&
3683 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003684 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003685 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003686 return -1;
3687 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003688 }
3689 self->check_hostname = check_hostname;
3690 return 0;
3691}
3692
Christian Heimes11a14932018-02-24 02:35:08 +01003693static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003694get_post_handshake_auth(PySSLContext *self, void *c) {
3695#if TLS1_3_VERSION
3696 return PyBool_FromLong(self->post_handshake_auth);
3697#else
3698 Py_RETURN_NONE;
3699#endif
3700}
3701
3702#if TLS1_3_VERSION
3703static int
3704set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3705 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3706 int mode = SSL_CTX_get_verify_mode(self->ctx);
Zackery Spytz842acaa2018-12-17 07:52:45 -07003707 if (arg == NULL) {
3708 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3709 return -1;
3710 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003711 int pha = PyObject_IsTrue(arg);
3712
3713 if (pha == -1) {
3714 return -1;
3715 }
3716 self->post_handshake_auth = pha;
3717
3718 /* client-side socket setting, ignored by server-side */
3719 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3720
3721 /* server-side socket setting, ignored by client-side */
3722 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3723 if (pha) {
3724 mode |= SSL_VERIFY_POST_HANDSHAKE;
3725 } else {
3726 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3727 }
3728 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3729
3730 return 0;
3731}
3732#endif
3733
3734static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003735get_protocol(PySSLContext *self, void *c) {
3736 return PyLong_FromLong(self->protocol);
3737}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003738
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003739typedef struct {
3740 PyThreadState *thread_state;
3741 PyObject *callable;
3742 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003743 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003744 int error;
3745} _PySSLPasswordInfo;
3746
3747static int
3748_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3749 const char *bad_type_error)
3750{
3751 /* Set the password and size fields of a _PySSLPasswordInfo struct
3752 from a unicode, bytes, or byte array object.
3753 The password field will be dynamically allocated and must be freed
3754 by the caller */
3755 PyObject *password_bytes = NULL;
3756 const char *data = NULL;
3757 Py_ssize_t size;
3758
3759 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003760 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003761 if (!password_bytes) {
3762 goto error;
3763 }
3764 data = PyBytes_AS_STRING(password_bytes);
3765 size = PyBytes_GET_SIZE(password_bytes);
3766 } else if (PyBytes_Check(password)) {
3767 data = PyBytes_AS_STRING(password);
3768 size = PyBytes_GET_SIZE(password);
3769 } else if (PyByteArray_Check(password)) {
3770 data = PyByteArray_AS_STRING(password);
3771 size = PyByteArray_GET_SIZE(password);
3772 } else {
3773 PyErr_SetString(PyExc_TypeError, bad_type_error);
3774 goto error;
3775 }
3776
Victor Stinner9ee02032013-06-23 15:08:23 +02003777 if (size > (Py_ssize_t)INT_MAX) {
3778 PyErr_Format(PyExc_ValueError,
3779 "password cannot be longer than %d bytes", INT_MAX);
3780 goto error;
3781 }
3782
Victor Stinner11ebff22013-07-07 17:07:52 +02003783 PyMem_Free(pw_info->password);
3784 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003785 if (!pw_info->password) {
3786 PyErr_SetString(PyExc_MemoryError,
3787 "unable to allocate password buffer");
3788 goto error;
3789 }
3790 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003791 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003792
3793 Py_XDECREF(password_bytes);
3794 return 1;
3795
3796error:
3797 Py_XDECREF(password_bytes);
3798 return 0;
3799}
3800
3801static int
3802_password_callback(char *buf, int size, int rwflag, void *userdata)
3803{
3804 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3805 PyObject *fn_ret = NULL;
3806
3807 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3808
3809 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003810 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003811 if (!fn_ret) {
3812 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3813 core python API, so we could use it to add a frame here */
3814 goto error;
3815 }
3816
3817 if (!_pwinfo_set(pw_info, fn_ret,
3818 "password callback must return a string")) {
3819 goto error;
3820 }
3821 Py_CLEAR(fn_ret);
3822 }
3823
3824 if (pw_info->size > size) {
3825 PyErr_Format(PyExc_ValueError,
3826 "password cannot be longer than %d bytes", size);
3827 goto error;
3828 }
3829
3830 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3831 memcpy(buf, pw_info->password, pw_info->size);
3832 return pw_info->size;
3833
3834error:
3835 Py_XDECREF(fn_ret);
3836 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3837 pw_info->error = 1;
3838 return -1;
3839}
3840
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003841/*[clinic input]
3842_ssl._SSLContext.load_cert_chain
3843 certfile: object
3844 keyfile: object = NULL
3845 password: object = NULL
3846
3847[clinic start generated code]*/
3848
Antoine Pitroub5218772010-05-21 09:56:06 +00003849static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003850_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3851 PyObject *keyfile, PyObject *password)
3852/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003853{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003854 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003855 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3856 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003857 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003858 int r;
3859
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003860 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003861 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003862 if (keyfile == Py_None)
3863 keyfile = NULL;
3864 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003865 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3866 PyErr_SetString(PyExc_TypeError,
3867 "certfile should be a valid filesystem path");
3868 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003869 return NULL;
3870 }
3871 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003872 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3873 PyErr_SetString(PyExc_TypeError,
3874 "keyfile should be a valid filesystem path");
3875 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003876 goto error;
3877 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003878 if (password && password != Py_None) {
3879 if (PyCallable_Check(password)) {
3880 pw_info.callable = password;
3881 } else if (!_pwinfo_set(&pw_info, password,
3882 "password should be a string or callable")) {
3883 goto error;
3884 }
3885 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3886 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3887 }
3888 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3890 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003891 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003892 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003893 if (pw_info.error) {
3894 ERR_clear_error();
3895 /* the password callback has already set the error information */
3896 }
3897 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003898 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003899 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003900 }
3901 else {
3902 _setSSLError(NULL, 0, __FILE__, __LINE__);
3903 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003904 goto error;
3905 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003906 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003907 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003908 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3909 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003910 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3911 Py_CLEAR(keyfile_bytes);
3912 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003913 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003914 if (pw_info.error) {
3915 ERR_clear_error();
3916 /* the password callback has already set the error information */
3917 }
3918 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003919 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003920 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003921 }
3922 else {
3923 _setSSLError(NULL, 0, __FILE__, __LINE__);
3924 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003925 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003926 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003927 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003928 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003929 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003930 if (r != 1) {
3931 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003932 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003933 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003934 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3935 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003936 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003937 Py_RETURN_NONE;
3938
3939error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003940 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3941 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003942 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003943 Py_XDECREF(keyfile_bytes);
3944 Py_XDECREF(certfile_bytes);
3945 return NULL;
3946}
3947
Christian Heimesefff7062013-11-21 03:35:02 +01003948/* internal helper function, returns -1 on error
3949 */
3950static int
3951_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3952 int filetype)
3953{
3954 BIO *biobuf = NULL;
3955 X509_STORE *store;
3956 int retval = 0, err, loaded = 0;
3957
3958 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3959
3960 if (len <= 0) {
3961 PyErr_SetString(PyExc_ValueError,
3962 "Empty certificate data");
3963 return -1;
3964 } else if (len > INT_MAX) {
3965 PyErr_SetString(PyExc_OverflowError,
3966 "Certificate data is too long.");
3967 return -1;
3968 }
3969
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003970 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003971 if (biobuf == NULL) {
3972 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3973 return -1;
3974 }
3975
3976 store = SSL_CTX_get_cert_store(self->ctx);
3977 assert(store != NULL);
3978
3979 while (1) {
3980 X509 *cert = NULL;
3981 int r;
3982
3983 if (filetype == SSL_FILETYPE_ASN1) {
3984 cert = d2i_X509_bio(biobuf, NULL);
3985 } else {
3986 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003987 SSL_CTX_get_default_passwd_cb(self->ctx),
3988 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3989 );
Christian Heimesefff7062013-11-21 03:35:02 +01003990 }
3991 if (cert == NULL) {
3992 break;
3993 }
3994 r = X509_STORE_add_cert(store, cert);
3995 X509_free(cert);
3996 if (!r) {
3997 err = ERR_peek_last_error();
3998 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3999 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4000 /* cert already in hash table, not an error */
4001 ERR_clear_error();
4002 } else {
4003 break;
4004 }
4005 }
4006 loaded++;
4007 }
4008
4009 err = ERR_peek_last_error();
4010 if ((filetype == SSL_FILETYPE_ASN1) &&
4011 (loaded > 0) &&
4012 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4013 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4014 /* EOF ASN1 file, not an error */
4015 ERR_clear_error();
4016 retval = 0;
4017 } else if ((filetype == SSL_FILETYPE_PEM) &&
4018 (loaded > 0) &&
4019 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4020 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4021 /* EOF PEM file, not an error */
4022 ERR_clear_error();
4023 retval = 0;
4024 } else {
4025 _setSSLError(NULL, 0, __FILE__, __LINE__);
4026 retval = -1;
4027 }
4028
4029 BIO_free(biobuf);
4030 return retval;
4031}
4032
4033
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004034/*[clinic input]
4035_ssl._SSLContext.load_verify_locations
4036 cafile: object = NULL
4037 capath: object = NULL
4038 cadata: object = NULL
4039
4040[clinic start generated code]*/
4041
Antoine Pitrou152efa22010-05-16 18:19:27 +00004042static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004043_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4044 PyObject *cafile,
4045 PyObject *capath,
4046 PyObject *cadata)
4047/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004048{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004049 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4050 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004051 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004052
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004053 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004054 if (cafile == Py_None)
4055 cafile = NULL;
4056 if (capath == Py_None)
4057 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004058 if (cadata == Py_None)
4059 cadata = NULL;
4060
4061 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004062 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004063 "cafile, capath and cadata cannot be all omitted");
4064 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065 }
4066 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004067 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4068 PyErr_SetString(PyExc_TypeError,
4069 "cafile should be a valid filesystem path");
4070 }
Christian Heimesefff7062013-11-21 03:35:02 +01004071 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004072 }
4073 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004074 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4075 PyErr_SetString(PyExc_TypeError,
4076 "capath should be a valid filesystem path");
4077 }
Christian Heimesefff7062013-11-21 03:35:02 +01004078 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004079 }
Christian Heimesefff7062013-11-21 03:35:02 +01004080
4081 /* validata cadata type and load cadata */
4082 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004083 if (PyUnicode_Check(cadata)) {
4084 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4085 if (cadata_ascii == NULL) {
4086 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4087 goto invalid_cadata;
4088 }
4089 goto error;
4090 }
4091 r = _add_ca_certs(self,
4092 PyBytes_AS_STRING(cadata_ascii),
4093 PyBytes_GET_SIZE(cadata_ascii),
4094 SSL_FILETYPE_PEM);
4095 Py_DECREF(cadata_ascii);
4096 if (r == -1) {
4097 goto error;
4098 }
4099 }
4100 else if (PyObject_CheckBuffer(cadata)) {
4101 Py_buffer buf;
4102 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4103 goto error;
4104 }
Christian Heimesefff7062013-11-21 03:35:02 +01004105 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4106 PyBuffer_Release(&buf);
4107 PyErr_SetString(PyExc_TypeError,
4108 "cadata should be a contiguous buffer with "
4109 "a single dimension");
4110 goto error;
4111 }
4112 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4113 PyBuffer_Release(&buf);
4114 if (r == -1) {
4115 goto error;
4116 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004117 }
4118 else {
4119 invalid_cadata:
4120 PyErr_SetString(PyExc_TypeError,
4121 "cadata should be an ASCII string or a "
4122 "bytes-like object");
4123 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004124 }
4125 }
4126
4127 /* load cafile or capath */
4128 if (cafile || capath) {
4129 if (cafile)
4130 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4131 if (capath)
4132 capath_buf = PyBytes_AS_STRING(capath_bytes);
4133 PySSL_BEGIN_ALLOW_THREADS
4134 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4135 PySSL_END_ALLOW_THREADS
4136 if (r != 1) {
4137 ok = 0;
4138 if (errno != 0) {
4139 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004140 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004141 }
4142 else {
4143 _setSSLError(NULL, 0, __FILE__, __LINE__);
4144 }
4145 goto error;
4146 }
4147 }
4148 goto end;
4149
4150 error:
4151 ok = 0;
4152 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004153 Py_XDECREF(cafile_bytes);
4154 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004155 if (ok) {
4156 Py_RETURN_NONE;
4157 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004158 return NULL;
4159 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004160}
4161
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004162/*[clinic input]
4163_ssl._SSLContext.load_dh_params
4164 path as filepath: object
4165 /
4166
4167[clinic start generated code]*/
4168
Antoine Pitrou152efa22010-05-16 18:19:27 +00004169static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004170_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4171/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004172{
4173 FILE *f;
4174 DH *dh;
4175
Victor Stinnerdaf45552013-08-28 00:53:59 +02004176 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004177 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004178 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004179
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004180 errno = 0;
4181 PySSL_BEGIN_ALLOW_THREADS
4182 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004183 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004184 PySSL_END_ALLOW_THREADS
4185 if (dh == NULL) {
4186 if (errno != 0) {
4187 ERR_clear_error();
4188 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4189 }
4190 else {
4191 _setSSLError(NULL, 0, __FILE__, __LINE__);
4192 }
4193 return NULL;
4194 }
4195 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4196 _setSSLError(NULL, 0, __FILE__, __LINE__);
4197 DH_free(dh);
4198 Py_RETURN_NONE;
4199}
4200
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004201/*[clinic input]
4202_ssl._SSLContext._wrap_socket
4203 sock: object(subclass_of="PySocketModule.Sock_Type")
4204 server_side: int
4205 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004206 *
4207 owner: object = None
4208 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004209
4210[clinic start generated code]*/
4211
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004212static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004213_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004214 int server_side, PyObject *hostname_obj,
4215 PyObject *owner, PyObject *session)
4216/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004217{
Antoine Pitroud5323212010-10-22 18:19:07 +00004218 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004219 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004220
Antoine Pitroud5323212010-10-22 18:19:07 +00004221 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004222 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004223 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004224 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004225 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004226 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004227
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004228 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4229 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004230 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004231 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004232 if (hostname != NULL)
4233 PyMem_Free(hostname);
4234 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004235}
4236
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004237/*[clinic input]
4238_ssl._SSLContext._wrap_bio
4239 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4240 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4241 server_side: int
4242 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004243 *
4244 owner: object = None
4245 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004246
4247[clinic start generated code]*/
4248
Antoine Pitroub0182c82010-10-12 20:09:02 +00004249static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004250_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4251 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004252 PyObject *hostname_obj, PyObject *owner,
4253 PyObject *session)
4254/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004255{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004256 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004257 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004258
4259 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004260 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004261 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004262 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004263 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004264 }
4265
4266 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004267 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004268 incoming, outgoing);
4269
4270 PyMem_Free(hostname);
4271 return res;
4272}
4273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004274/*[clinic input]
4275_ssl._SSLContext.session_stats
4276[clinic start generated code]*/
4277
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004278static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004279_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4280/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004281{
4282 int r;
4283 PyObject *value, *stats = PyDict_New();
4284 if (!stats)
4285 return NULL;
4286
4287#define ADD_STATS(SSL_NAME, KEY_NAME) \
4288 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4289 if (value == NULL) \
4290 goto error; \
4291 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4292 Py_DECREF(value); \
4293 if (r < 0) \
4294 goto error;
4295
4296 ADD_STATS(number, "number");
4297 ADD_STATS(connect, "connect");
4298 ADD_STATS(connect_good, "connect_good");
4299 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4300 ADD_STATS(accept, "accept");
4301 ADD_STATS(accept_good, "accept_good");
4302 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4303 ADD_STATS(accept, "accept");
4304 ADD_STATS(hits, "hits");
4305 ADD_STATS(misses, "misses");
4306 ADD_STATS(timeouts, "timeouts");
4307 ADD_STATS(cache_full, "cache_full");
4308
4309#undef ADD_STATS
4310
4311 return stats;
4312
4313error:
4314 Py_DECREF(stats);
4315 return NULL;
4316}
4317
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004318/*[clinic input]
4319_ssl._SSLContext.set_default_verify_paths
4320[clinic start generated code]*/
4321
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004322static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004323_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4324/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004325{
4326 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4327 _setSSLError(NULL, 0, __FILE__, __LINE__);
4328 return NULL;
4329 }
4330 Py_RETURN_NONE;
4331}
4332
Antoine Pitrou501da612011-12-21 09:27:41 +01004333#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004334/*[clinic input]
4335_ssl._SSLContext.set_ecdh_curve
4336 name: object
4337 /
4338
4339[clinic start generated code]*/
4340
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004341static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004342_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4343/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004344{
4345 PyObject *name_bytes;
4346 int nid;
4347 EC_KEY *key;
4348
4349 if (!PyUnicode_FSConverter(name, &name_bytes))
4350 return NULL;
4351 assert(PyBytes_Check(name_bytes));
4352 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4353 Py_DECREF(name_bytes);
4354 if (nid == 0) {
4355 PyErr_Format(PyExc_ValueError,
4356 "unknown elliptic curve name %R", name);
4357 return NULL;
4358 }
4359 key = EC_KEY_new_by_curve_name(nid);
4360 if (key == NULL) {
4361 _setSSLError(NULL, 0, __FILE__, __LINE__);
4362 return NULL;
4363 }
4364 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4365 EC_KEY_free(key);
4366 Py_RETURN_NONE;
4367}
Antoine Pitrou501da612011-12-21 09:27:41 +01004368#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004369
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004370#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004371static int
4372_servername_callback(SSL *s, int *al, void *args)
4373{
4374 int ret;
4375 PySSLContext *ssl_ctx = (PySSLContext *) args;
4376 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004377 PyObject *result;
4378 /* The high-level ssl.SSLSocket object */
4379 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004380 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004381 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004382
Christian Heimes11a14932018-02-24 02:35:08 +01004383 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004384 /* remove race condition in this the call back while if removing the
4385 * callback is in progress */
4386 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004387 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004388 }
4389
4390 ssl = SSL_get_app_data(s);
4391 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004392
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004393 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004394 * SSL connection and that has a .context attribute that can be changed to
4395 * identify the requested hostname. Since the official API is the Python
4396 * level API we want to pass the callback a Python level object rather than
4397 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4398 * SSLObject) that will be passed. Otherwise if there's a socket then that
4399 * will be passed. If both do not exist only then the C-level object is
4400 * passed. */
4401 if (ssl->owner)
4402 ssl_socket = PyWeakref_GetObject(ssl->owner);
4403 else if (ssl->Socket)
4404 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4405 else
4406 ssl_socket = (PyObject *) ssl;
4407
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004408 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004409 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004410 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004411
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004412 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004413 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004414 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004415 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004416 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004417 PyObject *servername_bytes;
4418 PyObject *servername_str;
4419
4420 servername_bytes = PyBytes_FromString(servername);
4421 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004422 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4423 goto error;
4424 }
Christian Heimes11a14932018-02-24 02:35:08 +01004425 /* server_hostname was encoded to an A-label by our caller; put it
4426 * back into a str object, but still as an A-label (bpo-28414)
4427 */
4428 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4429 Py_DECREF(servername_bytes);
4430 if (servername_str == NULL) {
4431 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004432 goto error;
4433 }
Christian Heimes11a14932018-02-24 02:35:08 +01004434 result = PyObject_CallFunctionObjArgs(
4435 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4436 ssl_ctx, NULL);
4437 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004438 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004439 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004440
4441 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004442 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004443 *al = SSL_AD_HANDSHAKE_FAILURE;
4444 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4445 }
4446 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004447 /* Result may be None, a SSLContext or an integer
4448 * None and SSLContext are OK, integer or other values are an error.
4449 */
4450 if (result == Py_None) {
4451 ret = SSL_TLSEXT_ERR_OK;
4452 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004453 *al = (int) PyLong_AsLong(result);
4454 if (PyErr_Occurred()) {
4455 PyErr_WriteUnraisable(result);
4456 *al = SSL_AD_INTERNAL_ERROR;
4457 }
4458 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4459 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004460 Py_DECREF(result);
4461 }
4462
4463 PyGILState_Release(gstate);
4464 return ret;
4465
4466error:
4467 Py_DECREF(ssl_socket);
4468 *al = SSL_AD_INTERNAL_ERROR;
4469 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4470 PyGILState_Release(gstate);
4471 return ret;
4472}
Antoine Pitroua5963382013-03-30 16:39:00 +01004473#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004474
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004475static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004476get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004477{
Christian Heimes11a14932018-02-24 02:35:08 +01004478 PyObject *cb = self->set_sni_cb;
4479 if (cb == NULL) {
4480 Py_RETURN_NONE;
4481 }
4482 Py_INCREF(cb);
4483 return cb;
4484}
4485
4486static int
4487set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4488{
4489 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4490 PyErr_SetString(PyExc_ValueError,
4491 "sni_callback cannot be set on TLS_CLIENT context");
4492 return -1;
4493 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004494#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004495 Py_CLEAR(self->set_sni_cb);
4496 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004497 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4498 }
4499 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004500 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004501 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4502 PyErr_SetString(PyExc_TypeError,
4503 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004504 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004505 }
Christian Heimes11a14932018-02-24 02:35:08 +01004506 Py_INCREF(arg);
4507 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4509 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4510 }
Christian Heimes11a14932018-02-24 02:35:08 +01004511 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004512#else
4513 PyErr_SetString(PyExc_NotImplementedError,
4514 "The TLS extension servername callback, "
4515 "SSL_CTX_set_tlsext_servername_callback, "
4516 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004517 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004518#endif
4519}
4520
Christian Heimes11a14932018-02-24 02:35:08 +01004521PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4522"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4523\n\
4524If the argument is None then the callback is disabled. The method is called\n\
4525with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4526See RFC 6066 for details of the SNI extension.");
4527
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004528/*[clinic input]
4529_ssl._SSLContext.cert_store_stats
4530
4531Returns quantities of loaded X.509 certificates.
4532
4533X.509 certificates with a CA extension and certificate revocation lists
4534inside the context's cert store.
4535
4536NOTE: Certificates in a capath directory aren't loaded unless they have
4537been used at least once.
4538[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004539
4540static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004541_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4542/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004543{
4544 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004545 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004546 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004547 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004548
4549 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004550 objs = X509_STORE_get0_objects(store);
4551 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4552 obj = sk_X509_OBJECT_value(objs, i);
4553 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004554 case X509_LU_X509:
4555 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004556 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004557 ca++;
4558 }
4559 break;
4560 case X509_LU_CRL:
4561 crl++;
4562 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004563 default:
4564 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4565 * As far as I can tell they are internal states and never
4566 * stored in a cert store */
4567 break;
4568 }
4569 }
4570 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4571 "x509_ca", ca);
4572}
4573
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004574/*[clinic input]
4575_ssl._SSLContext.get_ca_certs
4576 binary_form: bool = False
4577
4578Returns a list of dicts with information of loaded CA certs.
4579
4580If the optional argument is True, returns a DER-encoded copy of the CA
4581certificate.
4582
4583NOTE: Certificates in a capath directory aren't loaded unless they have
4584been used at least once.
4585[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004586
4587static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004588_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4589/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004590{
4591 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004592 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004593 PyObject *ci = NULL, *rlist = NULL;
4594 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004595
4596 if ((rlist = PyList_New(0)) == NULL) {
4597 return NULL;
4598 }
4599
4600 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004601 objs = X509_STORE_get0_objects(store);
4602 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004603 X509_OBJECT *obj;
4604 X509 *cert;
4605
Christian Heimes598894f2016-09-05 23:19:05 +02004606 obj = sk_X509_OBJECT_value(objs, i);
4607 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004608 /* not a x509 cert */
4609 continue;
4610 }
4611 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004612 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004613 if (!X509_check_ca(cert)) {
4614 continue;
4615 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004616 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004617 ci = _certificate_to_der(cert);
4618 } else {
4619 ci = _decode_certificate(cert);
4620 }
4621 if (ci == NULL) {
4622 goto error;
4623 }
4624 if (PyList_Append(rlist, ci) == -1) {
4625 goto error;
4626 }
4627 Py_CLEAR(ci);
4628 }
4629 return rlist;
4630
4631 error:
4632 Py_XDECREF(ci);
4633 Py_XDECREF(rlist);
4634 return NULL;
4635}
4636
4637
Antoine Pitrou152efa22010-05-16 18:19:27 +00004638static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004639 {"check_hostname", (getter) get_check_hostname,
4640 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004641 {"_host_flags", (getter) get_host_flags,
4642 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004643#if SSL_CTRL_GET_MAX_PROTO_VERSION
4644 {"minimum_version", (getter) get_minimum_version,
4645 (setter) set_minimum_version, NULL},
4646 {"maximum_version", (getter) get_maximum_version,
4647 (setter) set_maximum_version, NULL},
4648#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004649#ifdef HAVE_OPENSSL_KEYLOG
4650 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4651 (setter) _PySSLContext_set_keylog_filename, NULL},
4652#endif
4653 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4654 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004655 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004656 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004657 {"options", (getter) get_options,
4658 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004659 {"post_handshake_auth", (getter) get_post_handshake_auth,
4660#ifdef TLS1_3_VERSION
4661 (setter) set_post_handshake_auth,
4662#else
4663 NULL,
4664#endif
4665 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004666 {"protocol", (getter) get_protocol,
4667 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004668 {"verify_flags", (getter) get_verify_flags,
4669 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004670 {"verify_mode", (getter) get_verify_mode,
4671 (setter) set_verify_mode, NULL},
4672 {NULL}, /* sentinel */
4673};
4674
4675static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004676 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4677 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4678 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4679 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4680 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4681 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4682 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4683 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4684 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4685 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4686 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004687 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4688 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004689 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004690 {NULL, NULL} /* sentinel */
4691};
4692
4693static PyTypeObject PySSLContext_Type = {
4694 PyVarObject_HEAD_INIT(NULL, 0)
4695 "_ssl._SSLContext", /*tp_name*/
4696 sizeof(PySSLContext), /*tp_basicsize*/
4697 0, /*tp_itemsize*/
4698 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004699 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004700 0, /*tp_getattr*/
4701 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004702 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004703 0, /*tp_repr*/
4704 0, /*tp_as_number*/
4705 0, /*tp_as_sequence*/
4706 0, /*tp_as_mapping*/
4707 0, /*tp_hash*/
4708 0, /*tp_call*/
4709 0, /*tp_str*/
4710 0, /*tp_getattro*/
4711 0, /*tp_setattro*/
4712 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004713 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004714 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004715 (traverseproc) context_traverse, /*tp_traverse*/
4716 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004717 0, /*tp_richcompare*/
4718 0, /*tp_weaklistoffset*/
4719 0, /*tp_iter*/
4720 0, /*tp_iternext*/
4721 context_methods, /*tp_methods*/
4722 0, /*tp_members*/
4723 context_getsetlist, /*tp_getset*/
4724 0, /*tp_base*/
4725 0, /*tp_dict*/
4726 0, /*tp_descr_get*/
4727 0, /*tp_descr_set*/
4728 0, /*tp_dictoffset*/
4729 0, /*tp_init*/
4730 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004731 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004732};
4733
4734
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004735/*
4736 * MemoryBIO objects
4737 */
4738
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004739/*[clinic input]
4740@classmethod
4741_ssl.MemoryBIO.__new__
4742
4743[clinic start generated code]*/
4744
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004745static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004746_ssl_MemoryBIO_impl(PyTypeObject *type)
4747/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004748{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004749 BIO *bio;
4750 PySSLMemoryBIO *self;
4751
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004752 bio = BIO_new(BIO_s_mem());
4753 if (bio == NULL) {
4754 PyErr_SetString(PySSLErrorObject,
4755 "failed to allocate BIO");
4756 return NULL;
4757 }
4758 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4759 * just that no data is currently available. The SSL routines should retry
4760 * the read, which we can achieve by calling BIO_set_retry_read(). */
4761 BIO_set_retry_read(bio);
4762 BIO_set_mem_eof_return(bio, -1);
4763
4764 assert(type != NULL && type->tp_alloc != NULL);
4765 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4766 if (self == NULL) {
4767 BIO_free(bio);
4768 return NULL;
4769 }
4770 self->bio = bio;
4771 self->eof_written = 0;
4772
4773 return (PyObject *) self;
4774}
4775
4776static void
4777memory_bio_dealloc(PySSLMemoryBIO *self)
4778{
4779 BIO_free(self->bio);
4780 Py_TYPE(self)->tp_free(self);
4781}
4782
4783static PyObject *
4784memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4785{
Segev Finer5cff6372017-07-27 01:19:17 +03004786 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004787}
4788
4789PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4790"The number of bytes pending in the memory BIO.");
4791
4792static PyObject *
4793memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4794{
4795 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4796 && self->eof_written);
4797}
4798
4799PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4800"Whether the memory BIO is at EOF.");
4801
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004802/*[clinic input]
4803_ssl.MemoryBIO.read
4804 size as len: int = -1
4805 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004806
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004807Read up to size bytes from the memory BIO.
4808
4809If size is not specified, read the entire buffer.
4810If the return value is an empty bytes instance, this means either
4811EOF or that no data is available. Use the "eof" property to
4812distinguish between the two.
4813[clinic start generated code]*/
4814
4815static PyObject *
4816_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4817/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4818{
4819 int avail, nbytes;
4820 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004821
Segev Finer5cff6372017-07-27 01:19:17 +03004822 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004823 if ((len < 0) || (len > avail))
4824 len = avail;
4825
4826 result = PyBytes_FromStringAndSize(NULL, len);
4827 if ((result == NULL) || (len == 0))
4828 return result;
4829
4830 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004831 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004832 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004833 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004834 return NULL;
4835 }
4836
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004837 /* There should never be any short reads but check anyway. */
4838 if (nbytes < len) {
4839 _PyBytes_Resize(&result, nbytes);
4840 }
4841
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004842 return result;
4843}
4844
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004845/*[clinic input]
4846_ssl.MemoryBIO.write
4847 b: Py_buffer
4848 /
4849
4850Writes the bytes b into the memory BIO.
4851
4852Returns the number of bytes written.
4853[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004854
4855static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004856_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4857/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004858{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004859 int nbytes;
4860
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004861 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004862 PyErr_Format(PyExc_OverflowError,
4863 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004864 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004865 }
4866
4867 if (self->eof_written) {
4868 PyErr_SetString(PySSLErrorObject,
4869 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004870 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004871 }
4872
Segev Finer5cff6372017-07-27 01:19:17 +03004873 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004874 if (nbytes < 0) {
4875 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004876 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004877 }
4878
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004879 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004880}
4881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004882/*[clinic input]
4883_ssl.MemoryBIO.write_eof
4884
4885Write an EOF marker to the memory BIO.
4886
4887When all data has been read, the "eof" property will be True.
4888[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004889
4890static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004891_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4892/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004893{
4894 self->eof_written = 1;
4895 /* After an EOF is written, a zero return from read() should be a real EOF
4896 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4897 BIO_clear_retry_flags(self->bio);
4898 BIO_set_mem_eof_return(self->bio, 0);
4899
4900 Py_RETURN_NONE;
4901}
4902
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004903static PyGetSetDef memory_bio_getsetlist[] = {
4904 {"pending", (getter) memory_bio_get_pending, NULL,
4905 PySSL_memory_bio_pending_doc},
4906 {"eof", (getter) memory_bio_get_eof, NULL,
4907 PySSL_memory_bio_eof_doc},
4908 {NULL}, /* sentinel */
4909};
4910
4911static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004912 _SSL_MEMORYBIO_READ_METHODDEF
4913 _SSL_MEMORYBIO_WRITE_METHODDEF
4914 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004915 {NULL, NULL} /* sentinel */
4916};
4917
4918static PyTypeObject PySSLMemoryBIO_Type = {
4919 PyVarObject_HEAD_INIT(NULL, 0)
4920 "_ssl.MemoryBIO", /*tp_name*/
4921 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4922 0, /*tp_itemsize*/
4923 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004924 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004925 0, /*tp_getattr*/
4926 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004927 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004928 0, /*tp_repr*/
4929 0, /*tp_as_number*/
4930 0, /*tp_as_sequence*/
4931 0, /*tp_as_mapping*/
4932 0, /*tp_hash*/
4933 0, /*tp_call*/
4934 0, /*tp_str*/
4935 0, /*tp_getattro*/
4936 0, /*tp_setattro*/
4937 0, /*tp_as_buffer*/
4938 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4939 0, /*tp_doc*/
4940 0, /*tp_traverse*/
4941 0, /*tp_clear*/
4942 0, /*tp_richcompare*/
4943 0, /*tp_weaklistoffset*/
4944 0, /*tp_iter*/
4945 0, /*tp_iternext*/
4946 memory_bio_methods, /*tp_methods*/
4947 0, /*tp_members*/
4948 memory_bio_getsetlist, /*tp_getset*/
4949 0, /*tp_base*/
4950 0, /*tp_dict*/
4951 0, /*tp_descr_get*/
4952 0, /*tp_descr_set*/
4953 0, /*tp_dictoffset*/
4954 0, /*tp_init*/
4955 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004956 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004957};
4958
Antoine Pitrou152efa22010-05-16 18:19:27 +00004959
Christian Heimes99a65702016-09-10 23:44:53 +02004960/*
4961 * SSL Session object
4962 */
4963
4964static void
4965PySSLSession_dealloc(PySSLSession *self)
4966{
INADA Naokia6296d32017-08-24 14:55:17 +09004967 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004968 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004969 Py_XDECREF(self->ctx);
4970 if (self->session != NULL) {
4971 SSL_SESSION_free(self->session);
4972 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004973 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004974}
4975
4976static PyObject *
4977PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4978{
4979 int result;
4980
4981 if (left == NULL || right == NULL) {
4982 PyErr_BadInternalCall();
4983 return NULL;
4984 }
4985
4986 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4987 Py_RETURN_NOTIMPLEMENTED;
4988 }
4989
4990 if (left == right) {
4991 result = 0;
4992 } else {
4993 const unsigned char *left_id, *right_id;
4994 unsigned int left_len, right_len;
4995 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4996 &left_len);
4997 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4998 &right_len);
4999 if (left_len == right_len) {
5000 result = memcmp(left_id, right_id, left_len);
5001 } else {
5002 result = 1;
5003 }
5004 }
5005
5006 switch (op) {
5007 case Py_EQ:
5008 if (result == 0) {
5009 Py_RETURN_TRUE;
5010 } else {
5011 Py_RETURN_FALSE;
5012 }
5013 break;
5014 case Py_NE:
5015 if (result != 0) {
5016 Py_RETURN_TRUE;
5017 } else {
5018 Py_RETURN_FALSE;
5019 }
5020 break;
5021 case Py_LT:
5022 case Py_LE:
5023 case Py_GT:
5024 case Py_GE:
5025 Py_RETURN_NOTIMPLEMENTED;
5026 break;
5027 default:
5028 PyErr_BadArgument();
5029 return NULL;
5030 }
5031}
5032
5033static int
5034PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5035{
5036 Py_VISIT(self->ctx);
5037 return 0;
5038}
5039
5040static int
5041PySSLSession_clear(PySSLSession *self)
5042{
5043 Py_CLEAR(self->ctx);
5044 return 0;
5045}
5046
5047
5048static PyObject *
5049PySSLSession_get_time(PySSLSession *self, void *closure) {
5050 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5051}
5052
5053PyDoc_STRVAR(PySSLSession_get_time_doc,
5054"Session creation time (seconds since epoch).");
5055
5056
5057static PyObject *
5058PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5059 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5060}
5061
5062PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5063"Session timeout (delta in seconds).");
5064
5065
5066static PyObject *
5067PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5068 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5069 return PyLong_FromUnsignedLong(hint);
5070}
5071
5072PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5073"Ticket life time hint.");
5074
5075
5076static PyObject *
5077PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5078 const unsigned char *id;
5079 unsigned int len;
5080 id = SSL_SESSION_get_id(self->session, &len);
5081 return PyBytes_FromStringAndSize((const char *)id, len);
5082}
5083
5084PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5085"Session id");
5086
5087
5088static PyObject *
5089PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5090 if (SSL_SESSION_has_ticket(self->session)) {
5091 Py_RETURN_TRUE;
5092 } else {
5093 Py_RETURN_FALSE;
5094 }
5095}
5096
5097PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5098"Does the session contain a ticket?");
5099
5100
5101static PyGetSetDef PySSLSession_getsetlist[] = {
5102 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5103 PySSLSession_get_has_ticket_doc},
5104 {"id", (getter) PySSLSession_get_session_id, NULL,
5105 PySSLSession_get_session_id_doc},
5106 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5107 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5108 {"time", (getter) PySSLSession_get_time, NULL,
5109 PySSLSession_get_time_doc},
5110 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5111 PySSLSession_get_timeout_doc},
5112 {NULL}, /* sentinel */
5113};
5114
5115static PyTypeObject PySSLSession_Type = {
5116 PyVarObject_HEAD_INIT(NULL, 0)
5117 "_ssl.Session", /*tp_name*/
5118 sizeof(PySSLSession), /*tp_basicsize*/
5119 0, /*tp_itemsize*/
5120 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005121 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005122 0, /*tp_getattr*/
5123 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005124 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005125 0, /*tp_repr*/
5126 0, /*tp_as_number*/
5127 0, /*tp_as_sequence*/
5128 0, /*tp_as_mapping*/
5129 0, /*tp_hash*/
5130 0, /*tp_call*/
5131 0, /*tp_str*/
5132 0, /*tp_getattro*/
5133 0, /*tp_setattro*/
5134 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005135 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005136 0, /*tp_doc*/
5137 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5138 (inquiry)PySSLSession_clear, /*tp_clear*/
5139 PySSLSession_richcompare, /*tp_richcompare*/
5140 0, /*tp_weaklistoffset*/
5141 0, /*tp_iter*/
5142 0, /*tp_iternext*/
5143 0, /*tp_methods*/
5144 0, /*tp_members*/
5145 PySSLSession_getsetlist, /*tp_getset*/
5146};
5147
5148
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005149/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005150/*[clinic input]
5151_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005152 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005153 entropy: double
5154 /
5155
5156Mix string into the OpenSSL PRNG state.
5157
5158entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305159string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005160[clinic start generated code]*/
5161
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005163_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005164/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005165{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005166 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005167 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005168
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005169 buf = (const char *)view->buf;
5170 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005171 do {
5172 written = Py_MIN(len, INT_MAX);
5173 RAND_add(buf, (int)written, entropy);
5174 buf += written;
5175 len -= written;
5176 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005177 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005178}
5179
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005180static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005181PySSL_RAND(int len, int pseudo)
5182{
5183 int ok;
5184 PyObject *bytes;
5185 unsigned long err;
5186 const char *errstr;
5187 PyObject *v;
5188
Victor Stinner1e81a392013-12-19 16:47:04 +01005189 if (len < 0) {
5190 PyErr_SetString(PyExc_ValueError, "num must be positive");
5191 return NULL;
5192 }
5193
Victor Stinner99c8b162011-05-24 12:05:19 +02005194 bytes = PyBytes_FromStringAndSize(NULL, len);
5195 if (bytes == NULL)
5196 return NULL;
5197 if (pseudo) {
5198 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5199 if (ok == 0 || ok == 1)
5200 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5201 }
5202 else {
5203 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5204 if (ok == 1)
5205 return bytes;
5206 }
5207 Py_DECREF(bytes);
5208
5209 err = ERR_get_error();
5210 errstr = ERR_reason_error_string(err);
5211 v = Py_BuildValue("(ks)", err, errstr);
5212 if (v != NULL) {
5213 PyErr_SetObject(PySSLErrorObject, v);
5214 Py_DECREF(v);
5215 }
5216 return NULL;
5217}
5218
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005219/*[clinic input]
5220_ssl.RAND_bytes
5221 n: int
5222 /
5223
5224Generate n cryptographically strong pseudo-random bytes.
5225[clinic start generated code]*/
5226
Victor Stinner99c8b162011-05-24 12:05:19 +02005227static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005228_ssl_RAND_bytes_impl(PyObject *module, int n)
5229/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005230{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005231 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005232}
5233
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005234/*[clinic input]
5235_ssl.RAND_pseudo_bytes
5236 n: int
5237 /
5238
5239Generate n pseudo-random bytes.
5240
5241Return a pair (bytes, is_cryptographic). is_cryptographic is True
5242if the bytes generated are cryptographically strong.
5243[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005244
5245static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005246_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5247/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005248{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005249 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005250}
5251
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005252/*[clinic input]
5253_ssl.RAND_status
5254
5255Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5256
5257It is necessary to seed the PRNG with RAND_add() on some platforms before
5258using the ssl() function.
5259[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005260
5261static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005262_ssl_RAND_status_impl(PyObject *module)
5263/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005264{
Christian Heimes217cfd12007-12-02 14:31:20 +00005265 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005266}
5267
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005268#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005269/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005270/*[clinic input]
5271_ssl.RAND_egd
5272 path: object(converter="PyUnicode_FSConverter")
5273 /
5274
5275Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5276
5277Returns number of bytes read. Raises SSLError if connection to EGD
5278fails or if it does not provide enough data to seed PRNG.
5279[clinic start generated code]*/
5280
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005281static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005282_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5283/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005284{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005285 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005286 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005287 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005288 PyErr_SetString(PySSLErrorObject,
5289 "EGD connection failed or EGD did not return "
5290 "enough data to seed the PRNG");
5291 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005292 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005293 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005294}
Christian Heimesa5d07652016-09-24 10:48:05 +02005295/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005296#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005297
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005298
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005299
5300/*[clinic input]
5301_ssl.get_default_verify_paths
5302
5303Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5304
5305The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5306[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005307
5308static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005309_ssl_get_default_verify_paths_impl(PyObject *module)
5310/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005311{
5312 PyObject *ofile_env = NULL;
5313 PyObject *ofile = NULL;
5314 PyObject *odir_env = NULL;
5315 PyObject *odir = NULL;
5316
Benjamin Petersond113c962015-07-18 10:59:13 -07005317#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005318 const char *tmp = (info); \
5319 target = NULL; \
5320 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5321 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5322 target = PyBytes_FromString(tmp); } \
5323 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005324 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005325
Benjamin Petersond113c962015-07-18 10:59:13 -07005326 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5327 CONVERT(X509_get_default_cert_file(), ofile);
5328 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5329 CONVERT(X509_get_default_cert_dir(), odir);
5330#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005331
Christian Heimes200bb1b2013-06-14 15:14:29 +02005332 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005333
5334 error:
5335 Py_XDECREF(ofile_env);
5336 Py_XDECREF(ofile);
5337 Py_XDECREF(odir_env);
5338 Py_XDECREF(odir);
5339 return NULL;
5340}
5341
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005342static PyObject*
5343asn1obj2py(ASN1_OBJECT *obj)
5344{
5345 int nid;
5346 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005347
5348 nid = OBJ_obj2nid(obj);
5349 if (nid == NID_undef) {
5350 PyErr_Format(PyExc_ValueError, "Unknown object");
5351 return NULL;
5352 }
5353 sn = OBJ_nid2sn(nid);
5354 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005355 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005356}
5357
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005358/*[clinic input]
5359_ssl.txt2obj
5360 txt: str
5361 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005362
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005363Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5364
5365By default objects are looked up by OID. With name=True short and
5366long name are also matched.
5367[clinic start generated code]*/
5368
5369static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005370_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5371/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005372{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005373 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005374 ASN1_OBJECT *obj;
5375
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005376 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5377 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005378 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005379 return NULL;
5380 }
5381 result = asn1obj2py(obj);
5382 ASN1_OBJECT_free(obj);
5383 return result;
5384}
5385
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005386/*[clinic input]
5387_ssl.nid2obj
5388 nid: int
5389 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005390
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005391Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5392[clinic start generated code]*/
5393
5394static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005395_ssl_nid2obj_impl(PyObject *module, int nid)
5396/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005397{
5398 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005399 ASN1_OBJECT *obj;
5400
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005401 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005402 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005403 return NULL;
5404 }
5405 obj = OBJ_nid2obj(nid);
5406 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005407 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005408 return NULL;
5409 }
5410 result = asn1obj2py(obj);
5411 ASN1_OBJECT_free(obj);
5412 return result;
5413}
5414
Christian Heimes46bebee2013-06-09 19:03:31 +02005415#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005416
5417static PyObject*
5418certEncodingType(DWORD encodingType)
5419{
5420 static PyObject *x509_asn = NULL;
5421 static PyObject *pkcs_7_asn = NULL;
5422
5423 if (x509_asn == NULL) {
5424 x509_asn = PyUnicode_InternFromString("x509_asn");
5425 if (x509_asn == NULL)
5426 return NULL;
5427 }
5428 if (pkcs_7_asn == NULL) {
5429 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5430 if (pkcs_7_asn == NULL)
5431 return NULL;
5432 }
5433 switch(encodingType) {
5434 case X509_ASN_ENCODING:
5435 Py_INCREF(x509_asn);
5436 return x509_asn;
5437 case PKCS_7_ASN_ENCODING:
5438 Py_INCREF(pkcs_7_asn);
5439 return pkcs_7_asn;
5440 default:
5441 return PyLong_FromLong(encodingType);
5442 }
5443}
5444
5445static PyObject*
5446parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5447{
5448 CERT_ENHKEY_USAGE *usage;
5449 DWORD size, error, i;
5450 PyObject *retval;
5451
5452 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5453 error = GetLastError();
5454 if (error == CRYPT_E_NOT_FOUND) {
5455 Py_RETURN_TRUE;
5456 }
5457 return PyErr_SetFromWindowsErr(error);
5458 }
5459
5460 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5461 if (usage == NULL) {
5462 return PyErr_NoMemory();
5463 }
5464
5465 /* Now get the actual enhanced usage property */
5466 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5467 PyMem_Free(usage);
5468 error = GetLastError();
5469 if (error == CRYPT_E_NOT_FOUND) {
5470 Py_RETURN_TRUE;
5471 }
5472 return PyErr_SetFromWindowsErr(error);
5473 }
5474 retval = PySet_New(NULL);
5475 if (retval == NULL) {
5476 goto error;
5477 }
5478 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5479 if (usage->rgpszUsageIdentifier[i]) {
5480 PyObject *oid;
5481 int err;
5482 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5483 if (oid == NULL) {
5484 Py_CLEAR(retval);
5485 goto error;
5486 }
5487 err = PySet_Add(retval, oid);
5488 Py_DECREF(oid);
5489 if (err == -1) {
5490 Py_CLEAR(retval);
5491 goto error;
5492 }
5493 }
5494 }
5495 error:
5496 PyMem_Free(usage);
5497 return retval;
5498}
5499
kctherookied93fbbf2019-03-29 00:59:06 +07005500static HCERTSTORE
5501ssl_collect_certificates(const char *store_name)
5502{
5503/* this function collects the system certificate stores listed in
5504 * system_stores into a collection certificate store for being
5505 * enumerated. The store must be readable to be added to the
5506 * store collection.
5507 */
5508
5509 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5510 static DWORD system_stores[] = {
5511 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5512 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5513 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5514 CERT_SYSTEM_STORE_CURRENT_USER,
5515 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5516 CERT_SYSTEM_STORE_SERVICES,
5517 CERT_SYSTEM_STORE_USERS};
5518 size_t i, storesAdded;
5519 BOOL result;
5520
5521 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5522 (HCRYPTPROV)NULL, 0, NULL);
5523 if (!hCollectionStore) {
5524 return NULL;
5525 }
5526 storesAdded = 0;
5527 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5528 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5529 (HCRYPTPROV)NULL,
5530 CERT_STORE_READONLY_FLAG |
5531 system_stores[i], store_name);
5532 if (hSystemStore) {
5533 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5534 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5535 if (result) {
5536 ++storesAdded;
5537 }
5538 }
5539 }
5540 if (storesAdded == 0) {
5541 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5542 return NULL;
5543 }
5544
5545 return hCollectionStore;
5546}
5547
5548/* code from Objects/listobject.c */
5549
5550static int
5551list_contains(PyListObject *a, PyObject *el)
5552{
5553 Py_ssize_t i;
5554 int cmp;
5555
5556 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
5557 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
5558 Py_EQ);
5559 return cmp;
5560}
5561
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005562/*[clinic input]
5563_ssl.enum_certificates
5564 store_name: str
5565
5566Retrieve certificates from Windows' cert store.
5567
5568store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5569more cert storages, too. The function returns a list of (bytes,
5570encoding_type, trust) tuples. The encoding_type flag can be interpreted
5571with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5572a set of OIDs or the boolean True.
5573[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005574
Christian Heimes46bebee2013-06-09 19:03:31 +02005575static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005576_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5577/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005578{
kctherookied93fbbf2019-03-29 00:59:06 +07005579 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005580 PCCERT_CONTEXT pCertCtx = NULL;
5581 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005582 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005583
Christian Heimes44109d72013-11-22 01:51:30 +01005584 result = PyList_New(0);
5585 if (result == NULL) {
5586 return NULL;
5587 }
kctherookied93fbbf2019-03-29 00:59:06 +07005588 hCollectionStore = ssl_collect_certificates(store_name);
5589 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005590 Py_DECREF(result);
5591 return PyErr_SetFromWindowsErr(GetLastError());
5592 }
5593
kctherookied93fbbf2019-03-29 00:59:06 +07005594 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005595 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5596 pCertCtx->cbCertEncoded);
5597 if (!cert) {
5598 Py_CLEAR(result);
5599 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005600 }
Christian Heimes44109d72013-11-22 01:51:30 +01005601 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5602 Py_CLEAR(result);
5603 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005604 }
Christian Heimes44109d72013-11-22 01:51:30 +01005605 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5606 if (keyusage == Py_True) {
5607 Py_DECREF(keyusage);
5608 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005609 }
Christian Heimes44109d72013-11-22 01:51:30 +01005610 if (keyusage == NULL) {
5611 Py_CLEAR(result);
5612 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005613 }
Christian Heimes44109d72013-11-22 01:51:30 +01005614 if ((tup = PyTuple_New(3)) == NULL) {
5615 Py_CLEAR(result);
5616 break;
5617 }
5618 PyTuple_SET_ITEM(tup, 0, cert);
5619 cert = NULL;
5620 PyTuple_SET_ITEM(tup, 1, enc);
5621 enc = NULL;
5622 PyTuple_SET_ITEM(tup, 2, keyusage);
5623 keyusage = NULL;
kctherookied93fbbf2019-03-29 00:59:06 +07005624 if (!list_contains((PyListObject*)result, tup)) {
5625 if (PyList_Append(result, tup) < 0) {
5626 Py_CLEAR(result);
5627 break;
5628 }
Christian Heimes44109d72013-11-22 01:51:30 +01005629 }
5630 Py_CLEAR(tup);
5631 }
5632 if (pCertCtx) {
5633 /* loop ended with an error, need to clean up context manually */
5634 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005635 }
5636
5637 /* In error cases cert, enc and tup may not be NULL */
5638 Py_XDECREF(cert);
5639 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005640 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005641 Py_XDECREF(tup);
5642
kctherookied93fbbf2019-03-29 00:59:06 +07005643 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5644 associated with the store, in this case our collection store and the
5645 associated system stores. */
5646 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005647 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005648 Py_XDECREF(result);
5649 return PyErr_SetFromWindowsErr(GetLastError());
5650 }
kctherookied93fbbf2019-03-29 00:59:06 +07005651
Christian Heimes44109d72013-11-22 01:51:30 +01005652 return result;
5653}
5654
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005655/*[clinic input]
5656_ssl.enum_crls
5657 store_name: str
5658
5659Retrieve CRLs from Windows' cert store.
5660
5661store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5662more cert storages, too. The function returns a list of (bytes,
5663encoding_type) tuples. The encoding_type flag can be interpreted with
5664X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5665[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005666
5667static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005668_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5669/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005670{
kctherookied93fbbf2019-03-29 00:59:06 +07005671 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005672 PCCRL_CONTEXT pCrlCtx = NULL;
5673 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5674 PyObject *result = NULL;
5675
Christian Heimes44109d72013-11-22 01:51:30 +01005676 result = PyList_New(0);
5677 if (result == NULL) {
5678 return NULL;
5679 }
kctherookied93fbbf2019-03-29 00:59:06 +07005680 hCollectionStore = ssl_collect_certificates(store_name);
5681 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005682 Py_DECREF(result);
5683 return PyErr_SetFromWindowsErr(GetLastError());
5684 }
Christian Heimes44109d72013-11-22 01:51:30 +01005685
kctherookied93fbbf2019-03-29 00:59:06 +07005686 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005687 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5688 pCrlCtx->cbCrlEncoded);
5689 if (!crl) {
5690 Py_CLEAR(result);
5691 break;
5692 }
5693 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5694 Py_CLEAR(result);
5695 break;
5696 }
5697 if ((tup = PyTuple_New(2)) == NULL) {
5698 Py_CLEAR(result);
5699 break;
5700 }
5701 PyTuple_SET_ITEM(tup, 0, crl);
5702 crl = NULL;
5703 PyTuple_SET_ITEM(tup, 1, enc);
5704 enc = NULL;
5705
kctherookied93fbbf2019-03-29 00:59:06 +07005706 if (!list_contains((PyListObject*)result, tup)) {
5707 if (PyList_Append(result, tup) < 0) {
5708 Py_CLEAR(result);
5709 break;
5710 }
Christian Heimes44109d72013-11-22 01:51:30 +01005711 }
5712 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005713 }
Christian Heimes44109d72013-11-22 01:51:30 +01005714 if (pCrlCtx) {
5715 /* loop ended with an error, need to clean up context manually */
5716 CertFreeCRLContext(pCrlCtx);
5717 }
5718
5719 /* In error cases cert, enc and tup may not be NULL */
5720 Py_XDECREF(crl);
5721 Py_XDECREF(enc);
5722 Py_XDECREF(tup);
5723
kctherookied93fbbf2019-03-29 00:59:06 +07005724 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5725 associated with the store, in this case our collection store and the
5726 associated system stores. */
5727 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005728 /* This error case might shadow another exception.*/
5729 Py_XDECREF(result);
5730 return PyErr_SetFromWindowsErr(GetLastError());
5731 }
5732 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005733}
Christian Heimes44109d72013-11-22 01:51:30 +01005734
5735#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005736
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005737/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005738static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005739 _SSL__TEST_DECODE_CERT_METHODDEF
5740 _SSL_RAND_ADD_METHODDEF
5741 _SSL_RAND_BYTES_METHODDEF
5742 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5743 _SSL_RAND_EGD_METHODDEF
5744 _SSL_RAND_STATUS_METHODDEF
5745 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5746 _SSL_ENUM_CERTIFICATES_METHODDEF
5747 _SSL_ENUM_CRLS_METHODDEF
5748 _SSL_TXT2OBJ_METHODDEF
5749 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005750 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005751};
5752
5753
Christian Heimes598894f2016-09-05 23:19:05 +02005754#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005755
5756/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005757 * of the Python C thread library
5758 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5759 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005760
5761static PyThread_type_lock *_ssl_locks = NULL;
5762
Christian Heimes4d98ca92013-08-19 17:36:29 +02005763#if OPENSSL_VERSION_NUMBER >= 0x10000000
5764/* use new CRYPTO_THREADID API. */
5765static void
5766_ssl_threadid_callback(CRYPTO_THREADID *id)
5767{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005768 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005769}
5770#else
5771/* deprecated CRYPTO_set_id_callback() API. */
5772static unsigned long
5773_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005774 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005775}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005776#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005777
Bill Janssen6e027db2007-11-15 22:23:56 +00005778static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005779 (int mode, int n, const char *file, int line) {
5780 /* this function is needed to perform locking on shared data
5781 structures. (Note that OpenSSL uses a number of global data
5782 structures that will be implicitly shared whenever multiple
5783 threads use OpenSSL.) Multi-threaded applications will
5784 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005785
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005786 locking_function() must be able to handle up to
5787 CRYPTO_num_locks() different mutex locks. It sets the n-th
5788 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005790 file and line are the file number of the function setting the
5791 lock. They can be useful for debugging.
5792 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005793
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005794 if ((_ssl_locks == NULL) ||
5795 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5796 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005797
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005798 if (mode & CRYPTO_LOCK) {
5799 PyThread_acquire_lock(_ssl_locks[n], 1);
5800 } else {
5801 PyThread_release_lock(_ssl_locks[n]);
5802 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005803}
5804
5805static int _setup_ssl_threads(void) {
5806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005807 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005808
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005809 if (_ssl_locks == NULL) {
5810 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005811 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5812 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005813 if (_ssl_locks == NULL) {
5814 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005815 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005816 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005817 for (i = 0; i < _ssl_locks_count; i++) {
5818 _ssl_locks[i] = PyThread_allocate_lock();
5819 if (_ssl_locks[i] == NULL) {
5820 unsigned int j;
5821 for (j = 0; j < i; j++) {
5822 PyThread_free_lock(_ssl_locks[j]);
5823 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005824 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005825 return 0;
5826 }
5827 }
5828 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005829#if OPENSSL_VERSION_NUMBER >= 0x10000000
5830 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5831#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005832 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005833#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005834 }
5835 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005836}
5837
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005838#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005839
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005840PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005841"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005842for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005843
Martin v. Löwis1a214512008-06-11 05:26:20 +00005844
5845static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005846 PyModuleDef_HEAD_INIT,
5847 "_ssl",
5848 module_doc,
5849 -1,
5850 PySSL_methods,
5851 NULL,
5852 NULL,
5853 NULL,
5854 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005855};
5856
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005857
5858static void
5859parse_openssl_version(unsigned long libver,
5860 unsigned int *major, unsigned int *minor,
5861 unsigned int *fix, unsigned int *patch,
5862 unsigned int *status)
5863{
5864 *status = libver & 0xF;
5865 libver >>= 4;
5866 *patch = libver & 0xFF;
5867 libver >>= 8;
5868 *fix = libver & 0xFF;
5869 libver >>= 8;
5870 *minor = libver & 0xFF;
5871 libver >>= 8;
5872 *major = libver & 0xFF;
5873}
5874
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005875PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005876PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005877{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005878 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 unsigned long libver;
5880 unsigned int major, minor, fix, patch, status;
5881 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005882 struct py_ssl_error_code *errcode;
5883 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005884
Antoine Pitrou152efa22010-05-16 18:19:27 +00005885 if (PyType_Ready(&PySSLContext_Type) < 0)
5886 return NULL;
5887 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005888 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005889 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5890 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005891 if (PyType_Ready(&PySSLSession_Type) < 0)
5892 return NULL;
5893
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005894
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005895 m = PyModule_Create(&_sslmodule);
5896 if (m == NULL)
5897 return NULL;
5898 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005900 /* Load _socket module and its C API */
5901 socket_api = PySocketModule_ImportModuleAndAPI();
5902 if (!socket_api)
5903 return NULL;
5904 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005905
Christian Heimesc941e622017-09-05 15:47:11 +02005906#ifndef OPENSSL_VERSION_1_1
5907 /* Load all algorithms and initialize cpuid */
5908 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005909 /* Init OpenSSL */
5910 SSL_load_error_strings();
5911 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005912#endif
5913
Christian Heimes598894f2016-09-05 23:19:05 +02005914#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005915 /* note that this will start threading if not already started */
5916 if (!_setup_ssl_threads()) {
5917 return NULL;
5918 }
Christian Heimes598894f2016-09-05 23:19:05 +02005919#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5920 /* OpenSSL 1.1.0 builtin thread support is enabled */
5921 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005922#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005924 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005925 sslerror_type_slots[0].pfunc = PyExc_OSError;
5926 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005927 if (PySSLErrorObject == NULL)
5928 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005929
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005930 /* ssl.CertificateError used to be a subclass of ValueError */
5931 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5932 if (bases == NULL)
5933 return NULL;
5934 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5935 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5936 bases, NULL);
5937 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005938 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5939 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5940 PySSLErrorObject, NULL);
5941 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5942 "ssl.SSLWantReadError", SSLWantReadError_doc,
5943 PySSLErrorObject, NULL);
5944 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5945 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5946 PySSLErrorObject, NULL);
5947 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5948 "ssl.SSLSyscallError", SSLSyscallError_doc,
5949 PySSLErrorObject, NULL);
5950 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5951 "ssl.SSLEOFError", SSLEOFError_doc,
5952 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005953 if (PySSLCertVerificationErrorObject == NULL
5954 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005955 || PySSLWantReadErrorObject == NULL
5956 || PySSLWantWriteErrorObject == NULL
5957 || PySSLSyscallErrorObject == NULL
5958 || PySSLEOFErrorObject == NULL)
5959 return NULL;
5960 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005961 || PyDict_SetItemString(d, "SSLCertVerificationError",
5962 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005963 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5964 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5965 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5966 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5967 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005968 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005969 if (PyDict_SetItemString(d, "_SSLContext",
5970 (PyObject *)&PySSLContext_Type) != 0)
5971 return NULL;
5972 if (PyDict_SetItemString(d, "_SSLSocket",
5973 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005974 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005975 if (PyDict_SetItemString(d, "MemoryBIO",
5976 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5977 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005978 if (PyDict_SetItemString(d, "SSLSession",
5979 (PyObject *)&PySSLSession_Type) != 0)
5980 return NULL;
5981
Christian Heimes892d66e2018-01-29 14:10:18 +01005982 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5983 PY_SSL_DEFAULT_CIPHER_STRING);
5984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005985 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5986 PY_SSL_ERROR_ZERO_RETURN);
5987 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5988 PY_SSL_ERROR_WANT_READ);
5989 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5990 PY_SSL_ERROR_WANT_WRITE);
5991 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5992 PY_SSL_ERROR_WANT_X509_LOOKUP);
5993 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5994 PY_SSL_ERROR_SYSCALL);
5995 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5996 PY_SSL_ERROR_SSL);
5997 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5998 PY_SSL_ERROR_WANT_CONNECT);
5999 /* non ssl.h errorcodes */
6000 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6001 PY_SSL_ERROR_EOF);
6002 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6003 PY_SSL_ERROR_INVALID_ERROR_CODE);
6004 /* cert requirements */
6005 PyModule_AddIntConstant(m, "CERT_NONE",
6006 PY_SSL_CERT_NONE);
6007 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6008 PY_SSL_CERT_OPTIONAL);
6009 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6010 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006011 /* CRL verification for verification_flags */
6012 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6013 0);
6014 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6015 X509_V_FLAG_CRL_CHECK);
6016 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6017 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6018 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6019 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006020#ifdef X509_V_FLAG_TRUSTED_FIRST
6021 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6022 X509_V_FLAG_TRUSTED_FIRST);
6023#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006024
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006025 /* Alert Descriptions from ssl.h */
6026 /* note RESERVED constants no longer intended for use have been removed */
6027 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6028
6029#define ADD_AD_CONSTANT(s) \
6030 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6031 SSL_AD_##s)
6032
6033 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6034 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6035 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6036 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6037 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6038 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6039 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6040 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6041 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6042 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6043 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6044 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6045 ADD_AD_CONSTANT(UNKNOWN_CA);
6046 ADD_AD_CONSTANT(ACCESS_DENIED);
6047 ADD_AD_CONSTANT(DECODE_ERROR);
6048 ADD_AD_CONSTANT(DECRYPT_ERROR);
6049 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6050 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6051 ADD_AD_CONSTANT(INTERNAL_ERROR);
6052 ADD_AD_CONSTANT(USER_CANCELLED);
6053 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006054 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006055#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6056 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6057#endif
6058#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6059 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6060#endif
6061#ifdef SSL_AD_UNRECOGNIZED_NAME
6062 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6063#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006064#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6065 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6066#endif
6067#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6068 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6069#endif
6070#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6071 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6072#endif
6073
6074#undef ADD_AD_CONSTANT
6075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006076 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006077#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006078 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6079 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006080#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006081#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006082 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6083 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006084#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006085 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006086 PY_SSL_VERSION_TLS);
6087 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6088 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006089 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6090 PY_SSL_VERSION_TLS_CLIENT);
6091 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6092 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006093 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6094 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006095#if HAVE_TLSv1_2
6096 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6097 PY_SSL_VERSION_TLS1_1);
6098 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6099 PY_SSL_VERSION_TLS1_2);
6100#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006101
Antoine Pitroub5218772010-05-21 09:56:06 +00006102 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006103 PyModule_AddIntConstant(m, "OP_ALL",
6104 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006105 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6106 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6107 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006108#if HAVE_TLSv1_2
6109 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6110 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6111#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006112#ifdef SSL_OP_NO_TLSv1_3
6113 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6114#else
6115 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6116#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006117 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6118 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006119 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006120 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006121#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006122 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006123#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006124#ifdef SSL_OP_NO_COMPRESSION
6125 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6126 SSL_OP_NO_COMPRESSION);
6127#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006128#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6129 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6130 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6131#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006132#ifdef SSL_OP_NO_RENEGOTIATION
6133 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6134 SSL_OP_NO_RENEGOTIATION);
6135#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006136
Christian Heimes61d478c2018-01-27 15:51:38 +01006137#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6138 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6139 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6140#endif
6141#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6142 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6143 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6144#endif
6145#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6146 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6147 X509_CHECK_FLAG_NO_WILDCARDS);
6148#endif
6149#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6150 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6151 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6152#endif
6153#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6154 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6155 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6156#endif
6157#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6158 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6159 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6160#endif
6161
Christian Heimes698dde12018-02-27 11:54:43 +01006162 /* protocol versions */
6163 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6164 PY_PROTO_MINIMUM_SUPPORTED);
6165 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6166 PY_PROTO_MAXIMUM_SUPPORTED);
6167 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6168 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6169 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6170 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6171 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006172
Victor Stinnerb37672d2018-11-22 03:37:50 +01006173#define addbool(m, key, value) \
6174 do { \
6175 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6176 Py_INCREF(bool_obj); \
6177 PyModule_AddObject((m), (key), bool_obj); \
6178 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006179
6180#if HAVE_SNI
6181 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006182#else
Christian Heimes698dde12018-02-27 11:54:43 +01006183 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006184#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006185
6186 addbool(m, "HAS_TLS_UNIQUE", 1);
6187
6188#ifndef OPENSSL_NO_ECDH
6189 addbool(m, "HAS_ECDH", 1);
6190#else
6191 addbool(m, "HAS_ECDH", 0);
6192#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006193
Christian Heimes29eab552018-02-25 12:31:33 +01006194#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006195 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006196#else
Christian Heimes698dde12018-02-27 11:54:43 +01006197 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006198#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006199
Christian Heimes29eab552018-02-25 12:31:33 +01006200#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006201 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006202#else
Christian Heimes698dde12018-02-27 11:54:43 +01006203 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006204#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006205
6206#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6207 addbool(m, "HAS_SSLv2", 1);
6208#else
6209 addbool(m, "HAS_SSLv2", 0);
6210#endif
6211
6212#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6213 addbool(m, "HAS_SSLv3", 1);
6214#else
6215 addbool(m, "HAS_SSLv3", 0);
6216#endif
6217
6218#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6219 addbool(m, "HAS_TLSv1", 1);
6220#else
6221 addbool(m, "HAS_TLSv1", 0);
6222#endif
6223
6224#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6225 addbool(m, "HAS_TLSv1_1", 1);
6226#else
6227 addbool(m, "HAS_TLSv1_1", 0);
6228#endif
6229
6230#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6231 addbool(m, "HAS_TLSv1_2", 1);
6232#else
6233 addbool(m, "HAS_TLSv1_2", 0);
6234#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006235
Christian Heimescb5b68a2017-09-07 18:07:00 -07006236#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006237 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006238#else
Christian Heimes698dde12018-02-27 11:54:43 +01006239 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006240#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006241
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006242 /* Mappings for error codes */
6243 err_codes_to_names = PyDict_New();
6244 err_names_to_codes = PyDict_New();
6245 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6246 return NULL;
6247 errcode = error_codes;
6248 while (errcode->mnemonic != NULL) {
6249 PyObject *mnemo, *key;
6250 mnemo = PyUnicode_FromString(errcode->mnemonic);
6251 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6252 if (mnemo == NULL || key == NULL)
6253 return NULL;
6254 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6255 return NULL;
6256 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6257 return NULL;
6258 Py_DECREF(key);
6259 Py_DECREF(mnemo);
6260 errcode++;
6261 }
6262 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6263 return NULL;
6264 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6265 return NULL;
6266
6267 lib_codes_to_names = PyDict_New();
6268 if (lib_codes_to_names == NULL)
6269 return NULL;
6270 libcode = library_codes;
6271 while (libcode->library != NULL) {
6272 PyObject *mnemo, *key;
6273 key = PyLong_FromLong(libcode->code);
6274 mnemo = PyUnicode_FromString(libcode->library);
6275 if (key == NULL || mnemo == NULL)
6276 return NULL;
6277 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6278 return NULL;
6279 Py_DECREF(key);
6280 Py_DECREF(mnemo);
6281 libcode++;
6282 }
6283 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6284 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006285
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006286 /* OpenSSL version */
6287 /* SSLeay() gives us the version of the library linked against,
6288 which could be different from the headers version.
6289 */
6290 libver = SSLeay();
6291 r = PyLong_FromUnsignedLong(libver);
6292 if (r == NULL)
6293 return NULL;
6294 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6295 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006296 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006297 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6298 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6299 return NULL;
6300 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6301 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6302 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006303
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006304 libver = OPENSSL_VERSION_NUMBER;
6305 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6306 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6307 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6308 return NULL;
6309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006310 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006311}