blob: 6f1f9c881530f04e9a469784446e3dd4728c32f0 [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 Heimesf22c4cf2019-07-01 09:25:48 +0200966#ifdef TLS1_3_VERSION
967 if (sslctx->post_handshake_auth == 1) {
968 if (socket_type == PY_SSL_SERVER) {
969 /* bpo-37428: OpenSSL does not ignore SSL_VERIFY_POST_HANDSHAKE.
970 * Set SSL_VERIFY_POST_HANDSHAKE flag only for server sockets and
971 * only in combination with SSL_VERIFY_PEER flag. */
972 int mode = SSL_get_verify_mode(self->ssl);
973 if (mode & SSL_VERIFY_PEER) {
974 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
975 verify_cb = SSL_get_verify_callback(self->ssl);
976 mode |= SSL_VERIFY_POST_HANDSHAKE;
977 SSL_set_verify(self->ssl, mode, verify_cb);
978 }
979 } else {
980 /* client socket */
981 SSL_set_post_handshake_auth(self->ssl, 1);
982 }
983 }
984#endif
985
Christian Heimes61d478c2018-01-27 15:51:38 +0100986 if (server_hostname != NULL) {
987 if (_ssl_configure_hostname(self, server_hostname) < 0) {
988 Py_DECREF(self);
989 return NULL;
990 }
991 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 /* If the socket is in non-blocking mode or timeout mode, set the BIO
993 * to non-blocking mode (blocking is the default)
994 */
Victor Stinnere2452312015-03-28 03:00:46 +0100995 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
997 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
998 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 PySSL_BEGIN_ALLOW_THREADS
1001 if (socket_type == PY_SSL_CLIENT)
1002 SSL_set_connect_state(self->ssl);
1003 else
1004 SSL_set_accept_state(self->ssl);
1005 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +00001006
Antoine Pitroud6494802011-07-21 01:11:30 +02001007 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001008 if (sock != NULL) {
1009 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
1010 if (self->Socket == NULL) {
1011 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001012 return NULL;
1013 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +01001014 }
Christian Heimes141c5e82018-02-24 21:10:57 +01001015 if (owner && owner != Py_None) {
1016 if (PySSL_set_owner(self, owner, NULL) == -1) {
1017 Py_DECREF(self);
1018 return NULL;
1019 }
1020 }
1021 if (session && session != Py_None) {
1022 if (PySSL_set_session(self, session, NULL) == -1) {
1023 Py_DECREF(self);
1024 return NULL;
1025 }
1026 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001028}
1029
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001030/* SSL object methods */
1031
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001032/*[clinic input]
1033_ssl._SSLSocket.do_handshake
1034[clinic start generated code]*/
1035
1036static PyObject *
1037_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1038/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001039{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001041 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001043 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001044 _PyTime_t timeout, deadline = 0;
1045 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001046
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001047 if (sock) {
1048 if (((PyObject*)sock) == Py_None) {
1049 _setSSLError("Underlying socket connection gone",
1050 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1051 return NULL;
1052 }
1053 Py_INCREF(sock);
1054
1055 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001056 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001057 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1058 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001060
Victor Stinner14690702015-04-06 22:46:13 +02001061 timeout = GET_SOCKET_TIMEOUT(sock);
1062 has_timeout = (timeout > 0);
1063 if (has_timeout)
1064 deadline = _PyTime_GetMonotonicClock() + timeout;
1065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 /* Actually negotiate SSL connection */
1067 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001069 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001071 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001073 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001074
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001075 if (PyErr_CheckSignals())
1076 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001077
Victor Stinner14690702015-04-06 22:46:13 +02001078 if (has_timeout)
1079 timeout = deadline - _PyTime_GetMonotonicClock();
1080
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001081 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001082 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001083 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001084 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001085 } else {
1086 sockstate = SOCKET_OPERATION_OK;
1087 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001088
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001089 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001090 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001091 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001092 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1094 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001095 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001096 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1098 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001099 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001100 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001101 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1102 break;
1103 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001104 } while (err.ssl == SSL_ERROR_WANT_READ ||
1105 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001106 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 if (ret < 1)
1108 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001109 if (PySSL_ChainExceptions(self) < 0)
1110 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001111 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001112error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001113 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001114 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001115 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001116}
1117
Thomas Woutersed03b412007-08-28 21:37:11 +00001118static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001119_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1120{
1121 char buf[X509_NAME_MAXLEN];
1122 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001124 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001125
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001126 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 if (buflen < 0) {
1128 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001129 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001131 /* initial buffer is too small for oid + terminating null byte */
1132 if (buflen > X509_NAME_MAXLEN - 1) {
1133 /* make OBJ_obj2txt() calculate the required buflen */
1134 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1135 /* allocate len + 1 for terminating NULL byte */
1136 namebuf = PyMem_Malloc(buflen + 1);
1137 if (namebuf == NULL) {
1138 PyErr_NoMemory();
1139 return NULL;
1140 }
1141 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1142 if (buflen < 0) {
1143 _setSSLError(NULL, 0, __FILE__, __LINE__);
1144 goto done;
1145 }
1146 }
1147 if (!buflen && no_name) {
1148 Py_INCREF(Py_None);
1149 name_obj = Py_None;
1150 }
1151 else {
1152 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1153 }
1154
1155 done:
1156 if (buf != namebuf) {
1157 PyMem_Free(namebuf);
1158 }
1159 return name_obj;
1160}
1161
1162static PyObject *
1163_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1164{
1165 Py_ssize_t buflen;
1166 unsigned char *valuebuf = NULL;
1167 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1170 if (buflen < 0) {
1171 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001172 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001174 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001175 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001177}
1178
1179static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001181{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1183 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1184 PyObject *rdnt;
1185 PyObject *attr = NULL; /* tuple to hold an attribute */
1186 int entry_count = X509_NAME_entry_count(xname);
1187 X509_NAME_ENTRY *entry;
1188 ASN1_OBJECT *name;
1189 ASN1_STRING *value;
1190 int index_counter;
1191 int rdn_level = -1;
1192 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 dn = PyList_New(0);
1195 if (dn == NULL)
1196 return NULL;
1197 /* now create another tuple to hold the top-level RDN */
1198 rdn = PyList_New(0);
1199 if (rdn == NULL)
1200 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 for (index_counter = 0;
1203 index_counter < entry_count;
1204 index_counter++)
1205 {
1206 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 /* check to see if we've gotten to a new RDN */
1209 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001210 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 /* yes, new RDN */
1212 /* add old RDN to DN */
1213 rdnt = PyList_AsTuple(rdn);
1214 Py_DECREF(rdn);
1215 if (rdnt == NULL)
1216 goto fail0;
1217 retcode = PyList_Append(dn, rdnt);
1218 Py_DECREF(rdnt);
1219 if (retcode < 0)
1220 goto fail0;
1221 /* create new RDN */
1222 rdn = PyList_New(0);
1223 if (rdn == NULL)
1224 goto fail0;
1225 }
1226 }
Christian Heimes598894f2016-09-05 23:19:05 +02001227 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 /* now add this attribute to the current RDN */
1230 name = X509_NAME_ENTRY_get_object(entry);
1231 value = X509_NAME_ENTRY_get_data(entry);
1232 attr = _create_tuple_for_attribute(name, value);
1233 /*
1234 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1235 entry->set,
1236 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1237 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1238 */
1239 if (attr == NULL)
1240 goto fail1;
1241 retcode = PyList_Append(rdn, attr);
1242 Py_DECREF(attr);
1243 if (retcode < 0)
1244 goto fail1;
1245 }
1246 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001247 if (rdn != NULL) {
1248 if (PyList_GET_SIZE(rdn) > 0) {
1249 rdnt = PyList_AsTuple(rdn);
1250 Py_DECREF(rdn);
1251 if (rdnt == NULL)
1252 goto fail0;
1253 retcode = PyList_Append(dn, rdnt);
1254 Py_DECREF(rdnt);
1255 if (retcode < 0)
1256 goto fail0;
1257 }
1258 else {
1259 Py_DECREF(rdn);
1260 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 /* convert list to tuple */
1264 rdnt = PyList_AsTuple(dn);
1265 Py_DECREF(dn);
1266 if (rdnt == NULL)
1267 return NULL;
1268 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001269
1270 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272
1273 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 Py_XDECREF(dn);
1275 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276}
1277
1278static PyObject *
1279_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001281 /* this code follows the procedure outlined in
1282 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1283 function to extract the STACK_OF(GENERAL_NAME),
1284 then iterates through the stack to add the
1285 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001287 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001289 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 GENERAL_NAMES *names = NULL;
1291 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001292 BIO *biobuf = NULL;
1293 char buf[2048];
1294 char *vptr;
1295 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001296
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 if (certificate == NULL)
1298 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001300 /* get a memory buffer */
1301 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001302 if (biobuf == NULL) {
1303 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1304 return NULL;
1305 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001306
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001307 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1308 certificate, NID_subject_alt_name, NULL, NULL);
1309 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 if (peer_alt_names == Py_None) {
1311 peer_alt_names = PyList_New(0);
1312 if (peer_alt_names == NULL)
1313 goto fail;
1314 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001317 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001318 int gntype;
1319 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001322 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001323 switch (gntype) {
1324 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001325 /* we special-case DirName as a tuple of
1326 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001328 t = PyTuple_New(2);
1329 if (t == NULL) {
1330 goto fail;
1331 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 v = PyUnicode_FromString("DirName");
1334 if (v == NULL) {
1335 Py_DECREF(t);
1336 goto fail;
1337 }
1338 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 v = _create_tuple_for_X509_NAME (name->d.dirn);
1341 if (v == NULL) {
1342 Py_DECREF(t);
1343 goto fail;
1344 }
1345 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001346 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001347
Christian Heimes824f7f32013-08-17 00:54:47 +02001348 case GEN_EMAIL:
1349 case GEN_DNS:
1350 case GEN_URI:
1351 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1352 correctly, CVE-2013-4238 */
1353 t = PyTuple_New(2);
1354 if (t == NULL)
1355 goto fail;
1356 switch (gntype) {
1357 case GEN_EMAIL:
1358 v = PyUnicode_FromString("email");
1359 as = name->d.rfc822Name;
1360 break;
1361 case GEN_DNS:
1362 v = PyUnicode_FromString("DNS");
1363 as = name->d.dNSName;
1364 break;
1365 case GEN_URI:
1366 v = PyUnicode_FromString("URI");
1367 as = name->d.uniformResourceIdentifier;
1368 break;
1369 }
1370 if (v == NULL) {
1371 Py_DECREF(t);
1372 goto fail;
1373 }
1374 PyTuple_SET_ITEM(t, 0, v);
1375 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1376 ASN1_STRING_length(as));
1377 if (v == NULL) {
1378 Py_DECREF(t);
1379 goto fail;
1380 }
1381 PyTuple_SET_ITEM(t, 1, v);
1382 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001383
Christian Heimes1c03abd2016-09-06 23:25:35 +02001384 case GEN_RID:
1385 t = PyTuple_New(2);
1386 if (t == NULL)
1387 goto fail;
1388
1389 v = PyUnicode_FromString("Registered ID");
1390 if (v == NULL) {
1391 Py_DECREF(t);
1392 goto fail;
1393 }
1394 PyTuple_SET_ITEM(t, 0, v);
1395
1396 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1397 if (len < 0) {
1398 Py_DECREF(t);
1399 _setSSLError(NULL, 0, __FILE__, __LINE__);
1400 goto fail;
1401 } else if (len >= (int)sizeof(buf)) {
1402 v = PyUnicode_FromString("<INVALID>");
1403 } else {
1404 v = PyUnicode_FromStringAndSize(buf, len);
1405 }
1406 if (v == NULL) {
1407 Py_DECREF(t);
1408 goto fail;
1409 }
1410 PyTuple_SET_ITEM(t, 1, v);
1411 break;
1412
Christian Heimes824f7f32013-08-17 00:54:47 +02001413 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001414 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001415 switch (gntype) {
1416 /* check for new general name type */
1417 case GEN_OTHERNAME:
1418 case GEN_X400:
1419 case GEN_EDIPARTY:
1420 case GEN_IPADD:
1421 case GEN_RID:
1422 break;
1423 default:
1424 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1425 "Unknown general name type %d",
1426 gntype) == -1) {
1427 goto fail;
1428 }
1429 break;
1430 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 (void) BIO_reset(biobuf);
1432 GENERAL_NAME_print(biobuf, name);
1433 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1434 if (len < 0) {
1435 _setSSLError(NULL, 0, __FILE__, __LINE__);
1436 goto fail;
1437 }
1438 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001439 if (vptr == NULL) {
1440 PyErr_Format(PyExc_ValueError,
1441 "Invalid value %.200s",
1442 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001443 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001444 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 t = PyTuple_New(2);
1446 if (t == NULL)
1447 goto fail;
1448 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1449 if (v == NULL) {
1450 Py_DECREF(t);
1451 goto fail;
1452 }
1453 PyTuple_SET_ITEM(t, 0, v);
1454 v = PyUnicode_FromStringAndSize((vptr + 1),
1455 (len - (vptr - buf + 1)));
1456 if (v == NULL) {
1457 Py_DECREF(t);
1458 goto fail;
1459 }
1460 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001461 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 if (PyList_Append(peer_alt_names, t) < 0) {
1467 Py_DECREF(t);
1468 goto fail;
1469 }
1470 Py_DECREF(t);
1471 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001472 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 }
1474 BIO_free(biobuf);
1475 if (peer_alt_names != Py_None) {
1476 v = PyList_AsTuple(peer_alt_names);
1477 Py_DECREF(peer_alt_names);
1478 return v;
1479 } else {
1480 return peer_alt_names;
1481 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001482
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483
1484 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001485 if (biobuf != NULL)
1486 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001487
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 if (peer_alt_names != Py_None) {
1489 Py_XDECREF(peer_alt_names);
1490 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001491
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001492 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001493}
1494
1495static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001496_get_aia_uri(X509 *certificate, int nid) {
1497 PyObject *lst = NULL, *ostr = NULL;
1498 int i, result;
1499 AUTHORITY_INFO_ACCESS *info;
1500
1501 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001502 if (info == NULL)
1503 return Py_None;
1504 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1505 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001506 return Py_None;
1507 }
1508
1509 if ((lst = PyList_New(0)) == NULL) {
1510 goto fail;
1511 }
1512
1513 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1514 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1515 ASN1_IA5STRING *uri;
1516
1517 if ((OBJ_obj2nid(ad->method) != nid) ||
1518 (ad->location->type != GEN_URI)) {
1519 continue;
1520 }
1521 uri = ad->location->d.uniformResourceIdentifier;
1522 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1523 uri->length);
1524 if (ostr == NULL) {
1525 goto fail;
1526 }
1527 result = PyList_Append(lst, ostr);
1528 Py_DECREF(ostr);
1529 if (result < 0) {
1530 goto fail;
1531 }
1532 }
1533 AUTHORITY_INFO_ACCESS_free(info);
1534
1535 /* convert to tuple or None */
1536 if (PyList_Size(lst) == 0) {
1537 Py_DECREF(lst);
1538 return Py_None;
1539 } else {
1540 PyObject *tup;
1541 tup = PyList_AsTuple(lst);
1542 Py_DECREF(lst);
1543 return tup;
1544 }
1545
1546 fail:
1547 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001548 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001549 return NULL;
1550}
1551
1552static PyObject *
1553_get_crl_dp(X509 *certificate) {
1554 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001555 int i, j;
1556 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001557
Christian Heimes598894f2016-09-05 23:19:05 +02001558 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001559
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001560 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001561 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001562
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001563 lst = PyList_New(0);
1564 if (lst == NULL)
1565 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001566
1567 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1568 DIST_POINT *dp;
1569 STACK_OF(GENERAL_NAME) *gns;
1570
1571 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001572 if (dp->distpoint == NULL) {
1573 /* Ignore empty DP value, CVE-2019-5010 */
1574 continue;
1575 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001576 gns = dp->distpoint->name.fullname;
1577
1578 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1579 GENERAL_NAME *gn;
1580 ASN1_IA5STRING *uri;
1581 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001582 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001583
1584 gn = sk_GENERAL_NAME_value(gns, j);
1585 if (gn->type != GEN_URI) {
1586 continue;
1587 }
1588 uri = gn->d.uniformResourceIdentifier;
1589 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1590 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001591 if (ouri == NULL)
1592 goto done;
1593
1594 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001595 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001596 if (err < 0)
1597 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001598 }
1599 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001600
1601 /* Convert to tuple. */
1602 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1603
1604 done:
1605 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001606 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001607 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001608}
1609
1610static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001611_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001612
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 PyObject *retval = NULL;
1614 BIO *biobuf = NULL;
1615 PyObject *peer;
1616 PyObject *peer_alt_names = NULL;
1617 PyObject *issuer;
1618 PyObject *version;
1619 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001620 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 ASN1_INTEGER *serialNumber;
1622 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001623 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 ASN1_TIME *notBefore, *notAfter;
1625 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 retval = PyDict_New();
1628 if (retval == NULL)
1629 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001630
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 peer = _create_tuple_for_X509_NAME(
1632 X509_get_subject_name(certificate));
1633 if (peer == NULL)
1634 goto fail0;
1635 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1636 Py_DECREF(peer);
1637 goto fail0;
1638 }
1639 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001640
Antoine Pitroufb046912010-11-09 20:21:19 +00001641 issuer = _create_tuple_for_X509_NAME(
1642 X509_get_issuer_name(certificate));
1643 if (issuer == NULL)
1644 goto fail0;
1645 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001647 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001649 Py_DECREF(issuer);
1650
1651 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001652 if (version == NULL)
1653 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001654 if (PyDict_SetItemString(retval, "version", version) < 0) {
1655 Py_DECREF(version);
1656 goto fail0;
1657 }
1658 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001659
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001660 /* get a memory buffer */
1661 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001662 if (biobuf == NULL) {
1663 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1664 goto fail0;
1665 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001666
Antoine Pitroufb046912010-11-09 20:21:19 +00001667 (void) BIO_reset(biobuf);
1668 serialNumber = X509_get_serialNumber(certificate);
1669 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1670 i2a_ASN1_INTEGER(biobuf, serialNumber);
1671 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1672 if (len < 0) {
1673 _setSSLError(NULL, 0, __FILE__, __LINE__);
1674 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001676 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1677 if (sn_obj == NULL)
1678 goto fail1;
1679 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1680 Py_DECREF(sn_obj);
1681 goto fail1;
1682 }
1683 Py_DECREF(sn_obj);
1684
1685 (void) BIO_reset(biobuf);
1686 notBefore = X509_get_notBefore(certificate);
1687 ASN1_TIME_print(biobuf, notBefore);
1688 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1689 if (len < 0) {
1690 _setSSLError(NULL, 0, __FILE__, __LINE__);
1691 goto fail1;
1692 }
1693 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1694 if (pnotBefore == NULL)
1695 goto fail1;
1696 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1697 Py_DECREF(pnotBefore);
1698 goto fail1;
1699 }
1700 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 (void) BIO_reset(biobuf);
1703 notAfter = X509_get_notAfter(certificate);
1704 ASN1_TIME_print(biobuf, notAfter);
1705 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1706 if (len < 0) {
1707 _setSSLError(NULL, 0, __FILE__, __LINE__);
1708 goto fail1;
1709 }
1710 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1711 if (pnotAfter == NULL)
1712 goto fail1;
1713 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1714 Py_DECREF(pnotAfter);
1715 goto fail1;
1716 }
1717 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001718
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 peer_alt_names = _get_peer_alt_names(certificate);
1722 if (peer_alt_names == NULL)
1723 goto fail1;
1724 else if (peer_alt_names != Py_None) {
1725 if (PyDict_SetItemString(retval, "subjectAltName",
1726 peer_alt_names) < 0) {
1727 Py_DECREF(peer_alt_names);
1728 goto fail1;
1729 }
1730 Py_DECREF(peer_alt_names);
1731 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001732
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001733 /* Authority Information Access: OCSP URIs */
1734 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1735 if (obj == NULL) {
1736 goto fail1;
1737 } else if (obj != Py_None) {
1738 result = PyDict_SetItemString(retval, "OCSP", obj);
1739 Py_DECREF(obj);
1740 if (result < 0) {
1741 goto fail1;
1742 }
1743 }
1744
1745 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1746 if (obj == NULL) {
1747 goto fail1;
1748 } else if (obj != Py_None) {
1749 result = PyDict_SetItemString(retval, "caIssuers", obj);
1750 Py_DECREF(obj);
1751 if (result < 0) {
1752 goto fail1;
1753 }
1754 }
1755
1756 /* CDP (CRL distribution points) */
1757 obj = _get_crl_dp(certificate);
1758 if (obj == NULL) {
1759 goto fail1;
1760 } else if (obj != Py_None) {
1761 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1762 Py_DECREF(obj);
1763 if (result < 0) {
1764 goto fail1;
1765 }
1766 }
1767
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 BIO_free(biobuf);
1769 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001770
1771 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 if (biobuf != NULL)
1773 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001774 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001775 Py_XDECREF(retval);
1776 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001777}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001778
Christian Heimes9a5395a2013-06-17 15:44:12 +02001779static PyObject *
1780_certificate_to_der(X509 *certificate)
1781{
1782 unsigned char *bytes_buf = NULL;
1783 int len;
1784 PyObject *retval;
1785
1786 bytes_buf = NULL;
1787 len = i2d_X509(certificate, &bytes_buf);
1788 if (len < 0) {
1789 _setSSLError(NULL, 0, __FILE__, __LINE__);
1790 return NULL;
1791 }
1792 /* this is actually an immutable bytes sequence */
1793 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1794 OPENSSL_free(bytes_buf);
1795 return retval;
1796}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001797
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001798/*[clinic input]
1799_ssl._test_decode_cert
1800 path: object(converter="PyUnicode_FSConverter")
1801 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001802
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001803[clinic start generated code]*/
1804
1805static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001806_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1807/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001808{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 X509 *x=NULL;
1811 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001813 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1814 PyErr_SetString(PySSLErrorObject,
1815 "Can't malloc memory to read file");
1816 goto fail0;
1817 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001818
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001819 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 PyErr_SetString(PySSLErrorObject,
1821 "Can't open file");
1822 goto fail0;
1823 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001824
Miss Islington (bot)f7812832019-08-15 05:52:51 -07001825 x = PEM_read_bio_X509(cert, NULL, NULL, NULL);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 if (x == NULL) {
1827 PyErr_SetString(PySSLErrorObject,
1828 "Error decoding PEM-encoded file");
1829 goto fail0;
1830 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001831
Antoine Pitroufb046912010-11-09 20:21:19 +00001832 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001833 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001834
1835 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001836 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 if (cert != NULL) BIO_free(cert);
1838 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001839}
1840
1841
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001842/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001843_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001844 der as binary_mode: bool = False
1845 /
1846
1847Returns the certificate for the peer.
1848
1849If no certificate was provided, returns None. If a certificate was
1850provided, but not validated, returns an empty dictionary. Otherwise
1851returns a dict containing information about the peer certificate.
1852
1853If the optional argument is True, returns a DER-encoded copy of the
1854peer certificate, or None if no certificate was provided. This will
1855return the certificate even if it wasn't validated.
1856[clinic start generated code]*/
1857
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001858static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001859_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1860/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001861{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001863 X509 *peer_cert;
1864 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001865
Christian Heimes66dc33b2017-05-23 16:02:02 -07001866 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001867 PyErr_SetString(PyExc_ValueError,
1868 "handshake not done yet");
1869 return NULL;
1870 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001871 peer_cert = SSL_get_peer_certificate(self->ssl);
1872 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001874
Antoine Pitrou721738f2012-08-15 23:20:39 +02001875 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001877 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001879 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001881 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001883 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001884 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001885 X509_free(peer_cert);
1886 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001887}
1888
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001889static PyObject *
1890cipher_to_tuple(const SSL_CIPHER *cipher)
1891{
1892 const char *cipher_name, *cipher_protocol;
1893 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 if (retval == NULL)
1895 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001896
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001897 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001898 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001899 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 PyTuple_SET_ITEM(retval, 0, Py_None);
1901 } else {
1902 v = PyUnicode_FromString(cipher_name);
1903 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001904 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001905 PyTuple_SET_ITEM(retval, 0, v);
1906 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001907
1908 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001910 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001911 PyTuple_SET_ITEM(retval, 1, Py_None);
1912 } else {
1913 v = PyUnicode_FromString(cipher_protocol);
1914 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001915 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 PyTuple_SET_ITEM(retval, 1, v);
1917 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001918
1919 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001921 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001925
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001926 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 Py_DECREF(retval);
1928 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001929}
1930
Christian Heimes25bfcd52016-09-06 00:04:45 +02001931#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1932static PyObject *
1933cipher_to_dict(const SSL_CIPHER *cipher)
1934{
1935 const char *cipher_name, *cipher_protocol;
1936
1937 unsigned long cipher_id;
1938 int alg_bits, strength_bits, len;
1939 char buf[512] = {0};
1940#if OPENSSL_VERSION_1_1
1941 int aead, nid;
1942 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1943#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001944
1945 /* can be NULL */
1946 cipher_name = SSL_CIPHER_get_name(cipher);
1947 cipher_protocol = SSL_CIPHER_get_version(cipher);
1948 cipher_id = SSL_CIPHER_get_id(cipher);
1949 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001950 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1951 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001952 if (len > 1 && buf[len-1] == '\n')
1953 buf[len-1] = '\0';
1954 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1955
1956#if OPENSSL_VERSION_1_1
1957 aead = SSL_CIPHER_is_aead(cipher);
1958 nid = SSL_CIPHER_get_cipher_nid(cipher);
1959 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1960 nid = SSL_CIPHER_get_digest_nid(cipher);
1961 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1962 nid = SSL_CIPHER_get_kx_nid(cipher);
1963 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1964 nid = SSL_CIPHER_get_auth_nid(cipher);
1965 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1966#endif
1967
Victor Stinner410b9882016-09-12 12:00:23 +02001968 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001969 "{sksssssssisi"
1970#if OPENSSL_VERSION_1_1
1971 "sOssssssss"
1972#endif
1973 "}",
1974 "id", cipher_id,
1975 "name", cipher_name,
1976 "protocol", cipher_protocol,
1977 "description", buf,
1978 "strength_bits", strength_bits,
1979 "alg_bits", alg_bits
1980#if OPENSSL_VERSION_1_1
1981 ,"aead", aead ? Py_True : Py_False,
1982 "symmetric", skcipher,
1983 "digest", digest,
1984 "kea", kx,
1985 "auth", auth
1986#endif
1987 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001988}
1989#endif
1990
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001991/*[clinic input]
1992_ssl._SSLSocket.shared_ciphers
1993[clinic start generated code]*/
1994
1995static PyObject *
1996_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1997/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001998{
1999 STACK_OF(SSL_CIPHER) *ciphers;
2000 int i;
2001 PyObject *res;
2002
Christian Heimes598894f2016-09-05 23:19:05 +02002003 ciphers = SSL_get_ciphers(self->ssl);
2004 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002005 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002006 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
2007 if (!res)
2008 return NULL;
2009 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2010 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
2011 if (!tup) {
2012 Py_DECREF(res);
2013 return NULL;
2014 }
2015 PyList_SET_ITEM(res, i, tup);
2016 }
2017 return res;
2018}
2019
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002020/*[clinic input]
2021_ssl._SSLSocket.cipher
2022[clinic start generated code]*/
2023
2024static PyObject *
2025_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2026/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002027{
2028 const SSL_CIPHER *current;
2029
2030 if (self->ssl == NULL)
2031 Py_RETURN_NONE;
2032 current = SSL_get_current_cipher(self->ssl);
2033 if (current == NULL)
2034 Py_RETURN_NONE;
2035 return cipher_to_tuple(current);
2036}
2037
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002038/*[clinic input]
2039_ssl._SSLSocket.version
2040[clinic start generated code]*/
2041
2042static PyObject *
2043_ssl__SSLSocket_version_impl(PySSLSocket *self)
2044/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002045{
2046 const char *version;
2047
2048 if (self->ssl == NULL)
2049 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002050 if (!SSL_is_init_finished(self->ssl)) {
2051 /* handshake not finished */
2052 Py_RETURN_NONE;
2053 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002054 version = SSL_get_version(self->ssl);
2055 if (!strcmp(version, "unknown"))
2056 Py_RETURN_NONE;
2057 return PyUnicode_FromString(version);
2058}
2059
Christian Heimes29eab552018-02-25 12:31:33 +01002060#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002061/*[clinic input]
2062_ssl._SSLSocket.selected_npn_protocol
2063[clinic start generated code]*/
2064
2065static PyObject *
2066_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2067/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2068{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002069 const unsigned char *out;
2070 unsigned int outlen;
2071
Victor Stinner4569cd52013-06-23 14:58:43 +02002072 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002073 &out, &outlen);
2074
2075 if (out == NULL)
2076 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002077 return PyUnicode_FromStringAndSize((char *)out, outlen);
2078}
2079#endif
2080
Christian Heimes29eab552018-02-25 12:31:33 +01002081#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002082/*[clinic input]
2083_ssl._SSLSocket.selected_alpn_protocol
2084[clinic start generated code]*/
2085
2086static PyObject *
2087_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2088/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2089{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002090 const unsigned char *out;
2091 unsigned int outlen;
2092
2093 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2094
2095 if (out == NULL)
2096 Py_RETURN_NONE;
2097 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002098}
2099#endif
2100
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002101/*[clinic input]
2102_ssl._SSLSocket.compression
2103[clinic start generated code]*/
2104
2105static PyObject *
2106_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2107/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2108{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002109#ifdef OPENSSL_NO_COMP
2110 Py_RETURN_NONE;
2111#else
2112 const COMP_METHOD *comp_method;
2113 const char *short_name;
2114
2115 if (self->ssl == NULL)
2116 Py_RETURN_NONE;
2117 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002118 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002119 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002120 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002121 if (short_name == NULL)
2122 Py_RETURN_NONE;
2123 return PyUnicode_DecodeFSDefault(short_name);
2124#endif
2125}
2126
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002127static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2128 Py_INCREF(self->ctx);
2129 return self->ctx;
2130}
2131
2132static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2133 void *closure) {
2134
2135 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002136#if !HAVE_SNI
2137 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2138 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002139 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002140#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002141 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002142 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002143 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002144#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002145 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002146 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002147 return -1;
2148 }
2149
2150 return 0;
2151}
2152
2153PyDoc_STRVAR(PySSL_set_context_doc,
2154"_setter_context(ctx)\n\
2155\
2156This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002157used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002158on the SSLContext to change the certificate information associated with the\n\
2159SSLSocket before the cryptographic exchange handshake messages\n");
2160
2161
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002162static PyObject *
2163PySSL_get_server_side(PySSLSocket *self, void *c)
2164{
2165 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2166}
2167
2168PyDoc_STRVAR(PySSL_get_server_side_doc,
2169"Whether this is a server-side socket.");
2170
2171static PyObject *
2172PySSL_get_server_hostname(PySSLSocket *self, void *c)
2173{
2174 if (self->server_hostname == NULL)
2175 Py_RETURN_NONE;
2176 Py_INCREF(self->server_hostname);
2177 return self->server_hostname;
2178}
2179
2180PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2181"The currently set server hostname (for SNI).");
2182
2183static PyObject *
2184PySSL_get_owner(PySSLSocket *self, void *c)
2185{
2186 PyObject *owner;
2187
2188 if (self->owner == NULL)
2189 Py_RETURN_NONE;
2190
2191 owner = PyWeakref_GetObject(self->owner);
2192 Py_INCREF(owner);
2193 return owner;
2194}
2195
2196static int
2197PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2198{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002199 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002200 if (self->owner == NULL)
2201 return -1;
2202 return 0;
2203}
2204
2205PyDoc_STRVAR(PySSL_get_owner_doc,
2206"The Python-level owner of this object.\
2207Passed as \"self\" in servername callback.");
2208
Christian Heimesc7f70692019-05-31 11:44:05 +02002209static int
2210PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2211{
2212 Py_VISIT(self->exc_type);
2213 Py_VISIT(self->exc_value);
2214 Py_VISIT(self->exc_tb);
2215 return 0;
2216}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002217
Christian Heimesc7f70692019-05-31 11:44:05 +02002218static int
2219PySSL_clear(PySSLSocket *self)
2220{
2221 Py_CLEAR(self->exc_type);
2222 Py_CLEAR(self->exc_value);
2223 Py_CLEAR(self->exc_tb);
2224 return 0;
2225}
2226
2227static void
2228PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002229{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 if (self->ssl)
2231 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002233 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002234 Py_XDECREF(self->server_hostname);
2235 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002237}
2238
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002239/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002240 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002241 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002242 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002243
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002244static int
Victor Stinner14690702015-04-06 22:46:13 +02002245PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002246{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002247 int rc;
2248#ifdef HAVE_POLL
2249 struct pollfd pollfd;
2250 _PyTime_t ms;
2251#else
2252 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 fd_set fds;
2254 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002255#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002258 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002259 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002260 else if (timeout < 0) {
2261 if (s->sock_timeout > 0)
2262 return SOCKET_HAS_TIMED_OUT;
2263 else
2264 return SOCKET_IS_BLOCKING;
2265 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002268 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 /* Prefer poll, if available, since you can poll() any fd
2272 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002273#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002274 pollfd.fd = s->sock_fd;
2275 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002276
Victor Stinner14690702015-04-06 22:46:13 +02002277 /* timeout is in seconds, poll() uses milliseconds */
2278 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002279 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002280
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002281 PySSL_BEGIN_ALLOW_THREADS
2282 rc = poll(&pollfd, 1, (int)ms);
2283 PySSL_END_ALLOW_THREADS
2284#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002286 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002288
Victor Stinner14690702015-04-06 22:46:13 +02002289 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 FD_ZERO(&fds);
2292 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002293
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002294 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002296 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002298 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002300 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002302#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2305 (when we are able to write or when there's something to read) */
2306 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002307}
2308
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002309/*[clinic input]
2310_ssl._SSLSocket.write
2311 b: Py_buffer
2312 /
2313
2314Writes the bytes-like object b into the SSL object.
2315
2316Returns the number of bytes written.
2317[clinic start generated code]*/
2318
2319static PyObject *
2320_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2321/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002322{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 int len;
2324 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002325 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002326 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002327 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002328 _PyTime_t timeout, deadline = 0;
2329 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002330
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002331 if (sock != NULL) {
2332 if (((PyObject*)sock) == Py_None) {
2333 _setSSLError("Underlying socket connection gone",
2334 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2335 return NULL;
2336 }
2337 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 }
2339
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002340 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002341 PyErr_Format(PyExc_OverflowError,
2342 "string longer than %d bytes", INT_MAX);
2343 goto error;
2344 }
2345
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002346 if (sock != NULL) {
2347 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002348 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002349 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2350 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2351 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352
Victor Stinner14690702015-04-06 22:46:13 +02002353 timeout = GET_SOCKET_TIMEOUT(sock);
2354 has_timeout = (timeout > 0);
2355 if (has_timeout)
2356 deadline = _PyTime_GetMonotonicClock() + timeout;
2357
2358 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002360 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 "The write operation timed out");
2362 goto error;
2363 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2364 PyErr_SetString(PySSLErrorObject,
2365 "Underlying socket has been closed.");
2366 goto error;
2367 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2368 PyErr_SetString(PySSLErrorObject,
2369 "Underlying socket too large for select().");
2370 goto error;
2371 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002375 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002376 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002378 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002379
2380 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002381 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002382
Victor Stinner14690702015-04-06 22:46:13 +02002383 if (has_timeout)
2384 timeout = deadline - _PyTime_GetMonotonicClock();
2385
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002386 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002387 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002388 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002389 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 } else {
2391 sockstate = SOCKET_OPERATION_OK;
2392 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002393
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002394 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002395 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002396 "The write operation timed out");
2397 goto error;
2398 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2399 PyErr_SetString(PySSLErrorObject,
2400 "Underlying socket has been closed.");
2401 goto error;
2402 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2403 break;
2404 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002405 } while (err.ssl == SSL_ERROR_WANT_READ ||
2406 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002407
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002408 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002409 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002411 if (PySSL_ChainExceptions(self) < 0)
2412 return NULL;
2413 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002414error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002415 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002416 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002418}
2419
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002420/*[clinic input]
2421_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002422
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002423Returns the number of already decrypted bytes available for read, pending on the connection.
2424[clinic start generated code]*/
2425
2426static PyObject *
2427_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2428/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002429{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002431 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 PySSL_BEGIN_ALLOW_THREADS
2434 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002435 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002437 self->err = err;
2438
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 if (count < 0)
2440 return PySSL_SetError(self, count, __FILE__, __LINE__);
2441 else
2442 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002443}
2444
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002445/*[clinic input]
2446_ssl._SSLSocket.read
2447 size as len: int
2448 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002449 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002450 ]
2451 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002452
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002453Read up to size bytes from the SSL socket.
2454[clinic start generated code]*/
2455
2456static PyObject *
2457_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2458 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002459/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002460{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002462 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002463 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002464 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002465 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002467 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002468 _PyTime_t timeout, deadline = 0;
2469 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002470
Martin Panter5503d472016-03-27 05:35:19 +00002471 if (!group_right_1 && len < 0) {
2472 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2473 return NULL;
2474 }
2475
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002476 if (sock != NULL) {
2477 if (((PyObject*)sock) == Py_None) {
2478 _setSSLError("Underlying socket connection gone",
2479 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2480 return NULL;
2481 }
2482 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002483 }
2484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002485 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002486 dest = PyBytes_FromStringAndSize(NULL, len);
2487 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002488 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002489 if (len == 0) {
2490 Py_XDECREF(sock);
2491 return dest;
2492 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002493 mem = PyBytes_AS_STRING(dest);
2494 }
2495 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002496 mem = buffer->buf;
2497 if (len <= 0 || len > buffer->len) {
2498 len = (int) buffer->len;
2499 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002500 PyErr_SetString(PyExc_OverflowError,
2501 "maximum length can't fit in a C 'int'");
2502 goto error;
2503 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002504 if (len == 0) {
2505 count = 0;
2506 goto done;
2507 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002508 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 }
2510
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002511 if (sock != NULL) {
2512 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002513 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002514 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2515 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2516 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517
Victor Stinner14690702015-04-06 22:46:13 +02002518 timeout = GET_SOCKET_TIMEOUT(sock);
2519 has_timeout = (timeout > 0);
2520 if (has_timeout)
2521 deadline = _PyTime_GetMonotonicClock() + timeout;
2522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 PySSL_BEGIN_ALLOW_THREADS
2525 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002526 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002528 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002529
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002530 if (PyErr_CheckSignals())
2531 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002532
Victor Stinner14690702015-04-06 22:46:13 +02002533 if (has_timeout)
2534 timeout = deadline - _PyTime_GetMonotonicClock();
2535
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002536 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002537 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002538 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002539 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002540 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002541 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 {
2543 count = 0;
2544 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002546 else
2547 sockstate = SOCKET_OPERATION_OK;
2548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002549 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002550 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002551 "The read operation timed out");
2552 goto error;
2553 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2554 break;
2555 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002556 } while (err.ssl == SSL_ERROR_WANT_READ ||
2557 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 if (count <= 0) {
2560 PySSL_SetError(self, count, __FILE__, __LINE__);
2561 goto error;
2562 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002563 if (self->exc_type != NULL)
2564 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002565
2566done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002567 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002568 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002569 _PyBytes_Resize(&dest, count);
2570 return dest;
2571 }
2572 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 return PyLong_FromLong(count);
2574 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002575
2576error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002577 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002578 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002579 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002580 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002582}
2583
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002584/*[clinic input]
2585_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002586
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002587Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002588[clinic start generated code]*/
2589
2590static PyObject *
2591_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002592/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002593{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002594 _PySSLError err;
2595 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002596 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002597 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002598 _PyTime_t timeout, deadline = 0;
2599 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002600
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002601 if (sock != NULL) {
2602 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002603 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002604 _setSSLError("Underlying socket connection gone",
2605 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2606 return NULL;
2607 }
2608 Py_INCREF(sock);
2609
2610 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002611 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002612 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2613 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002614 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002615
Victor Stinner14690702015-04-06 22:46:13 +02002616 timeout = GET_SOCKET_TIMEOUT(sock);
2617 has_timeout = (timeout > 0);
2618 if (has_timeout)
2619 deadline = _PyTime_GetMonotonicClock() + timeout;
2620
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002621 while (1) {
2622 PySSL_BEGIN_ALLOW_THREADS
2623 /* Disable read-ahead so that unwrap can work correctly.
2624 * Otherwise OpenSSL might read in too much data,
2625 * eating clear text data that happens to be
2626 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002627 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002628 * function is used and the shutdown_seen_zero != 0
2629 * condition is met.
2630 */
2631 if (self->shutdown_seen_zero)
2632 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002633 ret = SSL_shutdown(self->ssl);
2634 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002636 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002638 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002639 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002640 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002641 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002642 /* Don't loop endlessly; instead preserve legacy
2643 behaviour of trying SSL_shutdown() only twice.
2644 This looks necessary for OpenSSL < 0.9.8m */
2645 if (++zeros > 1)
2646 break;
2647 /* Shutdown was sent, now try receiving */
2648 self->shutdown_seen_zero = 1;
2649 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002650 }
2651
Victor Stinner14690702015-04-06 22:46:13 +02002652 if (has_timeout)
2653 timeout = deadline - _PyTime_GetMonotonicClock();
2654
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002655 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002656 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002657 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002658 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002659 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002660 else
2661 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002663 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002664 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002665 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002666 "The read operation timed out");
2667 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002668 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002669 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002670 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002671 }
2672 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2673 PyErr_SetString(PySSLErrorObject,
2674 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002675 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002676 }
2677 else if (sockstate != SOCKET_OPERATION_OK)
2678 /* Retain the SSL error code */
2679 break;
2680 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002681 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002682 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002683 PySSL_SetError(self, ret, __FILE__, __LINE__);
2684 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002685 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002686 if (self->exc_type != NULL)
2687 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002688 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002689 /* It's already INCREF'ed */
2690 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002691 else
2692 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002693
2694error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002695 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002696 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002697 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002698}
2699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002700/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002701_ssl._SSLSocket.get_channel_binding
2702 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002703
Christian Heimes141c5e82018-02-24 21:10:57 +01002704Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002705
Christian Heimes141c5e82018-02-24 21:10:57 +01002706Raise ValueError if the requested `cb_type` is not supported. Return bytes
2707of the data or None if the data is not available (e.g. before the handshake).
2708Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002709[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002710
Antoine Pitroud6494802011-07-21 01:11:30 +02002711static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002712_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2713 const char *cb_type)
2714/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002715{
Antoine Pitroud6494802011-07-21 01:11:30 +02002716 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002717 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002718
Christian Heimes141c5e82018-02-24 21:10:57 +01002719 if (strcmp(cb_type, "tls-unique") == 0) {
2720 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2721 /* if session is resumed XOR we are the client */
2722 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2723 }
2724 else {
2725 /* if a new session XOR we are the server */
2726 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2727 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002728 }
2729 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002730 PyErr_Format(
2731 PyExc_ValueError,
2732 "'%s' channel binding type not implemented",
2733 cb_type
2734 );
2735 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002736 }
2737
2738 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002739 if (len == 0)
2740 Py_RETURN_NONE;
2741
Christian Heimes141c5e82018-02-24 21:10:57 +01002742 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002743}
2744
Christian Heimes9fb051f2018-09-23 08:32:31 +02002745/*[clinic input]
2746_ssl._SSLSocket.verify_client_post_handshake
2747
2748Initiate TLS 1.3 post-handshake authentication
2749[clinic start generated code]*/
2750
2751static PyObject *
2752_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2753/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2754{
2755#ifdef TLS1_3_VERSION
2756 int err = SSL_verify_client_post_handshake(self->ssl);
2757 if (err == 0)
2758 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2759 else
2760 Py_RETURN_NONE;
2761#else
2762 PyErr_SetString(PyExc_NotImplementedError,
2763 "Post-handshake auth is not supported by your "
2764 "OpenSSL version.");
2765 return NULL;
2766#endif
2767}
2768
Christian Heimes99a65702016-09-10 23:44:53 +02002769#ifdef OPENSSL_VERSION_1_1
2770
2771static SSL_SESSION*
2772_ssl_session_dup(SSL_SESSION *session) {
2773 SSL_SESSION *newsession = NULL;
2774 int slen;
2775 unsigned char *senc = NULL, *p;
2776 const unsigned char *const_p;
2777
2778 if (session == NULL) {
2779 PyErr_SetString(PyExc_ValueError, "Invalid session");
2780 goto error;
2781 }
2782
2783 /* get length */
2784 slen = i2d_SSL_SESSION(session, NULL);
2785 if (slen == 0 || slen > 0xFF00) {
2786 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2787 goto error;
2788 }
2789 if ((senc = PyMem_Malloc(slen)) == NULL) {
2790 PyErr_NoMemory();
2791 goto error;
2792 }
2793 p = senc;
2794 if (!i2d_SSL_SESSION(session, &p)) {
2795 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2796 goto error;
2797 }
2798 const_p = senc;
2799 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2800 if (session == NULL) {
2801 goto error;
2802 }
2803 PyMem_Free(senc);
2804 return newsession;
2805 error:
2806 if (senc != NULL) {
2807 PyMem_Free(senc);
2808 }
2809 return NULL;
2810}
2811#endif
2812
2813static PyObject *
2814PySSL_get_session(PySSLSocket *self, void *closure) {
2815 /* get_session can return sessions from a server-side connection,
2816 * it does not check for handshake done or client socket. */
2817 PySSLSession *pysess;
2818 SSL_SESSION *session;
2819
2820#ifdef OPENSSL_VERSION_1_1
2821 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2822 * https://github.com/openssl/openssl/issues/1550 */
2823 session = SSL_get0_session(self->ssl); /* borrowed reference */
2824 if (session == NULL) {
2825 Py_RETURN_NONE;
2826 }
2827 if ((session = _ssl_session_dup(session)) == NULL) {
2828 return NULL;
2829 }
2830#else
2831 session = SSL_get1_session(self->ssl);
2832 if (session == NULL) {
2833 Py_RETURN_NONE;
2834 }
2835#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002836 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002837 if (pysess == NULL) {
2838 SSL_SESSION_free(session);
2839 return NULL;
2840 }
2841
2842 assert(self->ctx);
2843 pysess->ctx = self->ctx;
2844 Py_INCREF(pysess->ctx);
2845 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002846 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002847 return (PyObject *)pysess;
2848}
2849
2850static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2851 void *closure)
2852 {
2853 PySSLSession *pysess;
2854#ifdef OPENSSL_VERSION_1_1
2855 SSL_SESSION *session;
2856#endif
2857 int result;
2858
2859 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002860 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002861 return -1;
2862 }
2863 pysess = (PySSLSession *)value;
2864
2865 if (self->ctx->ctx != pysess->ctx->ctx) {
2866 PyErr_SetString(PyExc_ValueError,
2867 "Session refers to a different SSLContext.");
2868 return -1;
2869 }
2870 if (self->socket_type != PY_SSL_CLIENT) {
2871 PyErr_SetString(PyExc_ValueError,
2872 "Cannot set session for server-side SSLSocket.");
2873 return -1;
2874 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002875 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002876 PyErr_SetString(PyExc_ValueError,
2877 "Cannot set session after handshake.");
2878 return -1;
2879 }
2880#ifdef OPENSSL_VERSION_1_1
2881 /* duplicate session */
2882 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2883 return -1;
2884 }
2885 result = SSL_set_session(self->ssl, session);
2886 /* free duplicate, SSL_set_session() bumps ref count */
2887 SSL_SESSION_free(session);
2888#else
2889 result = SSL_set_session(self->ssl, pysess->session);
2890#endif
2891 if (result == 0) {
2892 _setSSLError(NULL, 0, __FILE__, __LINE__);
2893 return -1;
2894 }
2895 return 0;
2896}
2897
2898PyDoc_STRVAR(PySSL_set_session_doc,
2899"_setter_session(session)\n\
2900\
2901Get / set SSLSession.");
2902
2903static PyObject *
2904PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2905 if (SSL_session_reused(self->ssl)) {
2906 Py_RETURN_TRUE;
2907 } else {
2908 Py_RETURN_FALSE;
2909 }
2910}
2911
2912PyDoc_STRVAR(PySSL_get_session_reused_doc,
2913"Was the client session reused during handshake?");
2914
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002915static PyGetSetDef ssl_getsetlist[] = {
2916 {"context", (getter) PySSL_get_context,
2917 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002918 {"server_side", (getter) PySSL_get_server_side, NULL,
2919 PySSL_get_server_side_doc},
2920 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2921 PySSL_get_server_hostname_doc},
2922 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2923 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002924 {"session", (getter) PySSL_get_session,
2925 (setter) PySSL_set_session, PySSL_set_session_doc},
2926 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2927 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002928 {NULL}, /* sentinel */
2929};
2930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002931static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002932 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2933 _SSL__SSLSOCKET_WRITE_METHODDEF
2934 _SSL__SSLSOCKET_READ_METHODDEF
2935 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002936 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2937 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002938 _SSL__SSLSOCKET_CIPHER_METHODDEF
2939 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2940 _SSL__SSLSOCKET_VERSION_METHODDEF
2941 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2942 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2943 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2944 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002945 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002946 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002947};
2948
Antoine Pitrou152efa22010-05-16 18:19:27 +00002949static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002950 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002951 "_ssl._SSLSocket", /*tp_name*/
2952 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002953 0, /*tp_itemsize*/
2954 /* methods */
2955 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002956 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002957 0, /*tp_getattr*/
2958 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002959 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002960 0, /*tp_repr*/
2961 0, /*tp_as_number*/
2962 0, /*tp_as_sequence*/
2963 0, /*tp_as_mapping*/
2964 0, /*tp_hash*/
2965 0, /*tp_call*/
2966 0, /*tp_str*/
2967 0, /*tp_getattro*/
2968 0, /*tp_setattro*/
2969 0, /*tp_as_buffer*/
2970 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2971 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02002972 (traverseproc) PySSL_traverse, /*tp_traverse*/
2973 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002974 0, /*tp_richcompare*/
2975 0, /*tp_weaklistoffset*/
2976 0, /*tp_iter*/
2977 0, /*tp_iternext*/
2978 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002979 0, /*tp_members*/
2980 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002981};
2982
Antoine Pitrou152efa22010-05-16 18:19:27 +00002983
2984/*
2985 * _SSLContext objects
2986 */
2987
Christian Heimes5fe668c2016-09-12 00:01:11 +02002988static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002989_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002990{
2991 int mode;
2992 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2993
2994 switch(n) {
2995 case PY_SSL_CERT_NONE:
2996 mode = SSL_VERIFY_NONE;
2997 break;
2998 case PY_SSL_CERT_OPTIONAL:
2999 mode = SSL_VERIFY_PEER;
3000 break;
3001 case PY_SSL_CERT_REQUIRED:
3002 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
3003 break;
3004 default:
3005 PyErr_SetString(PyExc_ValueError,
3006 "invalid value for verify_mode");
3007 return -1;
3008 }
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003009
3010 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3011 * server sockets and SSL_set_post_handshake_auth() for client. */
3012
Christian Heimes5fe668c2016-09-12 00:01:11 +02003013 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003014 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3015 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02003016 return 0;
3017}
3018
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003019/*[clinic input]
3020@classmethod
3021_ssl._SSLContext.__new__
3022 protocol as proto_version: int
3023 /
3024[clinic start generated code]*/
3025
Antoine Pitrou152efa22010-05-16 18:19:27 +00003026static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003027_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3028/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003029{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003031 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003032 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003033 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003034 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003035#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003036 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003037#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003038
Antoine Pitrou152efa22010-05-16 18:19:27 +00003039 PySSL_BEGIN_ALLOW_THREADS
3040 if (proto_version == PY_SSL_VERSION_TLS1)
3041 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003042#if HAVE_TLSv1_2
3043 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3044 ctx = SSL_CTX_new(TLSv1_1_method());
3045 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3046 ctx = SSL_CTX_new(TLSv1_2_method());
3047#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003048#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003049 else if (proto_version == PY_SSL_VERSION_SSL3)
3050 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003051#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003052#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003053 else if (proto_version == PY_SSL_VERSION_SSL2)
3054 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003055#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003056 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003057 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003058 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3059 ctx = SSL_CTX_new(TLS_client_method());
3060 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3061 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003062 else
3063 proto_version = -1;
3064 PySSL_END_ALLOW_THREADS
3065
3066 if (proto_version == -1) {
3067 PyErr_SetString(PyExc_ValueError,
3068 "invalid protocol version");
3069 return NULL;
3070 }
3071 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003072 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003073 return NULL;
3074 }
3075
3076 assert(type != NULL && type->tp_alloc != NULL);
3077 self = (PySSLContext *) type->tp_alloc(type, 0);
3078 if (self == NULL) {
3079 SSL_CTX_free(ctx);
3080 return NULL;
3081 }
3082 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003083 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003084 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003085 self->msg_cb = NULL;
3086#ifdef HAVE_OPENSSL_KEYLOG
3087 self->keylog_filename = NULL;
3088 self->keylog_bio = NULL;
3089#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003090#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003091 self->npn_protocols = NULL;
3092#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003093#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003094 self->alpn_protocols = NULL;
3095#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003096#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003097 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003098#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003099 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003100 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3101 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003102 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003103 Py_DECREF(self);
3104 return NULL;
3105 }
3106 } else {
3107 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003108 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003109 Py_DECREF(self);
3110 return NULL;
3111 }
3112 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003113 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003114 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3115 if (proto_version != PY_SSL_VERSION_SSL2)
3116 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003117 if (proto_version != PY_SSL_VERSION_SSL3)
3118 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003119 /* Minimal security flags for server and client side context.
3120 * Client sockets ignore server-side parameters. */
3121#ifdef SSL_OP_NO_COMPRESSION
3122 options |= SSL_OP_NO_COMPRESSION;
3123#endif
3124#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3125 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3126#endif
3127#ifdef SSL_OP_SINGLE_DH_USE
3128 options |= SSL_OP_SINGLE_DH_USE;
3129#endif
3130#ifdef SSL_OP_SINGLE_ECDH_USE
3131 options |= SSL_OP_SINGLE_ECDH_USE;
3132#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003133 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003134
Semen Zhydenko1295e112017-10-15 21:28:31 +02003135 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003136 * It's far from perfect but gives users a better head start. */
3137 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003138#if PY_SSL_DEFAULT_CIPHERS == 2
3139 /* stick to OpenSSL's default settings */
3140 result = 1;
3141#else
3142 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3143#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003144 } else {
3145 /* SSLv2 needs MD5 */
3146 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3147 }
3148 if (result == 0) {
3149 Py_DECREF(self);
3150 ERR_clear_error();
3151 PyErr_SetString(PySSLErrorObject,
3152 "No cipher can be selected.");
3153 return NULL;
3154 }
3155
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003156#if defined(SSL_MODE_RELEASE_BUFFERS)
3157 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3158 usage for no cost at all. However, don't do this for OpenSSL versions
3159 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3160 2014-0198. I can't find exactly which beta fixed this CVE, so be
3161 conservative and assume it wasn't fixed until release. We do this check
3162 at runtime to avoid problems from the dynamic linker.
3163 See #25672 for more on this. */
3164 libver = SSLeay();
3165 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3166 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3167 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3168 }
3169#endif
3170
3171
Donald Stufft8ae264c2017-03-02 11:45:29 -05003172#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003173 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3174 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003175 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3176 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003177#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003178 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3179#else
3180 {
3181 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3182 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3183 EC_KEY_free(key);
3184 }
3185#endif
3186#endif
3187
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003188#define SID_CTX "Python"
3189 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3190 sizeof(SID_CTX));
3191#undef SID_CTX
3192
Christian Heimes61d478c2018-01-27 15:51:38 +01003193 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003194#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003195 /* Improve trust chain building when cross-signed intermediate
3196 certificates are present. See https://bugs.python.org/issue23476. */
3197 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003198#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003199 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003200
Christian Heimes9fb051f2018-09-23 08:32:31 +02003201#ifdef TLS1_3_VERSION
3202 self->post_handshake_auth = 0;
3203 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3204#endif
3205
Antoine Pitrou152efa22010-05-16 18:19:27 +00003206 return (PyObject *)self;
3207}
3208
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003209static int
3210context_traverse(PySSLContext *self, visitproc visit, void *arg)
3211{
3212#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003213 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003214#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003215 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003216 return 0;
3217}
3218
3219static int
3220context_clear(PySSLContext *self)
3221{
3222#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003223 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003224#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003225 Py_CLEAR(self->msg_cb);
3226#ifdef HAVE_OPENSSL_KEYLOG
3227 Py_CLEAR(self->keylog_filename);
3228 if (self->keylog_bio != NULL) {
3229 PySSL_BEGIN_ALLOW_THREADS
3230 BIO_free_all(self->keylog_bio);
3231 PySSL_END_ALLOW_THREADS
3232 self->keylog_bio = NULL;
3233 }
3234#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003235 return 0;
3236}
3237
Antoine Pitrou152efa22010-05-16 18:19:27 +00003238static void
3239context_dealloc(PySSLContext *self)
3240{
INADA Naokia6296d32017-08-24 14:55:17 +09003241 /* bpo-31095: UnTrack is needed before calling any callbacks */
3242 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003243 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003244 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003245#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003246 PyMem_FREE(self->npn_protocols);
3247#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003248#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003249 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003250#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003251 Py_TYPE(self)->tp_free(self);
3252}
3253
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003254/*[clinic input]
3255_ssl._SSLContext.set_ciphers
3256 cipherlist: str
3257 /
3258[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003259
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003260static PyObject *
3261_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3262/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3263{
3264 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003265 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003266 /* Clearing the error queue is necessary on some OpenSSL versions,
3267 otherwise the error will be reported again when another SSL call
3268 is done. */
3269 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003270 PyErr_SetString(PySSLErrorObject,
3271 "No cipher can be selected.");
3272 return NULL;
3273 }
3274 Py_RETURN_NONE;
3275}
3276
Christian Heimes25bfcd52016-09-06 00:04:45 +02003277#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3278/*[clinic input]
3279_ssl._SSLContext.get_ciphers
3280[clinic start generated code]*/
3281
3282static PyObject *
3283_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3284/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3285{
3286 SSL *ssl = NULL;
3287 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003288 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003289 int i=0;
3290 PyObject *result = NULL, *dct;
3291
3292 ssl = SSL_new(self->ctx);
3293 if (ssl == NULL) {
3294 _setSSLError(NULL, 0, __FILE__, __LINE__);
3295 goto exit;
3296 }
3297 sk = SSL_get_ciphers(ssl);
3298
3299 result = PyList_New(sk_SSL_CIPHER_num(sk));
3300 if (result == NULL) {
3301 goto exit;
3302 }
3303
3304 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3305 cipher = sk_SSL_CIPHER_value(sk, i);
3306 dct = cipher_to_dict(cipher);
3307 if (dct == NULL) {
3308 Py_CLEAR(result);
3309 goto exit;
3310 }
3311 PyList_SET_ITEM(result, i, dct);
3312 }
3313
3314 exit:
3315 if (ssl != NULL)
3316 SSL_free(ssl);
3317 return result;
3318
3319}
3320#endif
3321
3322
Christian Heimes29eab552018-02-25 12:31:33 +01003323#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003324static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003325do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3326 const unsigned char *server_protocols, unsigned int server_protocols_len,
3327 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003328{
Benjamin Peterson88615022015-01-23 17:30:26 -05003329 int ret;
3330 if (client_protocols == NULL) {
3331 client_protocols = (unsigned char *)"";
3332 client_protocols_len = 0;
3333 }
3334 if (server_protocols == NULL) {
3335 server_protocols = (unsigned char *)"";
3336 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003337 }
3338
Benjamin Peterson88615022015-01-23 17:30:26 -05003339 ret = SSL_select_next_proto(out, outlen,
3340 server_protocols, server_protocols_len,
3341 client_protocols, client_protocols_len);
3342 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3343 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003344
3345 return SSL_TLSEXT_ERR_OK;
3346}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003347#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003348
Christian Heimes29eab552018-02-25 12:31:33 +01003349#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003350/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3351static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003352_advertiseNPN_cb(SSL *s,
3353 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003354 void *args)
3355{
3356 PySSLContext *ssl_ctx = (PySSLContext *) args;
3357
3358 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003359 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003360 *len = 0;
3361 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003362 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003363 *len = ssl_ctx->npn_protocols_len;
3364 }
3365
3366 return SSL_TLSEXT_ERR_OK;
3367}
3368/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3369static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003370_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003371 unsigned char **out, unsigned char *outlen,
3372 const unsigned char *server, unsigned int server_len,
3373 void *args)
3374{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003375 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003376 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003377 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003378}
3379#endif
3380
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003381/*[clinic input]
3382_ssl._SSLContext._set_npn_protocols
3383 protos: Py_buffer
3384 /
3385[clinic start generated code]*/
3386
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003387static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003388_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3389 Py_buffer *protos)
3390/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003391{
Christian Heimes29eab552018-02-25 12:31:33 +01003392#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003393 PyMem_Free(self->npn_protocols);
3394 self->npn_protocols = PyMem_Malloc(protos->len);
3395 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003396 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003397 memcpy(self->npn_protocols, protos->buf, protos->len);
3398 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003399
3400 /* set both server and client callbacks, because the context can
3401 * be used to create both types of sockets */
3402 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3403 _advertiseNPN_cb,
3404 self);
3405 SSL_CTX_set_next_proto_select_cb(self->ctx,
3406 _selectNPN_cb,
3407 self);
3408
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003409 Py_RETURN_NONE;
3410#else
3411 PyErr_SetString(PyExc_NotImplementedError,
3412 "The NPN extension requires OpenSSL 1.0.1 or later.");
3413 return NULL;
3414#endif
3415}
3416
Christian Heimes29eab552018-02-25 12:31:33 +01003417#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003418static int
3419_selectALPN_cb(SSL *s,
3420 const unsigned char **out, unsigned char *outlen,
3421 const unsigned char *client_protocols, unsigned int client_protocols_len,
3422 void *args)
3423{
3424 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003425 return do_protocol_selection(1, (unsigned char **)out, outlen,
3426 ctx->alpn_protocols, ctx->alpn_protocols_len,
3427 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003428}
3429#endif
3430
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003431/*[clinic input]
3432_ssl._SSLContext._set_alpn_protocols
3433 protos: Py_buffer
3434 /
3435[clinic start generated code]*/
3436
Benjamin Petersoncca27322015-01-23 16:35:37 -05003437static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003438_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3439 Py_buffer *protos)
3440/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003441{
Christian Heimes29eab552018-02-25 12:31:33 +01003442#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003443 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003444 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003445 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003446 return NULL;
3447 }
3448
Benjamin Petersoncca27322015-01-23 16:35:37 -05003449 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003450 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003451 if (!self->alpn_protocols)
3452 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003453 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003454 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003455
3456 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3457 return PyErr_NoMemory();
3458 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3459
Benjamin Petersoncca27322015-01-23 16:35:37 -05003460 Py_RETURN_NONE;
3461#else
3462 PyErr_SetString(PyExc_NotImplementedError,
3463 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3464 return NULL;
3465#endif
3466}
3467
Antoine Pitrou152efa22010-05-16 18:19:27 +00003468static PyObject *
3469get_verify_mode(PySSLContext *self, void *c)
3470{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003471 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3472 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3473 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3474 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003475 case SSL_VERIFY_NONE:
3476 return PyLong_FromLong(PY_SSL_CERT_NONE);
3477 case SSL_VERIFY_PEER:
3478 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3479 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3480 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3481 }
3482 PyErr_SetString(PySSLErrorObject,
3483 "invalid return value from SSL_CTX_get_verify_mode");
3484 return NULL;
3485}
3486
3487static int
3488set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3489{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003490 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003491 if (!PyArg_Parse(arg, "i", &n))
3492 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003493 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003494 PyErr_SetString(PyExc_ValueError,
3495 "Cannot set verify_mode to CERT_NONE when "
3496 "check_hostname is enabled.");
3497 return -1;
3498 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003499 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003500}
3501
3502static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003503get_verify_flags(PySSLContext *self, void *c)
3504{
Christian Heimes598894f2016-09-05 23:19:05 +02003505 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003506 unsigned long flags;
3507
Christian Heimes61d478c2018-01-27 15:51:38 +01003508 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003509 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003510 return PyLong_FromUnsignedLong(flags);
3511}
3512
3513static int
3514set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3515{
Christian Heimes598894f2016-09-05 23:19:05 +02003516 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003517 unsigned long new_flags, flags, set, clear;
3518
3519 if (!PyArg_Parse(arg, "k", &new_flags))
3520 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003521 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003522 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003523 clear = flags & ~new_flags;
3524 set = ~flags & new_flags;
3525 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003526 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003527 _setSSLError(NULL, 0, __FILE__, __LINE__);
3528 return -1;
3529 }
3530 }
3531 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003532 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003533 _setSSLError(NULL, 0, __FILE__, __LINE__);
3534 return -1;
3535 }
3536 }
3537 return 0;
3538}
3539
Christian Heimes698dde12018-02-27 11:54:43 +01003540/* Getter and setter for protocol version */
3541#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3542
3543
3544static int
3545set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3546{
3547 long v;
3548 int result;
3549
3550 if (!PyArg_Parse(arg, "l", &v))
3551 return -1;
3552 if (v > INT_MAX) {
3553 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3554 return -1;
3555 }
3556
3557 switch(self->protocol) {
3558 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3559 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3560 case PY_SSL_VERSION_TLS:
3561 break;
3562 default:
3563 PyErr_SetString(
3564 PyExc_ValueError,
3565 "The context's protocol doesn't support modification of "
3566 "highest and lowest version."
3567 );
3568 return -1;
3569 }
3570
3571 if (what == 0) {
3572 switch(v) {
3573 case PY_PROTO_MINIMUM_SUPPORTED:
3574 v = 0;
3575 break;
3576 case PY_PROTO_MAXIMUM_SUPPORTED:
3577 /* Emulate max for set_min_proto_version */
3578 v = PY_PROTO_MAXIMUM_AVAILABLE;
3579 break;
3580 default:
3581 break;
3582 }
3583 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3584 }
3585 else {
3586 switch(v) {
3587 case PY_PROTO_MAXIMUM_SUPPORTED:
3588 v = 0;
3589 break;
3590 case PY_PROTO_MINIMUM_SUPPORTED:
3591 /* Emulate max for set_min_proto_version */
3592 v = PY_PROTO_MINIMUM_AVAILABLE;
3593 break;
3594 default:
3595 break;
3596 }
3597 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3598 }
3599 if (result == 0) {
3600 PyErr_Format(PyExc_ValueError,
3601 "Unsupported protocol version 0x%x", v);
3602 return -1;
3603 }
3604 return 0;
3605}
3606
3607static PyObject *
3608get_minimum_version(PySSLContext *self, void *c)
3609{
3610 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3611 if (v == 0) {
3612 v = PY_PROTO_MINIMUM_SUPPORTED;
3613 }
3614 return PyLong_FromLong(v);
3615}
3616
3617static int
3618set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3619{
3620 return set_min_max_proto_version(self, arg, 0);
3621}
3622
3623static PyObject *
3624get_maximum_version(PySSLContext *self, void *c)
3625{
3626 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3627 if (v == 0) {
3628 v = PY_PROTO_MAXIMUM_SUPPORTED;
3629 }
3630 return PyLong_FromLong(v);
3631}
3632
3633static int
3634set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3635{
3636 return set_min_max_proto_version(self, arg, 1);
3637}
3638#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3639
Christian Heimes78c7d522019-06-03 21:00:10 +02003640#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3641static PyObject *
3642get_num_tickets(PySSLContext *self, void *c)
3643{
Miss Islington (bot)bbad6952019-07-09 05:42:49 -07003644 return PyLong_FromSize_t(SSL_CTX_get_num_tickets(self->ctx));
Christian Heimes78c7d522019-06-03 21:00:10 +02003645}
3646
3647static int
3648set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3649{
3650 long num;
3651 if (!PyArg_Parse(arg, "l", &num))
3652 return -1;
3653 if (num < 0) {
3654 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3655 return -1;
3656 }
3657 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3658 PyErr_SetString(PyExc_ValueError,
3659 "SSLContext is not a server context.");
3660 return -1;
3661 }
3662 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3663 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3664 return -1;
3665 }
3666 return 0;
3667}
3668
3669PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3670"Control the number of TLSv1.3 session tickets");
3671#endif /* OpenSSL 1.1.1 */
3672
Christian Heimes22587792013-11-21 23:56:13 +01003673static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003674get_options(PySSLContext *self, void *c)
3675{
3676 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3677}
3678
3679static int
3680set_options(PySSLContext *self, PyObject *arg, void *c)
3681{
3682 long new_opts, opts, set, clear;
3683 if (!PyArg_Parse(arg, "l", &new_opts))
3684 return -1;
3685 opts = SSL_CTX_get_options(self->ctx);
3686 clear = opts & ~new_opts;
3687 set = ~opts & new_opts;
3688 if (clear) {
3689#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3690 SSL_CTX_clear_options(self->ctx, clear);
3691#else
3692 PyErr_SetString(PyExc_ValueError,
3693 "can't clear options before OpenSSL 0.9.8m");
3694 return -1;
3695#endif
3696 }
3697 if (set)
3698 SSL_CTX_set_options(self->ctx, set);
3699 return 0;
3700}
3701
Christian Heimes1aa9a752013-12-02 02:41:19 +01003702static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003703get_host_flags(PySSLContext *self, void *c)
3704{
3705 return PyLong_FromUnsignedLong(self->hostflags);
3706}
3707
3708static int
3709set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3710{
3711 X509_VERIFY_PARAM *param;
3712 unsigned int new_flags = 0;
3713
3714 if (!PyArg_Parse(arg, "I", &new_flags))
3715 return -1;
3716
3717 param = SSL_CTX_get0_param(self->ctx);
3718 self->hostflags = new_flags;
3719 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3720 return 0;
3721}
3722
3723static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003724get_check_hostname(PySSLContext *self, void *c)
3725{
3726 return PyBool_FromLong(self->check_hostname);
3727}
3728
3729static int
3730set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3731{
3732 int check_hostname;
3733 if (!PyArg_Parse(arg, "p", &check_hostname))
3734 return -1;
3735 if (check_hostname &&
3736 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003737 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003738 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003739 return -1;
3740 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003741 }
3742 self->check_hostname = check_hostname;
3743 return 0;
3744}
3745
Christian Heimes11a14932018-02-24 02:35:08 +01003746static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003747get_post_handshake_auth(PySSLContext *self, void *c) {
3748#if TLS1_3_VERSION
3749 return PyBool_FromLong(self->post_handshake_auth);
3750#else
3751 Py_RETURN_NONE;
3752#endif
3753}
3754
3755#if TLS1_3_VERSION
3756static int
3757set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
Zackery Spytz842acaa2018-12-17 07:52:45 -07003758 if (arg == NULL) {
3759 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3760 return -1;
3761 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003762 int pha = PyObject_IsTrue(arg);
3763
3764 if (pha == -1) {
3765 return -1;
3766 }
3767 self->post_handshake_auth = pha;
3768
Christian Heimesf22c4cf2019-07-01 09:25:48 +02003769 /* bpo-37428: newPySSLSocket() sets SSL_VERIFY_POST_HANDSHAKE flag for
3770 * server sockets and SSL_set_post_handshake_auth() for client. */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003771
3772 return 0;
3773}
3774#endif
3775
3776static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003777get_protocol(PySSLContext *self, void *c) {
3778 return PyLong_FromLong(self->protocol);
3779}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003780
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003781typedef struct {
3782 PyThreadState *thread_state;
3783 PyObject *callable;
3784 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003785 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003786 int error;
3787} _PySSLPasswordInfo;
3788
3789static int
3790_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3791 const char *bad_type_error)
3792{
3793 /* Set the password and size fields of a _PySSLPasswordInfo struct
3794 from a unicode, bytes, or byte array object.
3795 The password field will be dynamically allocated and must be freed
3796 by the caller */
3797 PyObject *password_bytes = NULL;
3798 const char *data = NULL;
3799 Py_ssize_t size;
3800
3801 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003802 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003803 if (!password_bytes) {
3804 goto error;
3805 }
3806 data = PyBytes_AS_STRING(password_bytes);
3807 size = PyBytes_GET_SIZE(password_bytes);
3808 } else if (PyBytes_Check(password)) {
3809 data = PyBytes_AS_STRING(password);
3810 size = PyBytes_GET_SIZE(password);
3811 } else if (PyByteArray_Check(password)) {
3812 data = PyByteArray_AS_STRING(password);
3813 size = PyByteArray_GET_SIZE(password);
3814 } else {
3815 PyErr_SetString(PyExc_TypeError, bad_type_error);
3816 goto error;
3817 }
3818
Victor Stinner9ee02032013-06-23 15:08:23 +02003819 if (size > (Py_ssize_t)INT_MAX) {
3820 PyErr_Format(PyExc_ValueError,
3821 "password cannot be longer than %d bytes", INT_MAX);
3822 goto error;
3823 }
3824
Victor Stinner11ebff22013-07-07 17:07:52 +02003825 PyMem_Free(pw_info->password);
3826 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003827 if (!pw_info->password) {
3828 PyErr_SetString(PyExc_MemoryError,
3829 "unable to allocate password buffer");
3830 goto error;
3831 }
3832 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003833 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003834
3835 Py_XDECREF(password_bytes);
3836 return 1;
3837
3838error:
3839 Py_XDECREF(password_bytes);
3840 return 0;
3841}
3842
3843static int
3844_password_callback(char *buf, int size, int rwflag, void *userdata)
3845{
3846 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3847 PyObject *fn_ret = NULL;
3848
3849 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3850
3851 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003852 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003853 if (!fn_ret) {
3854 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3855 core python API, so we could use it to add a frame here */
3856 goto error;
3857 }
3858
3859 if (!_pwinfo_set(pw_info, fn_ret,
3860 "password callback must return a string")) {
3861 goto error;
3862 }
3863 Py_CLEAR(fn_ret);
3864 }
3865
3866 if (pw_info->size > size) {
3867 PyErr_Format(PyExc_ValueError,
3868 "password cannot be longer than %d bytes", size);
3869 goto error;
3870 }
3871
3872 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3873 memcpy(buf, pw_info->password, pw_info->size);
3874 return pw_info->size;
3875
3876error:
3877 Py_XDECREF(fn_ret);
3878 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3879 pw_info->error = 1;
3880 return -1;
3881}
3882
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003883/*[clinic input]
3884_ssl._SSLContext.load_cert_chain
3885 certfile: object
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003886 keyfile: object = None
3887 password: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003888
3889[clinic start generated code]*/
3890
Antoine Pitroub5218772010-05-21 09:56:06 +00003891static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003892_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3893 PyObject *keyfile, PyObject *password)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003894/*[clinic end generated code: output=9480bc1c380e2095 input=30bc7e967ea01a58]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003895{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003896 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003897 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3898 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003899 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003900 int r;
3901
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003902 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003903 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003904 if (keyfile == Py_None)
3905 keyfile = NULL;
3906 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003907 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3908 PyErr_SetString(PyExc_TypeError,
3909 "certfile should be a valid filesystem path");
3910 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003911 return NULL;
3912 }
3913 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003914 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3915 PyErr_SetString(PyExc_TypeError,
3916 "keyfile should be a valid filesystem path");
3917 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003918 goto error;
3919 }
Serhiy Storchakad322abb2019-09-14 13:31:50 +03003920 if (password != Py_None) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003921 if (PyCallable_Check(password)) {
3922 pw_info.callable = password;
3923 } else if (!_pwinfo_set(&pw_info, password,
3924 "password should be a string or callable")) {
3925 goto error;
3926 }
3927 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3928 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3929 }
3930 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003931 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3932 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003933 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003934 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003935 if (pw_info.error) {
3936 ERR_clear_error();
3937 /* the password callback has already set the error information */
3938 }
3939 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003940 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003941 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003942 }
3943 else {
3944 _setSSLError(NULL, 0, __FILE__, __LINE__);
3945 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003946 goto error;
3947 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003948 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003949 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003950 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3951 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003952 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3953 Py_CLEAR(keyfile_bytes);
3954 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003955 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003956 if (pw_info.error) {
3957 ERR_clear_error();
3958 /* the password callback has already set the error information */
3959 }
3960 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003961 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003962 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003963 }
3964 else {
3965 _setSSLError(NULL, 0, __FILE__, __LINE__);
3966 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003967 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003968 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003969 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003970 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003971 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003972 if (r != 1) {
3973 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003974 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003975 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003976 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3977 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003978 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003979 Py_RETURN_NONE;
3980
3981error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003982 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3983 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003984 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003985 Py_XDECREF(keyfile_bytes);
3986 Py_XDECREF(certfile_bytes);
3987 return NULL;
3988}
3989
Christian Heimesefff7062013-11-21 03:35:02 +01003990/* internal helper function, returns -1 on error
3991 */
3992static int
3993_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3994 int filetype)
3995{
3996 BIO *biobuf = NULL;
3997 X509_STORE *store;
3998 int retval = 0, err, loaded = 0;
3999
4000 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
4001
4002 if (len <= 0) {
4003 PyErr_SetString(PyExc_ValueError,
4004 "Empty certificate data");
4005 return -1;
4006 } else if (len > INT_MAX) {
4007 PyErr_SetString(PyExc_OverflowError,
4008 "Certificate data is too long.");
4009 return -1;
4010 }
4011
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004012 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004013 if (biobuf == NULL) {
4014 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4015 return -1;
4016 }
4017
4018 store = SSL_CTX_get_cert_store(self->ctx);
4019 assert(store != NULL);
4020
4021 while (1) {
4022 X509 *cert = NULL;
4023 int r;
4024
4025 if (filetype == SSL_FILETYPE_ASN1) {
4026 cert = d2i_X509_bio(biobuf, NULL);
4027 } else {
4028 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004029 SSL_CTX_get_default_passwd_cb(self->ctx),
4030 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4031 );
Christian Heimesefff7062013-11-21 03:35:02 +01004032 }
4033 if (cert == NULL) {
4034 break;
4035 }
4036 r = X509_STORE_add_cert(store, cert);
4037 X509_free(cert);
4038 if (!r) {
4039 err = ERR_peek_last_error();
4040 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4041 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4042 /* cert already in hash table, not an error */
4043 ERR_clear_error();
4044 } else {
4045 break;
4046 }
4047 }
4048 loaded++;
4049 }
4050
4051 err = ERR_peek_last_error();
4052 if ((filetype == SSL_FILETYPE_ASN1) &&
4053 (loaded > 0) &&
4054 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4055 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4056 /* EOF ASN1 file, not an error */
4057 ERR_clear_error();
4058 retval = 0;
4059 } else if ((filetype == SSL_FILETYPE_PEM) &&
4060 (loaded > 0) &&
4061 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4062 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4063 /* EOF PEM file, not an error */
4064 ERR_clear_error();
4065 retval = 0;
4066 } else {
4067 _setSSLError(NULL, 0, __FILE__, __LINE__);
4068 retval = -1;
4069 }
4070
4071 BIO_free(biobuf);
4072 return retval;
4073}
4074
4075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076/*[clinic input]
4077_ssl._SSLContext.load_verify_locations
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004078 cafile: object = None
4079 capath: object = None
4080 cadata: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004081
4082[clinic start generated code]*/
4083
Antoine Pitrou152efa22010-05-16 18:19:27 +00004084static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4086 PyObject *cafile,
4087 PyObject *capath,
4088 PyObject *cadata)
Serhiy Storchakad322abb2019-09-14 13:31:50 +03004089/*[clinic end generated code: output=454c7e41230ca551 input=42ecfe258233e194]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004090{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004091 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4092 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004093 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004094
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004095 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004096 if (cafile == Py_None)
4097 cafile = NULL;
4098 if (capath == Py_None)
4099 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004100 if (cadata == Py_None)
4101 cadata = NULL;
4102
4103 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004104 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004105 "cafile, capath and cadata cannot be all omitted");
4106 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004107 }
4108 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004109 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4110 PyErr_SetString(PyExc_TypeError,
4111 "cafile should be a valid filesystem path");
4112 }
Christian Heimesefff7062013-11-21 03:35:02 +01004113 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004114 }
4115 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004116 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4117 PyErr_SetString(PyExc_TypeError,
4118 "capath should be a valid filesystem path");
4119 }
Christian Heimesefff7062013-11-21 03:35:02 +01004120 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004121 }
Christian Heimesefff7062013-11-21 03:35:02 +01004122
4123 /* validata cadata type and load cadata */
4124 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004125 if (PyUnicode_Check(cadata)) {
4126 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4127 if (cadata_ascii == NULL) {
4128 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4129 goto invalid_cadata;
4130 }
4131 goto error;
4132 }
4133 r = _add_ca_certs(self,
4134 PyBytes_AS_STRING(cadata_ascii),
4135 PyBytes_GET_SIZE(cadata_ascii),
4136 SSL_FILETYPE_PEM);
4137 Py_DECREF(cadata_ascii);
4138 if (r == -1) {
4139 goto error;
4140 }
4141 }
4142 else if (PyObject_CheckBuffer(cadata)) {
4143 Py_buffer buf;
4144 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4145 goto error;
4146 }
Christian Heimesefff7062013-11-21 03:35:02 +01004147 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4148 PyBuffer_Release(&buf);
4149 PyErr_SetString(PyExc_TypeError,
4150 "cadata should be a contiguous buffer with "
4151 "a single dimension");
4152 goto error;
4153 }
4154 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4155 PyBuffer_Release(&buf);
4156 if (r == -1) {
4157 goto error;
4158 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004159 }
4160 else {
4161 invalid_cadata:
4162 PyErr_SetString(PyExc_TypeError,
4163 "cadata should be an ASCII string or a "
4164 "bytes-like object");
4165 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004166 }
4167 }
4168
4169 /* load cafile or capath */
4170 if (cafile || capath) {
4171 if (cafile)
4172 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4173 if (capath)
4174 capath_buf = PyBytes_AS_STRING(capath_bytes);
4175 PySSL_BEGIN_ALLOW_THREADS
4176 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4177 PySSL_END_ALLOW_THREADS
4178 if (r != 1) {
4179 ok = 0;
4180 if (errno != 0) {
4181 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004182 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004183 }
4184 else {
4185 _setSSLError(NULL, 0, __FILE__, __LINE__);
4186 }
4187 goto error;
4188 }
4189 }
4190 goto end;
4191
4192 error:
4193 ok = 0;
4194 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004195 Py_XDECREF(cafile_bytes);
4196 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004197 if (ok) {
4198 Py_RETURN_NONE;
4199 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004200 return NULL;
4201 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004202}
4203
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004204/*[clinic input]
4205_ssl._SSLContext.load_dh_params
4206 path as filepath: object
4207 /
4208
4209[clinic start generated code]*/
4210
Antoine Pitrou152efa22010-05-16 18:19:27 +00004211static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004212_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4213/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004214{
4215 FILE *f;
4216 DH *dh;
4217
Victor Stinnerdaf45552013-08-28 00:53:59 +02004218 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004219 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004220 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004221
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004222 errno = 0;
4223 PySSL_BEGIN_ALLOW_THREADS
4224 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004225 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004226 PySSL_END_ALLOW_THREADS
4227 if (dh == NULL) {
4228 if (errno != 0) {
4229 ERR_clear_error();
4230 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4231 }
4232 else {
4233 _setSSLError(NULL, 0, __FILE__, __LINE__);
4234 }
4235 return NULL;
4236 }
4237 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4238 _setSSLError(NULL, 0, __FILE__, __LINE__);
4239 DH_free(dh);
4240 Py_RETURN_NONE;
4241}
4242
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004243/*[clinic input]
4244_ssl._SSLContext._wrap_socket
4245 sock: object(subclass_of="PySocketModule.Sock_Type")
4246 server_side: int
4247 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004248 *
4249 owner: object = None
4250 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004251
4252[clinic start generated code]*/
4253
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004254static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004255_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004256 int server_side, PyObject *hostname_obj,
4257 PyObject *owner, PyObject *session)
4258/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004259{
Antoine Pitroud5323212010-10-22 18:19:07 +00004260 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004261 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004262
Antoine Pitroud5323212010-10-22 18:19:07 +00004263 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004264 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004265 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004266 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004267 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004268 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004269
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004270 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4271 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004272 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004273 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004274 if (hostname != NULL)
4275 PyMem_Free(hostname);
4276 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004277}
4278
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004279/*[clinic input]
4280_ssl._SSLContext._wrap_bio
4281 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4282 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4283 server_side: int
4284 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004285 *
4286 owner: object = None
4287 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004288
4289[clinic start generated code]*/
4290
Antoine Pitroub0182c82010-10-12 20:09:02 +00004291static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004292_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4293 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004294 PyObject *hostname_obj, PyObject *owner,
4295 PyObject *session)
4296/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004297{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004298 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004299 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004300
4301 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004302 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004303 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004304 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004305 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004306 }
4307
4308 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004309 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004310 incoming, outgoing);
4311
4312 PyMem_Free(hostname);
4313 return res;
4314}
4315
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004316/*[clinic input]
4317_ssl._SSLContext.session_stats
4318[clinic start generated code]*/
4319
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004320static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004321_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4322/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004323{
4324 int r;
4325 PyObject *value, *stats = PyDict_New();
4326 if (!stats)
4327 return NULL;
4328
4329#define ADD_STATS(SSL_NAME, KEY_NAME) \
4330 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4331 if (value == NULL) \
4332 goto error; \
4333 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4334 Py_DECREF(value); \
4335 if (r < 0) \
4336 goto error;
4337
4338 ADD_STATS(number, "number");
4339 ADD_STATS(connect, "connect");
4340 ADD_STATS(connect_good, "connect_good");
4341 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4342 ADD_STATS(accept, "accept");
4343 ADD_STATS(accept_good, "accept_good");
4344 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4345 ADD_STATS(accept, "accept");
4346 ADD_STATS(hits, "hits");
4347 ADD_STATS(misses, "misses");
4348 ADD_STATS(timeouts, "timeouts");
4349 ADD_STATS(cache_full, "cache_full");
4350
4351#undef ADD_STATS
4352
4353 return stats;
4354
4355error:
4356 Py_DECREF(stats);
4357 return NULL;
4358}
4359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004360/*[clinic input]
4361_ssl._SSLContext.set_default_verify_paths
4362[clinic start generated code]*/
4363
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004364static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004365_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4366/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004367{
4368 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4369 _setSSLError(NULL, 0, __FILE__, __LINE__);
4370 return NULL;
4371 }
4372 Py_RETURN_NONE;
4373}
4374
Antoine Pitrou501da612011-12-21 09:27:41 +01004375#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004376/*[clinic input]
4377_ssl._SSLContext.set_ecdh_curve
4378 name: object
4379 /
4380
4381[clinic start generated code]*/
4382
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004383static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004384_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4385/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004386{
4387 PyObject *name_bytes;
4388 int nid;
4389 EC_KEY *key;
4390
4391 if (!PyUnicode_FSConverter(name, &name_bytes))
4392 return NULL;
4393 assert(PyBytes_Check(name_bytes));
4394 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4395 Py_DECREF(name_bytes);
4396 if (nid == 0) {
4397 PyErr_Format(PyExc_ValueError,
4398 "unknown elliptic curve name %R", name);
4399 return NULL;
4400 }
4401 key = EC_KEY_new_by_curve_name(nid);
4402 if (key == NULL) {
4403 _setSSLError(NULL, 0, __FILE__, __LINE__);
4404 return NULL;
4405 }
4406 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4407 EC_KEY_free(key);
4408 Py_RETURN_NONE;
4409}
Antoine Pitrou501da612011-12-21 09:27:41 +01004410#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004411
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004412#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004413static int
4414_servername_callback(SSL *s, int *al, void *args)
4415{
4416 int ret;
4417 PySSLContext *ssl_ctx = (PySSLContext *) args;
4418 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004419 PyObject *result;
4420 /* The high-level ssl.SSLSocket object */
4421 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004422 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004423 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004424
Christian Heimes11a14932018-02-24 02:35:08 +01004425 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004426 /* remove race condition in this the call back while if removing the
4427 * callback is in progress */
4428 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004429 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004430 }
4431
4432 ssl = SSL_get_app_data(s);
4433 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004434
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004435 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004436 * SSL connection and that has a .context attribute that can be changed to
4437 * identify the requested hostname. Since the official API is the Python
4438 * level API we want to pass the callback a Python level object rather than
4439 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4440 * SSLObject) that will be passed. Otherwise if there's a socket then that
4441 * will be passed. If both do not exist only then the C-level object is
4442 * passed. */
4443 if (ssl->owner)
4444 ssl_socket = PyWeakref_GetObject(ssl->owner);
4445 else if (ssl->Socket)
4446 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4447 else
4448 ssl_socket = (PyObject *) ssl;
4449
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004450 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004451 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004452 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004453
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004454 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004455 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004456 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004457 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004458 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004459 PyObject *servername_bytes;
4460 PyObject *servername_str;
4461
4462 servername_bytes = PyBytes_FromString(servername);
4463 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004464 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4465 goto error;
4466 }
Christian Heimes11a14932018-02-24 02:35:08 +01004467 /* server_hostname was encoded to an A-label by our caller; put it
4468 * back into a str object, but still as an A-label (bpo-28414)
4469 */
4470 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4471 Py_DECREF(servername_bytes);
4472 if (servername_str == NULL) {
4473 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004474 goto error;
4475 }
Christian Heimes11a14932018-02-24 02:35:08 +01004476 result = PyObject_CallFunctionObjArgs(
4477 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4478 ssl_ctx, NULL);
4479 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004480 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004481 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004482
4483 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004484 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004485 *al = SSL_AD_HANDSHAKE_FAILURE;
4486 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4487 }
4488 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004489 /* Result may be None, a SSLContext or an integer
4490 * None and SSLContext are OK, integer or other values are an error.
4491 */
4492 if (result == Py_None) {
4493 ret = SSL_TLSEXT_ERR_OK;
4494 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004495 *al = (int) PyLong_AsLong(result);
4496 if (PyErr_Occurred()) {
4497 PyErr_WriteUnraisable(result);
4498 *al = SSL_AD_INTERNAL_ERROR;
4499 }
4500 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4501 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004502 Py_DECREF(result);
4503 }
4504
4505 PyGILState_Release(gstate);
4506 return ret;
4507
4508error:
4509 Py_DECREF(ssl_socket);
4510 *al = SSL_AD_INTERNAL_ERROR;
4511 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4512 PyGILState_Release(gstate);
4513 return ret;
4514}
Antoine Pitroua5963382013-03-30 16:39:00 +01004515#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004516
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004517static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004518get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004519{
Christian Heimes11a14932018-02-24 02:35:08 +01004520 PyObject *cb = self->set_sni_cb;
4521 if (cb == NULL) {
4522 Py_RETURN_NONE;
4523 }
4524 Py_INCREF(cb);
4525 return cb;
4526}
4527
4528static int
4529set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4530{
4531 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4532 PyErr_SetString(PyExc_ValueError,
4533 "sni_callback cannot be set on TLS_CLIENT context");
4534 return -1;
4535 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004536#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004537 Py_CLEAR(self->set_sni_cb);
4538 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004539 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4540 }
4541 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004542 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004543 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4544 PyErr_SetString(PyExc_TypeError,
4545 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004546 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004547 }
Christian Heimes11a14932018-02-24 02:35:08 +01004548 Py_INCREF(arg);
4549 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004550 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4551 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4552 }
Christian Heimes11a14932018-02-24 02:35:08 +01004553 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004554#else
4555 PyErr_SetString(PyExc_NotImplementedError,
4556 "The TLS extension servername callback, "
4557 "SSL_CTX_set_tlsext_servername_callback, "
4558 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004559 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004560#endif
4561}
4562
Christian Heimes11a14932018-02-24 02:35:08 +01004563PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4564"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4565\n\
4566If the argument is None then the callback is disabled. The method is called\n\
4567with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4568See RFC 6066 for details of the SNI extension.");
4569
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004570/*[clinic input]
4571_ssl._SSLContext.cert_store_stats
4572
4573Returns quantities of loaded X.509 certificates.
4574
4575X.509 certificates with a CA extension and certificate revocation lists
4576inside the context's cert store.
4577
4578NOTE: Certificates in a capath directory aren't loaded unless they have
4579been used at least once.
4580[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004581
4582static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004583_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4584/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004585{
4586 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004587 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004588 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004589 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004590
4591 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004592 objs = X509_STORE_get0_objects(store);
4593 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4594 obj = sk_X509_OBJECT_value(objs, i);
4595 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004596 case X509_LU_X509:
4597 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004598 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004599 ca++;
4600 }
4601 break;
4602 case X509_LU_CRL:
4603 crl++;
4604 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004605 default:
4606 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4607 * As far as I can tell they are internal states and never
4608 * stored in a cert store */
4609 break;
4610 }
4611 }
4612 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4613 "x509_ca", ca);
4614}
4615
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004616/*[clinic input]
4617_ssl._SSLContext.get_ca_certs
4618 binary_form: bool = False
4619
4620Returns a list of dicts with information of loaded CA certs.
4621
4622If the optional argument is True, returns a DER-encoded copy of the CA
4623certificate.
4624
4625NOTE: Certificates in a capath directory aren't loaded unless they have
4626been used at least once.
4627[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004628
4629static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004630_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4631/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004632{
4633 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004634 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004635 PyObject *ci = NULL, *rlist = NULL;
4636 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004637
4638 if ((rlist = PyList_New(0)) == NULL) {
4639 return NULL;
4640 }
4641
4642 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004643 objs = X509_STORE_get0_objects(store);
4644 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004645 X509_OBJECT *obj;
4646 X509 *cert;
4647
Christian Heimes598894f2016-09-05 23:19:05 +02004648 obj = sk_X509_OBJECT_value(objs, i);
4649 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004650 /* not a x509 cert */
4651 continue;
4652 }
4653 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004654 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004655 if (!X509_check_ca(cert)) {
4656 continue;
4657 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004658 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004659 ci = _certificate_to_der(cert);
4660 } else {
4661 ci = _decode_certificate(cert);
4662 }
4663 if (ci == NULL) {
4664 goto error;
4665 }
4666 if (PyList_Append(rlist, ci) == -1) {
4667 goto error;
4668 }
4669 Py_CLEAR(ci);
4670 }
4671 return rlist;
4672
4673 error:
4674 Py_XDECREF(ci);
4675 Py_XDECREF(rlist);
4676 return NULL;
4677}
4678
4679
Antoine Pitrou152efa22010-05-16 18:19:27 +00004680static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004681 {"check_hostname", (getter) get_check_hostname,
4682 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004683 {"_host_flags", (getter) get_host_flags,
4684 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004685#if SSL_CTRL_GET_MAX_PROTO_VERSION
4686 {"minimum_version", (getter) get_minimum_version,
4687 (setter) set_minimum_version, NULL},
4688 {"maximum_version", (getter) get_maximum_version,
4689 (setter) set_maximum_version, NULL},
4690#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004691#ifdef HAVE_OPENSSL_KEYLOG
4692 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4693 (setter) _PySSLContext_set_keylog_filename, NULL},
4694#endif
4695 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4696 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004697 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004698 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004699#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4700 {"num_tickets", (getter) get_num_tickets,
4701 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4702#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004703 {"options", (getter) get_options,
4704 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004705 {"post_handshake_auth", (getter) get_post_handshake_auth,
4706#ifdef TLS1_3_VERSION
4707 (setter) set_post_handshake_auth,
4708#else
4709 NULL,
4710#endif
4711 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004712 {"protocol", (getter) get_protocol,
4713 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004714 {"verify_flags", (getter) get_verify_flags,
4715 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004716 {"verify_mode", (getter) get_verify_mode,
4717 (setter) set_verify_mode, NULL},
4718 {NULL}, /* sentinel */
4719};
4720
4721static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004722 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4723 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4724 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4725 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4726 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4727 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4728 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4729 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4730 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4731 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4732 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004733 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4734 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004735 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004736 {NULL, NULL} /* sentinel */
4737};
4738
4739static PyTypeObject PySSLContext_Type = {
4740 PyVarObject_HEAD_INIT(NULL, 0)
4741 "_ssl._SSLContext", /*tp_name*/
4742 sizeof(PySSLContext), /*tp_basicsize*/
4743 0, /*tp_itemsize*/
4744 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004745 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004746 0, /*tp_getattr*/
4747 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004748 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004749 0, /*tp_repr*/
4750 0, /*tp_as_number*/
4751 0, /*tp_as_sequence*/
4752 0, /*tp_as_mapping*/
4753 0, /*tp_hash*/
4754 0, /*tp_call*/
4755 0, /*tp_str*/
4756 0, /*tp_getattro*/
4757 0, /*tp_setattro*/
4758 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004759 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004760 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004761 (traverseproc) context_traverse, /*tp_traverse*/
4762 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004763 0, /*tp_richcompare*/
4764 0, /*tp_weaklistoffset*/
4765 0, /*tp_iter*/
4766 0, /*tp_iternext*/
4767 context_methods, /*tp_methods*/
4768 0, /*tp_members*/
4769 context_getsetlist, /*tp_getset*/
4770 0, /*tp_base*/
4771 0, /*tp_dict*/
4772 0, /*tp_descr_get*/
4773 0, /*tp_descr_set*/
4774 0, /*tp_dictoffset*/
4775 0, /*tp_init*/
4776 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004777 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004778};
4779
4780
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004781/*
4782 * MemoryBIO objects
4783 */
4784
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004785/*[clinic input]
4786@classmethod
4787_ssl.MemoryBIO.__new__
4788
4789[clinic start generated code]*/
4790
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004791static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004792_ssl_MemoryBIO_impl(PyTypeObject *type)
4793/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004794{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004795 BIO *bio;
4796 PySSLMemoryBIO *self;
4797
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004798 bio = BIO_new(BIO_s_mem());
4799 if (bio == NULL) {
4800 PyErr_SetString(PySSLErrorObject,
4801 "failed to allocate BIO");
4802 return NULL;
4803 }
4804 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4805 * just that no data is currently available. The SSL routines should retry
4806 * the read, which we can achieve by calling BIO_set_retry_read(). */
4807 BIO_set_retry_read(bio);
4808 BIO_set_mem_eof_return(bio, -1);
4809
4810 assert(type != NULL && type->tp_alloc != NULL);
4811 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4812 if (self == NULL) {
4813 BIO_free(bio);
4814 return NULL;
4815 }
4816 self->bio = bio;
4817 self->eof_written = 0;
4818
4819 return (PyObject *) self;
4820}
4821
4822static void
4823memory_bio_dealloc(PySSLMemoryBIO *self)
4824{
4825 BIO_free(self->bio);
4826 Py_TYPE(self)->tp_free(self);
4827}
4828
4829static PyObject *
4830memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4831{
Segev Finer5cff6372017-07-27 01:19:17 +03004832 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004833}
4834
4835PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4836"The number of bytes pending in the memory BIO.");
4837
4838static PyObject *
4839memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4840{
4841 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4842 && self->eof_written);
4843}
4844
4845PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4846"Whether the memory BIO is at EOF.");
4847
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004848/*[clinic input]
4849_ssl.MemoryBIO.read
4850 size as len: int = -1
4851 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004852
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004853Read up to size bytes from the memory BIO.
4854
4855If size is not specified, read the entire buffer.
4856If the return value is an empty bytes instance, this means either
4857EOF or that no data is available. Use the "eof" property to
4858distinguish between the two.
4859[clinic start generated code]*/
4860
4861static PyObject *
4862_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4863/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4864{
4865 int avail, nbytes;
4866 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004867
Segev Finer5cff6372017-07-27 01:19:17 +03004868 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004869 if ((len < 0) || (len > avail))
4870 len = avail;
4871
4872 result = PyBytes_FromStringAndSize(NULL, len);
4873 if ((result == NULL) || (len == 0))
4874 return result;
4875
4876 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004877 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004878 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004879 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004880 return NULL;
4881 }
4882
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004883 /* There should never be any short reads but check anyway. */
4884 if (nbytes < len) {
4885 _PyBytes_Resize(&result, nbytes);
4886 }
4887
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004888 return result;
4889}
4890
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004891/*[clinic input]
4892_ssl.MemoryBIO.write
4893 b: Py_buffer
4894 /
4895
4896Writes the bytes b into the memory BIO.
4897
4898Returns the number of bytes written.
4899[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004900
4901static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004902_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4903/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004904{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004905 int nbytes;
4906
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004907 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004908 PyErr_Format(PyExc_OverflowError,
4909 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004910 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004911 }
4912
4913 if (self->eof_written) {
4914 PyErr_SetString(PySSLErrorObject,
4915 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004916 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004917 }
4918
Segev Finer5cff6372017-07-27 01:19:17 +03004919 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004920 if (nbytes < 0) {
4921 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004922 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004923 }
4924
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004925 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004926}
4927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004928/*[clinic input]
4929_ssl.MemoryBIO.write_eof
4930
4931Write an EOF marker to the memory BIO.
4932
4933When all data has been read, the "eof" property will be True.
4934[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004935
4936static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004937_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4938/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004939{
4940 self->eof_written = 1;
4941 /* After an EOF is written, a zero return from read() should be a real EOF
4942 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4943 BIO_clear_retry_flags(self->bio);
4944 BIO_set_mem_eof_return(self->bio, 0);
4945
4946 Py_RETURN_NONE;
4947}
4948
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004949static PyGetSetDef memory_bio_getsetlist[] = {
4950 {"pending", (getter) memory_bio_get_pending, NULL,
4951 PySSL_memory_bio_pending_doc},
4952 {"eof", (getter) memory_bio_get_eof, NULL,
4953 PySSL_memory_bio_eof_doc},
4954 {NULL}, /* sentinel */
4955};
4956
4957static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004958 _SSL_MEMORYBIO_READ_METHODDEF
4959 _SSL_MEMORYBIO_WRITE_METHODDEF
4960 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004961 {NULL, NULL} /* sentinel */
4962};
4963
4964static PyTypeObject PySSLMemoryBIO_Type = {
4965 PyVarObject_HEAD_INIT(NULL, 0)
4966 "_ssl.MemoryBIO", /*tp_name*/
4967 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4968 0, /*tp_itemsize*/
4969 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004970 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004971 0, /*tp_getattr*/
4972 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004973 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004974 0, /*tp_repr*/
4975 0, /*tp_as_number*/
4976 0, /*tp_as_sequence*/
4977 0, /*tp_as_mapping*/
4978 0, /*tp_hash*/
4979 0, /*tp_call*/
4980 0, /*tp_str*/
4981 0, /*tp_getattro*/
4982 0, /*tp_setattro*/
4983 0, /*tp_as_buffer*/
4984 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4985 0, /*tp_doc*/
4986 0, /*tp_traverse*/
4987 0, /*tp_clear*/
4988 0, /*tp_richcompare*/
4989 0, /*tp_weaklistoffset*/
4990 0, /*tp_iter*/
4991 0, /*tp_iternext*/
4992 memory_bio_methods, /*tp_methods*/
4993 0, /*tp_members*/
4994 memory_bio_getsetlist, /*tp_getset*/
4995 0, /*tp_base*/
4996 0, /*tp_dict*/
4997 0, /*tp_descr_get*/
4998 0, /*tp_descr_set*/
4999 0, /*tp_dictoffset*/
5000 0, /*tp_init*/
5001 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005002 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005003};
5004
Antoine Pitrou152efa22010-05-16 18:19:27 +00005005
Christian Heimes99a65702016-09-10 23:44:53 +02005006/*
5007 * SSL Session object
5008 */
5009
5010static void
5011PySSLSession_dealloc(PySSLSession *self)
5012{
INADA Naokia6296d32017-08-24 14:55:17 +09005013 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005014 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005015 Py_XDECREF(self->ctx);
5016 if (self->session != NULL) {
5017 SSL_SESSION_free(self->session);
5018 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005019 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005020}
5021
5022static PyObject *
5023PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5024{
5025 int result;
5026
5027 if (left == NULL || right == NULL) {
5028 PyErr_BadInternalCall();
5029 return NULL;
5030 }
5031
5032 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5033 Py_RETURN_NOTIMPLEMENTED;
5034 }
5035
5036 if (left == right) {
5037 result = 0;
5038 } else {
5039 const unsigned char *left_id, *right_id;
5040 unsigned int left_len, right_len;
5041 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5042 &left_len);
5043 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5044 &right_len);
5045 if (left_len == right_len) {
5046 result = memcmp(left_id, right_id, left_len);
5047 } else {
5048 result = 1;
5049 }
5050 }
5051
5052 switch (op) {
5053 case Py_EQ:
5054 if (result == 0) {
5055 Py_RETURN_TRUE;
5056 } else {
5057 Py_RETURN_FALSE;
5058 }
5059 break;
5060 case Py_NE:
5061 if (result != 0) {
5062 Py_RETURN_TRUE;
5063 } else {
5064 Py_RETURN_FALSE;
5065 }
5066 break;
5067 case Py_LT:
5068 case Py_LE:
5069 case Py_GT:
5070 case Py_GE:
5071 Py_RETURN_NOTIMPLEMENTED;
5072 break;
5073 default:
5074 PyErr_BadArgument();
5075 return NULL;
5076 }
5077}
5078
5079static int
5080PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5081{
5082 Py_VISIT(self->ctx);
5083 return 0;
5084}
5085
5086static int
5087PySSLSession_clear(PySSLSession *self)
5088{
5089 Py_CLEAR(self->ctx);
5090 return 0;
5091}
5092
5093
5094static PyObject *
5095PySSLSession_get_time(PySSLSession *self, void *closure) {
5096 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5097}
5098
5099PyDoc_STRVAR(PySSLSession_get_time_doc,
5100"Session creation time (seconds since epoch).");
5101
5102
5103static PyObject *
5104PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5105 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5106}
5107
5108PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5109"Session timeout (delta in seconds).");
5110
5111
5112static PyObject *
5113PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5114 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5115 return PyLong_FromUnsignedLong(hint);
5116}
5117
5118PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5119"Ticket life time hint.");
5120
5121
5122static PyObject *
5123PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5124 const unsigned char *id;
5125 unsigned int len;
5126 id = SSL_SESSION_get_id(self->session, &len);
5127 return PyBytes_FromStringAndSize((const char *)id, len);
5128}
5129
5130PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5131"Session id");
5132
5133
5134static PyObject *
5135PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5136 if (SSL_SESSION_has_ticket(self->session)) {
5137 Py_RETURN_TRUE;
5138 } else {
5139 Py_RETURN_FALSE;
5140 }
5141}
5142
5143PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5144"Does the session contain a ticket?");
5145
5146
5147static PyGetSetDef PySSLSession_getsetlist[] = {
5148 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5149 PySSLSession_get_has_ticket_doc},
5150 {"id", (getter) PySSLSession_get_session_id, NULL,
5151 PySSLSession_get_session_id_doc},
5152 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5153 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5154 {"time", (getter) PySSLSession_get_time, NULL,
5155 PySSLSession_get_time_doc},
5156 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5157 PySSLSession_get_timeout_doc},
5158 {NULL}, /* sentinel */
5159};
5160
5161static PyTypeObject PySSLSession_Type = {
5162 PyVarObject_HEAD_INIT(NULL, 0)
5163 "_ssl.Session", /*tp_name*/
5164 sizeof(PySSLSession), /*tp_basicsize*/
5165 0, /*tp_itemsize*/
5166 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005167 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005168 0, /*tp_getattr*/
5169 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005170 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005171 0, /*tp_repr*/
5172 0, /*tp_as_number*/
5173 0, /*tp_as_sequence*/
5174 0, /*tp_as_mapping*/
5175 0, /*tp_hash*/
5176 0, /*tp_call*/
5177 0, /*tp_str*/
5178 0, /*tp_getattro*/
5179 0, /*tp_setattro*/
5180 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005181 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005182 0, /*tp_doc*/
5183 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5184 (inquiry)PySSLSession_clear, /*tp_clear*/
5185 PySSLSession_richcompare, /*tp_richcompare*/
5186 0, /*tp_weaklistoffset*/
5187 0, /*tp_iter*/
5188 0, /*tp_iternext*/
5189 0, /*tp_methods*/
5190 0, /*tp_members*/
5191 PySSLSession_getsetlist, /*tp_getset*/
5192};
5193
5194
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005195/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005196/*[clinic input]
5197_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005198 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005199 entropy: double
5200 /
5201
5202Mix string into the OpenSSL PRNG state.
5203
5204entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305205string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005206[clinic start generated code]*/
5207
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005209_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005210/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005211{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005212 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005213 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005214
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005215 buf = (const char *)view->buf;
5216 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005217 do {
5218 written = Py_MIN(len, INT_MAX);
5219 RAND_add(buf, (int)written, entropy);
5220 buf += written;
5221 len -= written;
5222 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005223 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005224}
5225
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005226static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005227PySSL_RAND(int len, int pseudo)
5228{
5229 int ok;
5230 PyObject *bytes;
5231 unsigned long err;
5232 const char *errstr;
5233 PyObject *v;
5234
Victor Stinner1e81a392013-12-19 16:47:04 +01005235 if (len < 0) {
5236 PyErr_SetString(PyExc_ValueError, "num must be positive");
5237 return NULL;
5238 }
5239
Victor Stinner99c8b162011-05-24 12:05:19 +02005240 bytes = PyBytes_FromStringAndSize(NULL, len);
5241 if (bytes == NULL)
5242 return NULL;
5243 if (pseudo) {
5244 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5245 if (ok == 0 || ok == 1)
5246 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5247 }
5248 else {
5249 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5250 if (ok == 1)
5251 return bytes;
5252 }
5253 Py_DECREF(bytes);
5254
5255 err = ERR_get_error();
5256 errstr = ERR_reason_error_string(err);
5257 v = Py_BuildValue("(ks)", err, errstr);
5258 if (v != NULL) {
5259 PyErr_SetObject(PySSLErrorObject, v);
5260 Py_DECREF(v);
5261 }
5262 return NULL;
5263}
5264
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005265/*[clinic input]
5266_ssl.RAND_bytes
5267 n: int
5268 /
5269
5270Generate n cryptographically strong pseudo-random bytes.
5271[clinic start generated code]*/
5272
Victor Stinner99c8b162011-05-24 12:05:19 +02005273static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005274_ssl_RAND_bytes_impl(PyObject *module, int n)
5275/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005276{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005277 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005278}
5279
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005280/*[clinic input]
5281_ssl.RAND_pseudo_bytes
5282 n: int
5283 /
5284
5285Generate n pseudo-random bytes.
5286
5287Return a pair (bytes, is_cryptographic). is_cryptographic is True
5288if the bytes generated are cryptographically strong.
5289[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005290
5291static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005292_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5293/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005294{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005295 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005296}
5297
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005298/*[clinic input]
5299_ssl.RAND_status
5300
5301Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5302
5303It is necessary to seed the PRNG with RAND_add() on some platforms before
5304using the ssl() function.
5305[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005306
5307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005308_ssl_RAND_status_impl(PyObject *module)
5309/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005310{
Christian Heimes217cfd12007-12-02 14:31:20 +00005311 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005312}
5313
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005314#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005315/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005316/*[clinic input]
5317_ssl.RAND_egd
5318 path: object(converter="PyUnicode_FSConverter")
5319 /
5320
5321Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5322
5323Returns number of bytes read. Raises SSLError if connection to EGD
5324fails or if it does not provide enough data to seed PRNG.
5325[clinic start generated code]*/
5326
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005327static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005328_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5329/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005330{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005331 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005332 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005333 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005334 PyErr_SetString(PySSLErrorObject,
5335 "EGD connection failed or EGD did not return "
5336 "enough data to seed the PRNG");
5337 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005338 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005339 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005340}
Christian Heimesa5d07652016-09-24 10:48:05 +02005341/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005342#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005343
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005344
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005345
5346/*[clinic input]
5347_ssl.get_default_verify_paths
5348
5349Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5350
5351The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5352[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005353
5354static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005355_ssl_get_default_verify_paths_impl(PyObject *module)
5356/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005357{
5358 PyObject *ofile_env = NULL;
5359 PyObject *ofile = NULL;
5360 PyObject *odir_env = NULL;
5361 PyObject *odir = NULL;
5362
Benjamin Petersond113c962015-07-18 10:59:13 -07005363#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005364 const char *tmp = (info); \
5365 target = NULL; \
5366 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5367 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5368 target = PyBytes_FromString(tmp); } \
5369 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005370 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005371
Benjamin Petersond113c962015-07-18 10:59:13 -07005372 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5373 CONVERT(X509_get_default_cert_file(), ofile);
5374 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5375 CONVERT(X509_get_default_cert_dir(), odir);
5376#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005377
Christian Heimes200bb1b2013-06-14 15:14:29 +02005378 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005379
5380 error:
5381 Py_XDECREF(ofile_env);
5382 Py_XDECREF(ofile);
5383 Py_XDECREF(odir_env);
5384 Py_XDECREF(odir);
5385 return NULL;
5386}
5387
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005388static PyObject*
5389asn1obj2py(ASN1_OBJECT *obj)
5390{
5391 int nid;
5392 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005393
5394 nid = OBJ_obj2nid(obj);
5395 if (nid == NID_undef) {
5396 PyErr_Format(PyExc_ValueError, "Unknown object");
5397 return NULL;
5398 }
5399 sn = OBJ_nid2sn(nid);
5400 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005401 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005402}
5403
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005404/*[clinic input]
5405_ssl.txt2obj
5406 txt: str
5407 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005408
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005409Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5410
5411By default objects are looked up by OID. With name=True short and
5412long name are also matched.
5413[clinic start generated code]*/
5414
5415static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005416_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5417/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005418{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005419 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005420 ASN1_OBJECT *obj;
5421
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005422 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5423 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005424 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005425 return NULL;
5426 }
5427 result = asn1obj2py(obj);
5428 ASN1_OBJECT_free(obj);
5429 return result;
5430}
5431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005432/*[clinic input]
5433_ssl.nid2obj
5434 nid: int
5435 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005436
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005437Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5438[clinic start generated code]*/
5439
5440static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005441_ssl_nid2obj_impl(PyObject *module, int nid)
5442/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005443{
5444 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005445 ASN1_OBJECT *obj;
5446
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005447 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005448 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005449 return NULL;
5450 }
5451 obj = OBJ_nid2obj(nid);
5452 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005453 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005454 return NULL;
5455 }
5456 result = asn1obj2py(obj);
5457 ASN1_OBJECT_free(obj);
5458 return result;
5459}
5460
Christian Heimes46bebee2013-06-09 19:03:31 +02005461#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005462
5463static PyObject*
5464certEncodingType(DWORD encodingType)
5465{
5466 static PyObject *x509_asn = NULL;
5467 static PyObject *pkcs_7_asn = NULL;
5468
5469 if (x509_asn == NULL) {
5470 x509_asn = PyUnicode_InternFromString("x509_asn");
5471 if (x509_asn == NULL)
5472 return NULL;
5473 }
5474 if (pkcs_7_asn == NULL) {
5475 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5476 if (pkcs_7_asn == NULL)
5477 return NULL;
5478 }
5479 switch(encodingType) {
5480 case X509_ASN_ENCODING:
5481 Py_INCREF(x509_asn);
5482 return x509_asn;
5483 case PKCS_7_ASN_ENCODING:
5484 Py_INCREF(pkcs_7_asn);
5485 return pkcs_7_asn;
5486 default:
5487 return PyLong_FromLong(encodingType);
5488 }
5489}
5490
5491static PyObject*
5492parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5493{
5494 CERT_ENHKEY_USAGE *usage;
5495 DWORD size, error, i;
5496 PyObject *retval;
5497
5498 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5499 error = GetLastError();
5500 if (error == CRYPT_E_NOT_FOUND) {
5501 Py_RETURN_TRUE;
5502 }
5503 return PyErr_SetFromWindowsErr(error);
5504 }
5505
5506 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5507 if (usage == NULL) {
5508 return PyErr_NoMemory();
5509 }
5510
5511 /* Now get the actual enhanced usage property */
5512 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5513 PyMem_Free(usage);
5514 error = GetLastError();
5515 if (error == CRYPT_E_NOT_FOUND) {
5516 Py_RETURN_TRUE;
5517 }
5518 return PyErr_SetFromWindowsErr(error);
5519 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005520 retval = PyFrozenSet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005521 if (retval == NULL) {
5522 goto error;
5523 }
5524 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5525 if (usage->rgpszUsageIdentifier[i]) {
5526 PyObject *oid;
5527 int err;
5528 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5529 if (oid == NULL) {
5530 Py_CLEAR(retval);
5531 goto error;
5532 }
5533 err = PySet_Add(retval, oid);
5534 Py_DECREF(oid);
5535 if (err == -1) {
5536 Py_CLEAR(retval);
5537 goto error;
5538 }
5539 }
5540 }
5541 error:
5542 PyMem_Free(usage);
5543 return retval;
5544}
5545
kctherookied93fbbf2019-03-29 00:59:06 +07005546static HCERTSTORE
5547ssl_collect_certificates(const char *store_name)
5548{
5549/* this function collects the system certificate stores listed in
5550 * system_stores into a collection certificate store for being
5551 * enumerated. The store must be readable to be added to the
5552 * store collection.
5553 */
5554
5555 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5556 static DWORD system_stores[] = {
5557 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5558 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5559 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5560 CERT_SYSTEM_STORE_CURRENT_USER,
5561 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5562 CERT_SYSTEM_STORE_SERVICES,
5563 CERT_SYSTEM_STORE_USERS};
5564 size_t i, storesAdded;
5565 BOOL result;
5566
5567 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5568 (HCRYPTPROV)NULL, 0, NULL);
5569 if (!hCollectionStore) {
5570 return NULL;
5571 }
5572 storesAdded = 0;
5573 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5574 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5575 (HCRYPTPROV)NULL,
5576 CERT_STORE_READONLY_FLAG |
5577 system_stores[i], store_name);
5578 if (hSystemStore) {
5579 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5580 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5581 if (result) {
5582 ++storesAdded;
5583 }
Steve Dower5d695b62019-09-09 06:48:22 -07005584 CertCloseStore(hSystemStore, 0); /* flag must be 0 */
kctherookied93fbbf2019-03-29 00:59:06 +07005585 }
5586 }
5587 if (storesAdded == 0) {
5588 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5589 return NULL;
5590 }
5591
5592 return hCollectionStore;
5593}
5594
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005595/*[clinic input]
5596_ssl.enum_certificates
5597 store_name: str
5598
5599Retrieve certificates from Windows' cert store.
5600
5601store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5602more cert storages, too. The function returns a list of (bytes,
5603encoding_type, trust) tuples. The encoding_type flag can be interpreted
5604with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5605a set of OIDs or the boolean True.
5606[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005607
Christian Heimes46bebee2013-06-09 19:03:31 +02005608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005609_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5610/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005611{
kctherookied93fbbf2019-03-29 00:59:06 +07005612 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005613 PCCERT_CONTEXT pCertCtx = NULL;
5614 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005615 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005616
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005617 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005618 if (result == NULL) {
5619 return NULL;
5620 }
kctherookied93fbbf2019-03-29 00:59:06 +07005621 hCollectionStore = ssl_collect_certificates(store_name);
5622 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005623 Py_DECREF(result);
5624 return PyErr_SetFromWindowsErr(GetLastError());
5625 }
5626
kctherookied93fbbf2019-03-29 00:59:06 +07005627 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005628 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5629 pCertCtx->cbCertEncoded);
5630 if (!cert) {
5631 Py_CLEAR(result);
5632 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005633 }
Christian Heimes44109d72013-11-22 01:51:30 +01005634 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5635 Py_CLEAR(result);
5636 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005637 }
Christian Heimes44109d72013-11-22 01:51:30 +01005638 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5639 if (keyusage == Py_True) {
5640 Py_DECREF(keyusage);
5641 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005642 }
Christian Heimes44109d72013-11-22 01:51:30 +01005643 if (keyusage == NULL) {
5644 Py_CLEAR(result);
5645 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005646 }
Christian Heimes44109d72013-11-22 01:51:30 +01005647 if ((tup = PyTuple_New(3)) == NULL) {
5648 Py_CLEAR(result);
5649 break;
5650 }
5651 PyTuple_SET_ITEM(tup, 0, cert);
5652 cert = NULL;
5653 PyTuple_SET_ITEM(tup, 1, enc);
5654 enc = NULL;
5655 PyTuple_SET_ITEM(tup, 2, keyusage);
5656 keyusage = NULL;
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005657 if (PySet_Add(result, tup) == -1) {
5658 Py_CLEAR(result);
5659 Py_CLEAR(tup);
5660 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005661 }
5662 Py_CLEAR(tup);
5663 }
5664 if (pCertCtx) {
5665 /* loop ended with an error, need to clean up context manually */
5666 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005667 }
5668
5669 /* In error cases cert, enc and tup may not be NULL */
5670 Py_XDECREF(cert);
5671 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005672 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005673 Py_XDECREF(tup);
5674
kctherookied93fbbf2019-03-29 00:59:06 +07005675 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5676 associated with the store, in this case our collection store and the
5677 associated system stores. */
5678 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005679 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005680 Py_XDECREF(result);
5681 return PyErr_SetFromWindowsErr(GetLastError());
5682 }
kctherookied93fbbf2019-03-29 00:59:06 +07005683
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005684 /* convert set to list */
5685 if (result == NULL) {
5686 return NULL;
5687 } else {
5688 PyObject *lst = PySequence_List(result);
5689 Py_DECREF(result);
5690 return lst;
5691 }
Christian Heimes44109d72013-11-22 01:51:30 +01005692}
5693
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005694/*[clinic input]
5695_ssl.enum_crls
5696 store_name: str
5697
5698Retrieve CRLs from Windows' cert store.
5699
5700store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5701more cert storages, too. The function returns a list of (bytes,
5702encoding_type) tuples. The encoding_type flag can be interpreted with
5703X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5704[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005705
5706static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005707_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5708/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005709{
kctherookied93fbbf2019-03-29 00:59:06 +07005710 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005711 PCCRL_CONTEXT pCrlCtx = NULL;
5712 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5713 PyObject *result = NULL;
5714
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005715 result = PySet_New(NULL);
Christian Heimes44109d72013-11-22 01:51:30 +01005716 if (result == NULL) {
5717 return NULL;
5718 }
kctherookied93fbbf2019-03-29 00:59:06 +07005719 hCollectionStore = ssl_collect_certificates(store_name);
5720 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005721 Py_DECREF(result);
5722 return PyErr_SetFromWindowsErr(GetLastError());
5723 }
Christian Heimes44109d72013-11-22 01:51:30 +01005724
kctherookied93fbbf2019-03-29 00:59:06 +07005725 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005726 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5727 pCrlCtx->cbCrlEncoded);
5728 if (!crl) {
5729 Py_CLEAR(result);
5730 break;
5731 }
5732 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5733 Py_CLEAR(result);
5734 break;
5735 }
5736 if ((tup = PyTuple_New(2)) == NULL) {
5737 Py_CLEAR(result);
5738 break;
5739 }
5740 PyTuple_SET_ITEM(tup, 0, crl);
5741 crl = NULL;
5742 PyTuple_SET_ITEM(tup, 1, enc);
5743 enc = NULL;
5744
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005745 if (PySet_Add(result, tup) == -1) {
5746 Py_CLEAR(result);
5747 Py_CLEAR(tup);
5748 break;
Christian Heimes44109d72013-11-22 01:51:30 +01005749 }
5750 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005751 }
Christian Heimes44109d72013-11-22 01:51:30 +01005752 if (pCrlCtx) {
5753 /* loop ended with an error, need to clean up context manually */
5754 CertFreeCRLContext(pCrlCtx);
5755 }
5756
5757 /* In error cases cert, enc and tup may not be NULL */
5758 Py_XDECREF(crl);
5759 Py_XDECREF(enc);
5760 Py_XDECREF(tup);
5761
kctherookied93fbbf2019-03-29 00:59:06 +07005762 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5763 associated with the store, in this case our collection store and the
5764 associated system stores. */
5765 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005766 /* This error case might shadow another exception.*/
5767 Py_XDECREF(result);
5768 return PyErr_SetFromWindowsErr(GetLastError());
5769 }
Steve Dowerfdd17ab2019-09-10 02:02:04 -07005770 /* convert set to list */
5771 if (result == NULL) {
5772 return NULL;
5773 } else {
5774 PyObject *lst = PySequence_List(result);
5775 Py_DECREF(result);
5776 return lst;
5777 }
Christian Heimes46bebee2013-06-09 19:03:31 +02005778}
Christian Heimes44109d72013-11-22 01:51:30 +01005779
5780#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005781
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005782/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005783static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005784 _SSL__TEST_DECODE_CERT_METHODDEF
5785 _SSL_RAND_ADD_METHODDEF
5786 _SSL_RAND_BYTES_METHODDEF
5787 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5788 _SSL_RAND_EGD_METHODDEF
5789 _SSL_RAND_STATUS_METHODDEF
5790 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5791 _SSL_ENUM_CERTIFICATES_METHODDEF
5792 _SSL_ENUM_CRLS_METHODDEF
5793 _SSL_TXT2OBJ_METHODDEF
5794 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005795 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005796};
5797
5798
Christian Heimes598894f2016-09-05 23:19:05 +02005799#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005800
5801/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005802 * of the Python C thread library
5803 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5804 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005805
5806static PyThread_type_lock *_ssl_locks = NULL;
5807
Christian Heimes4d98ca92013-08-19 17:36:29 +02005808#if OPENSSL_VERSION_NUMBER >= 0x10000000
5809/* use new CRYPTO_THREADID API. */
5810static void
5811_ssl_threadid_callback(CRYPTO_THREADID *id)
5812{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005813 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005814}
5815#else
5816/* deprecated CRYPTO_set_id_callback() API. */
5817static unsigned long
5818_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005819 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005820}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005821#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005822
Bill Janssen6e027db2007-11-15 22:23:56 +00005823static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005824 (int mode, int n, const char *file, int line) {
5825 /* this function is needed to perform locking on shared data
5826 structures. (Note that OpenSSL uses a number of global data
5827 structures that will be implicitly shared whenever multiple
5828 threads use OpenSSL.) Multi-threaded applications will
5829 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005831 locking_function() must be able to handle up to
5832 CRYPTO_num_locks() different mutex locks. It sets the n-th
5833 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005835 file and line are the file number of the function setting the
5836 lock. They can be useful for debugging.
5837 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005838
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005839 if ((_ssl_locks == NULL) ||
5840 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5841 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005842
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005843 if (mode & CRYPTO_LOCK) {
5844 PyThread_acquire_lock(_ssl_locks[n], 1);
5845 } else {
5846 PyThread_release_lock(_ssl_locks[n]);
5847 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005848}
5849
5850static int _setup_ssl_threads(void) {
5851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005852 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005853
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005854 if (_ssl_locks == NULL) {
5855 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005856 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5857 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005858 if (_ssl_locks == NULL) {
5859 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005860 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005861 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005862 for (i = 0; i < _ssl_locks_count; i++) {
5863 _ssl_locks[i] = PyThread_allocate_lock();
5864 if (_ssl_locks[i] == NULL) {
5865 unsigned int j;
5866 for (j = 0; j < i; j++) {
5867 PyThread_free_lock(_ssl_locks[j]);
5868 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005869 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005870 return 0;
5871 }
5872 }
5873 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005874#if OPENSSL_VERSION_NUMBER >= 0x10000000
5875 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5876#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005877 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005878#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005879 }
5880 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005881}
5882
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005883#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005884
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005885PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005886"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005887for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005888
Martin v. Löwis1a214512008-06-11 05:26:20 +00005889
5890static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005891 PyModuleDef_HEAD_INIT,
5892 "_ssl",
5893 module_doc,
5894 -1,
5895 PySSL_methods,
5896 NULL,
5897 NULL,
5898 NULL,
5899 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005900};
5901
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005902
5903static void
5904parse_openssl_version(unsigned long libver,
5905 unsigned int *major, unsigned int *minor,
5906 unsigned int *fix, unsigned int *patch,
5907 unsigned int *status)
5908{
5909 *status = libver & 0xF;
5910 libver >>= 4;
5911 *patch = libver & 0xFF;
5912 libver >>= 8;
5913 *fix = libver & 0xFF;
5914 libver >>= 8;
5915 *minor = libver & 0xFF;
5916 libver >>= 8;
5917 *major = libver & 0xFF;
5918}
5919
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005920PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005921PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005922{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005923 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005924 unsigned long libver;
5925 unsigned int major, minor, fix, patch, status;
5926 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005927 struct py_ssl_error_code *errcode;
5928 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005929
Antoine Pitrou152efa22010-05-16 18:19:27 +00005930 if (PyType_Ready(&PySSLContext_Type) < 0)
5931 return NULL;
5932 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005933 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005934 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5935 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005936 if (PyType_Ready(&PySSLSession_Type) < 0)
5937 return NULL;
5938
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005940 m = PyModule_Create(&_sslmodule);
5941 if (m == NULL)
5942 return NULL;
5943 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005945 /* Load _socket module and its C API */
5946 socket_api = PySocketModule_ImportModuleAndAPI();
5947 if (!socket_api)
5948 return NULL;
5949 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005950
Christian Heimesc941e622017-09-05 15:47:11 +02005951#ifndef OPENSSL_VERSION_1_1
5952 /* Load all algorithms and initialize cpuid */
5953 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005954 /* Init OpenSSL */
5955 SSL_load_error_strings();
5956 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005957#endif
5958
Christian Heimes598894f2016-09-05 23:19:05 +02005959#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005960 /* note that this will start threading if not already started */
5961 if (!_setup_ssl_threads()) {
5962 return NULL;
5963 }
Christian Heimes598894f2016-09-05 23:19:05 +02005964#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5965 /* OpenSSL 1.1.0 builtin thread support is enabled */
5966 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005967#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005968
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005969 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005970 sslerror_type_slots[0].pfunc = PyExc_OSError;
5971 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005972 if (PySSLErrorObject == NULL)
5973 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005974
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005975 /* ssl.CertificateError used to be a subclass of ValueError */
5976 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5977 if (bases == NULL)
5978 return NULL;
5979 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5980 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5981 bases, NULL);
5982 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005983 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5984 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5985 PySSLErrorObject, NULL);
5986 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5987 "ssl.SSLWantReadError", SSLWantReadError_doc,
5988 PySSLErrorObject, NULL);
5989 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5990 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5991 PySSLErrorObject, NULL);
5992 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5993 "ssl.SSLSyscallError", SSLSyscallError_doc,
5994 PySSLErrorObject, NULL);
5995 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5996 "ssl.SSLEOFError", SSLEOFError_doc,
5997 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005998 if (PySSLCertVerificationErrorObject == NULL
5999 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02006000 || PySSLWantReadErrorObject == NULL
6001 || PySSLWantWriteErrorObject == NULL
6002 || PySSLSyscallErrorObject == NULL
6003 || PySSLEOFErrorObject == NULL)
6004 return NULL;
6005 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07006006 || PyDict_SetItemString(d, "SSLCertVerificationError",
6007 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006008 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6009 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6010 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6011 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6012 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006013 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006014 if (PyDict_SetItemString(d, "_SSLContext",
6015 (PyObject *)&PySSLContext_Type) != 0)
6016 return NULL;
6017 if (PyDict_SetItemString(d, "_SSLSocket",
6018 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006019 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006020 if (PyDict_SetItemString(d, "MemoryBIO",
6021 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6022 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006023 if (PyDict_SetItemString(d, "SSLSession",
6024 (PyObject *)&PySSLSession_Type) != 0)
6025 return NULL;
6026
Christian Heimes892d66e2018-01-29 14:10:18 +01006027 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6028 PY_SSL_DEFAULT_CIPHER_STRING);
6029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006030 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6031 PY_SSL_ERROR_ZERO_RETURN);
6032 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6033 PY_SSL_ERROR_WANT_READ);
6034 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6035 PY_SSL_ERROR_WANT_WRITE);
6036 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6037 PY_SSL_ERROR_WANT_X509_LOOKUP);
6038 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6039 PY_SSL_ERROR_SYSCALL);
6040 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6041 PY_SSL_ERROR_SSL);
6042 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6043 PY_SSL_ERROR_WANT_CONNECT);
6044 /* non ssl.h errorcodes */
6045 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6046 PY_SSL_ERROR_EOF);
6047 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6048 PY_SSL_ERROR_INVALID_ERROR_CODE);
6049 /* cert requirements */
6050 PyModule_AddIntConstant(m, "CERT_NONE",
6051 PY_SSL_CERT_NONE);
6052 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6053 PY_SSL_CERT_OPTIONAL);
6054 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6055 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006056 /* CRL verification for verification_flags */
6057 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6058 0);
6059 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6060 X509_V_FLAG_CRL_CHECK);
6061 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6062 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6063 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6064 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006065#ifdef X509_V_FLAG_TRUSTED_FIRST
6066 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6067 X509_V_FLAG_TRUSTED_FIRST);
6068#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006069
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006070 /* Alert Descriptions from ssl.h */
6071 /* note RESERVED constants no longer intended for use have been removed */
6072 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6073
6074#define ADD_AD_CONSTANT(s) \
6075 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6076 SSL_AD_##s)
6077
6078 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6079 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6080 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6081 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6082 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6083 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6084 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6085 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6086 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6087 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6088 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6089 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6090 ADD_AD_CONSTANT(UNKNOWN_CA);
6091 ADD_AD_CONSTANT(ACCESS_DENIED);
6092 ADD_AD_CONSTANT(DECODE_ERROR);
6093 ADD_AD_CONSTANT(DECRYPT_ERROR);
6094 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6095 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6096 ADD_AD_CONSTANT(INTERNAL_ERROR);
6097 ADD_AD_CONSTANT(USER_CANCELLED);
6098 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006099 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006100#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6101 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6102#endif
6103#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6104 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6105#endif
6106#ifdef SSL_AD_UNRECOGNIZED_NAME
6107 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6108#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006109#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6110 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6111#endif
6112#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6113 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6114#endif
6115#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6116 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6117#endif
6118
6119#undef ADD_AD_CONSTANT
6120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006121 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006122#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006123 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6124 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006125#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006126#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006127 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6128 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006129#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006130 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006131 PY_SSL_VERSION_TLS);
6132 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6133 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006134 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6135 PY_SSL_VERSION_TLS_CLIENT);
6136 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6137 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006138 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6139 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006140#if HAVE_TLSv1_2
6141 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6142 PY_SSL_VERSION_TLS1_1);
6143 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6144 PY_SSL_VERSION_TLS1_2);
6145#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006146
Antoine Pitroub5218772010-05-21 09:56:06 +00006147 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006148 PyModule_AddIntConstant(m, "OP_ALL",
6149 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006150 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6151 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6152 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006153#if HAVE_TLSv1_2
6154 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6155 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6156#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006157#ifdef SSL_OP_NO_TLSv1_3
6158 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6159#else
6160 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6161#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006162 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6163 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006164 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006165 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006166#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006167 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006168#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006169#ifdef SSL_OP_NO_COMPRESSION
6170 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6171 SSL_OP_NO_COMPRESSION);
6172#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006173#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6174 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6175 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6176#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006177#ifdef SSL_OP_NO_RENEGOTIATION
6178 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6179 SSL_OP_NO_RENEGOTIATION);
6180#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006181
Christian Heimes61d478c2018-01-27 15:51:38 +01006182#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6183 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6184 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6185#endif
6186#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6187 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6188 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6189#endif
6190#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6191 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6192 X509_CHECK_FLAG_NO_WILDCARDS);
6193#endif
6194#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6195 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6196 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6197#endif
6198#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6199 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6200 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6201#endif
6202#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6203 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6204 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6205#endif
6206
Christian Heimes698dde12018-02-27 11:54:43 +01006207 /* protocol versions */
6208 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6209 PY_PROTO_MINIMUM_SUPPORTED);
6210 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6211 PY_PROTO_MAXIMUM_SUPPORTED);
6212 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6213 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6214 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6215 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6216 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006217
Victor Stinnerb37672d2018-11-22 03:37:50 +01006218#define addbool(m, key, value) \
6219 do { \
6220 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6221 Py_INCREF(bool_obj); \
6222 PyModule_AddObject((m), (key), bool_obj); \
6223 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006224
6225#if HAVE_SNI
6226 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006227#else
Christian Heimes698dde12018-02-27 11:54:43 +01006228 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006229#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006230
6231 addbool(m, "HAS_TLS_UNIQUE", 1);
6232
6233#ifndef OPENSSL_NO_ECDH
6234 addbool(m, "HAS_ECDH", 1);
6235#else
6236 addbool(m, "HAS_ECDH", 0);
6237#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006238
Christian Heimes29eab552018-02-25 12:31:33 +01006239#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006240 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006241#else
Christian Heimes698dde12018-02-27 11:54:43 +01006242 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006243#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006244
Christian Heimes29eab552018-02-25 12:31:33 +01006245#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006246 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006247#else
Christian Heimes698dde12018-02-27 11:54:43 +01006248 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006249#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006250
6251#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6252 addbool(m, "HAS_SSLv2", 1);
6253#else
6254 addbool(m, "HAS_SSLv2", 0);
6255#endif
6256
6257#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6258 addbool(m, "HAS_SSLv3", 1);
6259#else
6260 addbool(m, "HAS_SSLv3", 0);
6261#endif
6262
6263#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6264 addbool(m, "HAS_TLSv1", 1);
6265#else
6266 addbool(m, "HAS_TLSv1", 0);
6267#endif
6268
6269#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6270 addbool(m, "HAS_TLSv1_1", 1);
6271#else
6272 addbool(m, "HAS_TLSv1_1", 0);
6273#endif
6274
6275#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6276 addbool(m, "HAS_TLSv1_2", 1);
6277#else
6278 addbool(m, "HAS_TLSv1_2", 0);
6279#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006280
Christian Heimescb5b68a2017-09-07 18:07:00 -07006281#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006282 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006283#else
Christian Heimes698dde12018-02-27 11:54:43 +01006284 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006285#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006286
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006287 /* Mappings for error codes */
6288 err_codes_to_names = PyDict_New();
6289 err_names_to_codes = PyDict_New();
6290 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6291 return NULL;
6292 errcode = error_codes;
6293 while (errcode->mnemonic != NULL) {
6294 PyObject *mnemo, *key;
6295 mnemo = PyUnicode_FromString(errcode->mnemonic);
6296 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6297 if (mnemo == NULL || key == NULL)
6298 return NULL;
6299 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6300 return NULL;
6301 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6302 return NULL;
6303 Py_DECREF(key);
6304 Py_DECREF(mnemo);
6305 errcode++;
6306 }
6307 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6308 return NULL;
6309 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6310 return NULL;
6311
6312 lib_codes_to_names = PyDict_New();
6313 if (lib_codes_to_names == NULL)
6314 return NULL;
6315 libcode = library_codes;
6316 while (libcode->library != NULL) {
6317 PyObject *mnemo, *key;
6318 key = PyLong_FromLong(libcode->code);
6319 mnemo = PyUnicode_FromString(libcode->library);
6320 if (key == NULL || mnemo == NULL)
6321 return NULL;
6322 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6323 return NULL;
6324 Py_DECREF(key);
6325 Py_DECREF(mnemo);
6326 libcode++;
6327 }
6328 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6329 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006330
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006331 /* OpenSSL version */
6332 /* SSLeay() gives us the version of the library linked against,
6333 which could be different from the headers version.
6334 */
6335 libver = SSLeay();
6336 r = PyLong_FromUnsignedLong(libver);
6337 if (r == NULL)
6338 return NULL;
6339 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6340 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006341 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006342 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6343 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6344 return NULL;
6345 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6346 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6347 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006348
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006349 libver = OPENSSL_VERSION_NUMBER;
6350 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6351 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6352 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6353 return NULL;
6354
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006355 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006356}