blob: 2331c58ad77d5a015fef59b873d4e2e6a616b65d [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Alexandru Ardeleanb3a271f2018-09-17 14:53:31 +030066#include "openssl/dh.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010067
Christian Heimesff5be6e2018-01-20 13:19:21 +010068#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010069# ifdef LIBRESSL_VERSION_NUMBER
70# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
71# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010072# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010073# else
74# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010075# endif
76#endif
77
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010078/* SSL error object */
79static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070080static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010081static PyObject *PySSLZeroReturnErrorObject;
82static PyObject *PySSLWantReadErrorObject;
83static PyObject *PySSLWantWriteErrorObject;
84static PyObject *PySSLSyscallErrorObject;
85static PyObject *PySSLEOFErrorObject;
86
87/* Error mappings */
88static PyObject *err_codes_to_names;
89static PyObject *err_names_to_codes;
90static PyObject *lib_codes_to_names;
91
92struct py_ssl_error_code {
93 const char *mnemonic;
94 int library, reason;
95};
96struct py_ssl_library_code {
97 const char *library;
98 int code;
99};
100
Steve Dower68d663c2017-07-17 11:15:48 +0200101#if defined(MS_WINDOWS) && defined(Py_DEBUG)
102/* Debug builds on Windows rely on getting errno directly from OpenSSL.
103 * However, because it uses a different CRT, we need to transfer the
104 * value of errno from OpenSSL into our debug CRT.
105 *
106 * Don't be fooled - this is horribly ugly code. The only reasonable
107 * alternative is to do both debug and release builds of OpenSSL, which
108 * requires much uglier code to transform their automatically generated
109 * makefile. This is the lesser of all the evils.
110 */
111
112static void _PySSLFixErrno(void) {
113 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
114 if (!ucrtbase) {
115 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
116 * have a catastrophic failure, but this function is not the
117 * place to raise it. */
118 return;
119 }
120
121 typedef int *(__stdcall *errno_func)(void);
122 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
123 if (ssl_errno) {
124 errno = *ssl_errno();
125 *ssl_errno() = 0;
126 } else {
127 errno = ENOTRECOVERABLE;
128 }
129}
130
131#undef _PySSL_FIX_ERRNO
132#define _PySSL_FIX_ERRNO _PySSLFixErrno()
133#endif
134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135/* Include generated data (error codes) */
136#include "_ssl_data.h"
137
Christian Heimes598894f2016-09-05 23:19:05 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
139# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100140# define PY_OPENSSL_1_1_API 1
141#endif
142
143/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
144#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
145# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200146#endif
147
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100148/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
149 http://www.openssl.org/news/changelog.html
150 */
151#if OPENSSL_VERSION_NUMBER >= 0x10001000L
152# define HAVE_TLSv1_2 1
153#else
154# define HAVE_TLSv1_2 0
155#endif
156
Christian Heimes470fba12013-11-28 15:12:15 +0100157/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100158 * This includes the SSL_set_SSL_CTX() function.
159 */
160#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
161# define HAVE_SNI 1
162#else
163# define HAVE_SNI 0
164#endif
165
Benjamin Petersond3308222015-09-27 00:09:02 -0700166#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Christian Heimes6cdb7952018-02-24 22:12:40 +0100172/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
173 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
174 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
175 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100182#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100183# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100184#else
Christian Heimes29eab552018-02-25 12:31:33 +0100185# define HAVE_NPN 0
186#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100187
Christian Heimesc7f70692019-05-31 11:44:05 +0200188#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
189#define HAVE_OPENSSL_KEYLOG 1
190#endif
191
Victor Stinner524714e2016-07-22 17:43:59 +0200192#ifndef INVALID_SOCKET /* MS defines this */
193#define INVALID_SOCKET (-1)
194#endif
195
Christian Heimes4ca07392018-03-24 15:41:37 +0100196/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
197#ifndef OPENSSL_VERSION_1_1
198#define HAVE_OPENSSL_CRYPTO_LOCK
199#endif
200
201#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200202#define OPENSSL_NO_SSL2
203#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100204
205#ifndef PY_OPENSSL_1_1_API
206/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200209#define TLS_client_method SSLv23_client_method
210#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200211
212static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
213{
214 return ne->set;
215}
216
217#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200218/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200219static int COMP_get_type(const COMP_METHOD *meth)
220{
221 return meth->type;
222}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200223/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200224#endif
225
226static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
227{
228 return ctx->default_passwd_callback;
229}
230
231static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
232{
233 return ctx->default_passwd_callback_userdata;
234}
235
236static int X509_OBJECT_get_type(X509_OBJECT *x)
237{
238 return x->type;
239}
240
241static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
242{
243 return x->data.x509;
244}
245
246static int BIO_up_ref(BIO *b)
247{
248 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
249 return 1;
250}
251
252static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
253 return store->objs;
254}
255
Christian Heimes99a65702016-09-10 23:44:53 +0200256static int
257SSL_SESSION_has_ticket(const SSL_SESSION *s)
258{
259 return (s->tlsext_ticklen > 0) ? 1 : 0;
260}
261
262static unsigned long
263SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
264{
265 return s->tlsext_tick_lifetime_hint;
266}
267
Christian Heimes4ca07392018-03-24 15:41:37 +0100268#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200269
Christian Heimes892d66e2018-01-29 14:10:18 +0100270/* Default cipher suites */
271#ifndef PY_SSL_DEFAULT_CIPHERS
272#define PY_SSL_DEFAULT_CIPHERS 1
273#endif
274
275#if PY_SSL_DEFAULT_CIPHERS == 0
276 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
277 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
278 #endif
279#elif PY_SSL_DEFAULT_CIPHERS == 1
Stéphane Wirtel07fbbfd2018-10-05 16:17:18 +0200280/* Python custom selection of sensible cipher suites
Christian Heimes892d66e2018-01-29 14:10:18 +0100281 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
282 * !aNULL:!eNULL: really no NULL ciphers
283 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
284 * !aDSS: no authentication with discrete logarithm DSA algorithm
285 * !SRP:!PSK: no secure remote password or pre-shared key authentication
286 */
287 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
288#elif PY_SSL_DEFAULT_CIPHERS == 2
289/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
290 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
291#else
292 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
293#endif
294
Christian Heimes598894f2016-09-05 23:19:05 +0200295
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000296enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000297 /* these mirror ssl.h */
298 PY_SSL_ERROR_NONE,
299 PY_SSL_ERROR_SSL,
300 PY_SSL_ERROR_WANT_READ,
301 PY_SSL_ERROR_WANT_WRITE,
302 PY_SSL_ERROR_WANT_X509_LOOKUP,
303 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
304 PY_SSL_ERROR_ZERO_RETURN,
305 PY_SSL_ERROR_WANT_CONNECT,
306 /* start of non ssl.h errorcodes */
307 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
308 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
309 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000310};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000311
Thomas Woutersed03b412007-08-28 21:37:11 +0000312enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 PY_SSL_CLIENT,
314 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000315};
316
317enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000318 PY_SSL_CERT_NONE,
319 PY_SSL_CERT_OPTIONAL,
320 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000321};
322
323enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000324 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200325 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#if HAVE_TLSv1_2
328 PY_SSL_VERSION_TLS1,
329 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100331#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200332 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000333#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200334 PY_SSL_VERSION_TLS_CLIENT=0x10,
335 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100336};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200337
Christian Heimes698dde12018-02-27 11:54:43 +0100338enum py_proto_version {
339 PY_PROTO_MINIMUM_SUPPORTED = -2,
340 PY_PROTO_SSLv3 = SSL3_VERSION,
341 PY_PROTO_TLSv1 = TLS1_VERSION,
342 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
343 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
344#ifdef TLS1_3_VERSION
345 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
346#else
347 PY_PROTO_TLSv1_3 = 0x304,
348#endif
349 PY_PROTO_MAXIMUM_SUPPORTED = -1,
350
351/* OpenSSL has no dedicated API to set the minimum version to the maximum
352 * available version, and the other way around. We have to figure out the
353 * minimum and maximum available version on our own and hope for the best.
354 */
355#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
357#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
359#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
361#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
362 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
363#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
364 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
365#else
366 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
367#endif
368
369#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
371#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
373#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
375#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
376 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
377#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
378 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
379#else
380 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
381#endif
382};
383
384
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000385/* serves as a flag to see whether we've initialized the SSL thread support. */
386/* 0 means no, greater than 0 means yes */
387
388static unsigned int _ssl_locks_count = 0;
389
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000390/* SSL socket object */
391
392#define X509_NAME_MAXLEN 256
393
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000394/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
395 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
396 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
397#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000398# define HAVE_SSL_CTX_CLEAR_OPTIONS
399#else
400# undef HAVE_SSL_CTX_CLEAR_OPTIONS
401#endif
402
Antoine Pitroud6494802011-07-21 01:11:30 +0200403/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
404 * older SSL, but let's be safe */
405#define PySSL_CB_MAXLEN 128
406
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100407
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000408typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000409 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000410 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100411#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100413 int npn_protocols_len;
414#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100415#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500416 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300417 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500418#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100419#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100420 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100421#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100422 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100423 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
424 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
425 */
426 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100427 int protocol;
Christian Heimes9fb051f2018-09-23 08:32:31 +0200428#ifdef TLS1_3_VERSION
429 int post_handshake_auth;
430#endif
Christian Heimesc7f70692019-05-31 11:44:05 +0200431 PyObject *msg_cb;
432#ifdef HAVE_OPENSSL_KEYLOG
433 PyObject *keylog_filename;
434 BIO *keylog_bio;
435#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000436} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000437
Antoine Pitrou152efa22010-05-16 18:19:27 +0000438typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700439 int ssl; /* last seen error from SSL */
440 int c; /* last seen error from libc */
441#ifdef MS_WINDOWS
442 int ws; /* last seen error from winsock */
443#endif
444} _PySSLError;
445
446typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447 PyObject_HEAD
448 PyObject *Socket; /* weakref to socket on which we're layered */
449 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100450 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200451 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200452 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200453 PyObject *owner; /* Python level "owner" passed to servername callback */
454 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700455 _PySSLError err; /* last seen error from various sources */
Christian Heimesc7f70692019-05-31 11:44:05 +0200456 /* Some SSL callbacks don't have error reporting. Callback wrappers
457 * store exception information on the socket. The handshake, read, write,
458 * and shutdown methods check for chained exceptions.
459 */
460 PyObject *exc_type;
461 PyObject *exc_value;
462 PyObject *exc_tb;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000463} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000464
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200465typedef struct {
466 PyObject_HEAD
467 BIO *bio;
468 int eof_written;
469} PySSLMemoryBIO;
470
Christian Heimes99a65702016-09-10 23:44:53 +0200471typedef struct {
472 PyObject_HEAD
473 SSL_SESSION *session;
474 PySSLContext *ctx;
475} PySSLSession;
476
Antoine Pitrou152efa22010-05-16 18:19:27 +0000477static PyTypeObject PySSLContext_Type;
478static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200479static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200480static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000481
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700482static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
483{
484 _PySSLError err = { 0 };
485 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700486#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700487 err.ws = WSAGetLastError();
488 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700489#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700490 err.c = errno;
491 err.ssl = SSL_get_error(ssl, retcode);
492 }
493 return err;
494}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300496/*[clinic input]
497module _ssl
498class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
499class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
500class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200501class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300502[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200503/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300504
505#include "clinic/_ssl.c.h"
506
Victor Stinner14690702015-04-06 22:46:13 +0200507static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000508
Christian Heimes141c5e82018-02-24 21:10:57 +0100509static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
510static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000511#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200512#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200513#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000514
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000515typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000516 SOCKET_IS_NONBLOCKING,
517 SOCKET_IS_BLOCKING,
518 SOCKET_HAS_TIMED_OUT,
519 SOCKET_HAS_BEEN_CLOSED,
520 SOCKET_TOO_LARGE_FOR_SELECT,
521 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000522} timeout_state;
523
Thomas Woutersed03b412007-08-28 21:37:11 +0000524/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000525#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200526#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000527
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200528/* Get the socket from a PySSLSocket, if it has one */
529#define GET_SOCKET(obj) ((obj)->Socket ? \
530 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200531
Victor Stinner14690702015-04-06 22:46:13 +0200532/* If sock is NULL, use a timeout of 0 second */
533#define GET_SOCKET_TIMEOUT(sock) \
534 ((sock != NULL) ? (sock)->sock_timeout : 0)
535
Christian Heimesc7f70692019-05-31 11:44:05 +0200536#include "_ssl/debughelpers.c"
537
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200538/*
539 * SSL errors.
540 */
541
542PyDoc_STRVAR(SSLError_doc,
543"An error occurred in the SSL implementation.");
544
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700545PyDoc_STRVAR(SSLCertVerificationError_doc,
546"A certificate could not be verified.");
547
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200548PyDoc_STRVAR(SSLZeroReturnError_doc,
549"SSL/TLS session closed cleanly.");
550
551PyDoc_STRVAR(SSLWantReadError_doc,
552"Non-blocking SSL socket needs to read more data\n"
553"before the requested operation can be completed.");
554
555PyDoc_STRVAR(SSLWantWriteError_doc,
556"Non-blocking SSL socket needs to write more data\n"
557"before the requested operation can be completed.");
558
559PyDoc_STRVAR(SSLSyscallError_doc,
560"System error when attempting SSL operation.");
561
562PyDoc_STRVAR(SSLEOFError_doc,
563"SSL/TLS connection terminated abruptly.");
564
565static PyObject *
566SSLError_str(PyOSErrorObject *self)
567{
568 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
569 Py_INCREF(self->strerror);
570 return self->strerror;
571 }
572 else
573 return PyObject_Str(self->args);
574}
575
576static PyType_Slot sslerror_type_slots[] = {
577 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
Inada Naoki926b0cb2019-04-17 08:39:46 +0900578 {Py_tp_doc, (void*)SSLError_doc},
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 {Py_tp_str, SSLError_str},
580 {0, 0},
581};
582
583static PyType_Spec sslerror_type_spec = {
584 "ssl.SSLError",
585 sizeof(PyOSErrorObject),
586 0,
587 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
588 sslerror_type_slots
589};
590
591static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700592fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
593 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594{
595 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700596 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 PyObject *init_value, *msg, *key;
598 _Py_IDENTIFIER(reason);
599 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700600 _Py_IDENTIFIER(verify_message);
601 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200602
603 if (errcode != 0) {
604 int lib, reason;
605
606 lib = ERR_GET_LIB(errcode);
607 reason = ERR_GET_REASON(errcode);
608 key = Py_BuildValue("ii", lib, reason);
609 if (key == NULL)
610 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300611 reason_obj = PyDict_GetItemWithError(err_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200612 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300613 if (reason_obj == NULL && PyErr_Occurred()) {
614 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200615 }
616 key = PyLong_FromLong(lib);
617 if (key == NULL)
618 goto fail;
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300619 lib_obj = PyDict_GetItemWithError(lib_codes_to_names, key);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200620 Py_DECREF(key);
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +0300621 if (lib_obj == NULL && PyErr_Occurred()) {
622 goto fail;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200623 }
624 if (errstr == NULL)
625 errstr = ERR_reason_error_string(errcode);
626 }
627 if (errstr == NULL)
628 errstr = "unknown error";
629
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700630 /* verify code for cert validation error */
631 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
632 const char *verify_str = NULL;
633 long verify_code;
634
635 verify_code = SSL_get_verify_result(sslsock->ssl);
636 verify_code_obj = PyLong_FromLong(verify_code);
637 if (verify_code_obj == NULL) {
638 goto fail;
639 }
640
641 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700642#ifdef X509_V_ERR_HOSTNAME_MISMATCH
643 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700644 case X509_V_ERR_HOSTNAME_MISMATCH:
645 verify_obj = PyUnicode_FromFormat(
646 "Hostname mismatch, certificate is not valid for '%S'.",
647 sslsock->server_hostname
648 );
649 break;
Christian Heimes09153602017-09-08 14:47:58 -0700650#endif
651#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700652 case X509_V_ERR_IP_ADDRESS_MISMATCH:
653 verify_obj = PyUnicode_FromFormat(
654 "IP address mismatch, certificate is not valid for '%S'.",
655 sslsock->server_hostname
656 );
657 break;
Christian Heimes09153602017-09-08 14:47:58 -0700658#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 default:
660 verify_str = X509_verify_cert_error_string(verify_code);
661 if (verify_str != NULL) {
662 verify_obj = PyUnicode_FromString(verify_str);
663 } else {
664 verify_obj = Py_None;
665 Py_INCREF(verify_obj);
666 }
667 break;
668 }
669 if (verify_obj == NULL) {
670 goto fail;
671 }
672 }
673
674 if (verify_obj && reason_obj && lib_obj)
675 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
676 lib_obj, reason_obj, errstr, verify_obj,
677 lineno);
678 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200679 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
680 lib_obj, reason_obj, errstr, lineno);
681 else if (lib_obj)
682 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
683 lib_obj, errstr, lineno);
684 else
685 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 if (msg == NULL)
687 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100688
Paul Monsonfb7e7502019-05-15 15:38:55 -0700689 init_value = Py_BuildValue("iN", ERR_GET_REASON(ssl_errno), msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100690 if (init_value == NULL)
691 goto fail;
692
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200693 err_value = PyObject_CallObject(type, init_value);
694 Py_DECREF(init_value);
695 if (err_value == NULL)
696 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100697
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200698 if (reason_obj == NULL)
699 reason_obj = Py_None;
700 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
701 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700702
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200703 if (lib_obj == NULL)
704 lib_obj = Py_None;
705 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
706 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700707
708 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
709 /* Only set verify code / message for SSLCertVerificationError */
710 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
711 verify_code_obj))
712 goto fail;
713 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
714 goto fail;
715 }
716
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200717 PyErr_SetObject(type, err_value);
718fail:
719 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700720 Py_XDECREF(verify_code_obj);
721 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200722}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000723
Christian Heimesc7f70692019-05-31 11:44:05 +0200724static int
725PySSL_ChainExceptions(PySSLSocket *sslsock) {
726 if (sslsock->exc_type == NULL)
727 return 0;
728
729 _PyErr_ChainExceptions(sslsock->exc_type, sslsock->exc_value, sslsock->exc_tb);
730 sslsock->exc_type = NULL;
731 sslsock->exc_value = NULL;
732 sslsock->exc_tb = NULL;
733 return -1;
734}
735
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000736static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700737PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000738{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200739 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200740 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700741 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200743 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000744
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200746 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000747
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700748 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700749 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000750
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700751 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200753 errstr = "TLS/SSL connection has been closed (EOF)";
754 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000755 p = PY_SSL_ERROR_ZERO_RETURN;
756 break;
757 case SSL_ERROR_WANT_READ:
758 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200759 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000760 p = PY_SSL_ERROR_WANT_READ;
761 break;
762 case SSL_ERROR_WANT_WRITE:
763 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200764 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 errstr = "The operation did not complete (write)";
766 break;
767 case SSL_ERROR_WANT_X509_LOOKUP:
768 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000769 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 break;
771 case SSL_ERROR_WANT_CONNECT:
772 p = PY_SSL_ERROR_WANT_CONNECT;
773 errstr = "The operation did not complete (connect)";
774 break;
775 case SSL_ERROR_SYSCALL:
776 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000777 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700778 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000780 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200781 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200783 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000784 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000785 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700786#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700787 if (err.ws) {
788 return PyErr_SetFromWindowsErr(err.ws);
789 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700790#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700791 if (err.c) {
792 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700793 return PyErr_SetFromErrno(PyExc_OSError);
794 }
795 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200796 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000797 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200798 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000800 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200801 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000802 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 }
804 } else {
805 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 }
807 break;
808 }
809 case SSL_ERROR_SSL:
810 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700812 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200813 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000814 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700815 }
816 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
817 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
818 type = PySSLCertVerificationErrorObject;
819 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 break;
821 }
822 default:
823 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
824 errstr = "Invalid error code";
825 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700827 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000828 ERR_clear_error();
Christian Heimesc7f70692019-05-31 11:44:05 +0200829 PySSL_ChainExceptions(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000831}
832
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200834_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000835
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200836 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000837 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200838 else
839 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700840 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000841 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000843}
844
Christian Heimes61d478c2018-01-27 15:51:38 +0100845/*
846 * SSL objects
847 */
848
849static int
850_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
851{
852 int retval = -1;
853 ASN1_OCTET_STRING *ip;
854 PyObject *hostname;
855 size_t len;
856
857 assert(server_hostname);
858
859 /* Disable OpenSSL's special mode with leading dot in hostname:
860 * When name starts with a dot (e.g ".example.com"), it will be
861 * matched by a certificate valid for any sub-domain of name.
862 */
863 len = strlen(server_hostname);
864 if (len == 0 || *server_hostname == '.') {
865 PyErr_SetString(
866 PyExc_ValueError,
867 "server_hostname cannot be an empty string or start with a "
868 "leading dot.");
869 return retval;
870 }
871
872 /* inet_pton is not available on all platforms. */
873 ip = a2i_IPADDRESS(server_hostname);
874 if (ip == NULL) {
875 ERR_clear_error();
876 }
877
Christian Heimes11a14932018-02-24 02:35:08 +0100878 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100879 if (hostname == NULL) {
880 goto error;
881 }
882 self->server_hostname = hostname;
883
884 /* Only send SNI extension for non-IP hostnames */
885 if (ip == NULL) {
886 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
887 _setSSLError(NULL, 0, __FILE__, __LINE__);
888 }
889 }
890 if (self->ctx->check_hostname) {
891 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
892 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200893 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
894 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100895 _setSSLError(NULL, 0, __FILE__, __LINE__);
896 goto error;
897 }
898 } else {
899 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
900 ASN1_STRING_length(ip))) {
901 _setSSLError(NULL, 0, __FILE__, __LINE__);
902 goto error;
903 }
904 }
905 }
906 retval = 0;
907 error:
908 if (ip != NULL) {
909 ASN1_OCTET_STRING_free(ip);
910 }
911 return retval;
912}
913
Antoine Pitrou152efa22010-05-16 18:19:27 +0000914static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100915newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000916 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200917 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100918 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000920{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000921 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100922 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700923 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000924
Antoine Pitrou152efa22010-05-16 18:19:27 +0000925 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000926 if (self == NULL)
927 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100931 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700932 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200933 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200934 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700935 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700936 self->err = err;
Christian Heimesc7f70692019-05-31 11:44:05 +0200937 self->exc_type = NULL;
938 self->exc_value = NULL;
939 self->exc_tb = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000945 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 PySSL_END_ALLOW_THREADS
Zackery Spytz4c49da02018-12-07 03:11:30 -0700947 if (self->ssl == NULL) {
948 Py_DECREF(self);
949 _setSSLError(NULL, 0, __FILE__, __LINE__);
950 return NULL;
951 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200952 SSL_set_app_data(self->ssl, self);
953 if (sock) {
954 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
955 } else {
956 /* BIOs are reference counted and SSL_set_bio borrows our reference.
957 * To prevent a double free in memory_bio_dealloc() we need to take an
958 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200959 BIO_up_ref(inbio->bio);
960 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200961 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
962 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400963 SSL_set_mode(self->ssl,
964 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000965
Christian Heimes61d478c2018-01-27 15:51:38 +0100966 if (server_hostname != NULL) {
967 if (_ssl_configure_hostname(self, server_hostname) < 0) {
968 Py_DECREF(self);
969 return NULL;
970 }
971 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 /* If the socket is in non-blocking mode or timeout mode, set the BIO
973 * to non-blocking mode (blocking is the default)
974 */
Victor Stinnere2452312015-03-28 03:00:46 +0100975 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
977 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
978 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 PySSL_BEGIN_ALLOW_THREADS
981 if (socket_type == PY_SSL_CLIENT)
982 SSL_set_connect_state(self->ssl);
983 else
984 SSL_set_accept_state(self->ssl);
985 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000986
Antoine Pitroud6494802011-07-21 01:11:30 +0200987 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200988 if (sock != NULL) {
989 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
990 if (self->Socket == NULL) {
991 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200992 return NULL;
993 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100994 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100995 if (owner && owner != Py_None) {
996 if (PySSL_set_owner(self, owner, NULL) == -1) {
997 Py_DECREF(self);
998 return NULL;
999 }
1000 }
1001 if (session && session != Py_None) {
1002 if (PySSL_set_session(self, session, NULL) == -1) {
1003 Py_DECREF(self);
1004 return NULL;
1005 }
1006 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001008}
1009
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001010/* SSL object methods */
1011
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001012/*[clinic input]
1013_ssl._SSLSocket.do_handshake
1014[clinic start generated code]*/
1015
1016static PyObject *
1017_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
1018/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001019{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001021 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001023 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001024 _PyTime_t timeout, deadline = 0;
1025 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +00001026
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001027 if (sock) {
1028 if (((PyObject*)sock) == Py_None) {
1029 _setSSLError("Underlying socket connection gone",
1030 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1031 return NULL;
1032 }
1033 Py_INCREF(sock);
1034
1035 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001036 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001037 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1038 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001040
Victor Stinner14690702015-04-06 22:46:13 +02001041 timeout = GET_SOCKET_TIMEOUT(sock);
1042 has_timeout = (timeout > 0);
1043 if (has_timeout)
1044 deadline = _PyTime_GetMonotonicClock() + timeout;
1045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 /* Actually negotiate SSL connection */
1047 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001049 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001051 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001053 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001054
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001055 if (PyErr_CheckSignals())
1056 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001057
Victor Stinner14690702015-04-06 22:46:13 +02001058 if (has_timeout)
1059 timeout = deadline - _PyTime_GetMonotonicClock();
1060
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001061 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001062 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001063 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001064 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 } else {
1066 sockstate = SOCKET_OPERATION_OK;
1067 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001068
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001070 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001071 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001072 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001073 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1074 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001075 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001076 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001077 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1078 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001079 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001080 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1082 break;
1083 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001084 } while (err.ssl == SSL_ERROR_WANT_READ ||
1085 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001086 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001087 if (ret < 1)
1088 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02001089 if (PySSL_ChainExceptions(self) < 0)
1090 return NULL;
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001091 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001092error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001093 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02001094 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001095 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001096}
1097
Thomas Woutersed03b412007-08-28 21:37:11 +00001098static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001099_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1100{
1101 char buf[X509_NAME_MAXLEN];
1102 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001103 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001104 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001105
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001106 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 if (buflen < 0) {
1108 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001109 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001111 /* initial buffer is too small for oid + terminating null byte */
1112 if (buflen > X509_NAME_MAXLEN - 1) {
1113 /* make OBJ_obj2txt() calculate the required buflen */
1114 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1115 /* allocate len + 1 for terminating NULL byte */
1116 namebuf = PyMem_Malloc(buflen + 1);
1117 if (namebuf == NULL) {
1118 PyErr_NoMemory();
1119 return NULL;
1120 }
1121 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1122 if (buflen < 0) {
1123 _setSSLError(NULL, 0, __FILE__, __LINE__);
1124 goto done;
1125 }
1126 }
1127 if (!buflen && no_name) {
1128 Py_INCREF(Py_None);
1129 name_obj = Py_None;
1130 }
1131 else {
1132 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1133 }
1134
1135 done:
1136 if (buf != namebuf) {
1137 PyMem_Free(namebuf);
1138 }
1139 return name_obj;
1140}
1141
1142static PyObject *
1143_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1144{
1145 Py_ssize_t buflen;
1146 unsigned char *valuebuf = NULL;
1147 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1150 if (buflen < 0) {
1151 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001152 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001153 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001154 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001157}
1158
1159static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001161{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1163 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1164 PyObject *rdnt;
1165 PyObject *attr = NULL; /* tuple to hold an attribute */
1166 int entry_count = X509_NAME_entry_count(xname);
1167 X509_NAME_ENTRY *entry;
1168 ASN1_OBJECT *name;
1169 ASN1_STRING *value;
1170 int index_counter;
1171 int rdn_level = -1;
1172 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 dn = PyList_New(0);
1175 if (dn == NULL)
1176 return NULL;
1177 /* now create another tuple to hold the top-level RDN */
1178 rdn = PyList_New(0);
1179 if (rdn == NULL)
1180 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001181
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 for (index_counter = 0;
1183 index_counter < entry_count;
1184 index_counter++)
1185 {
1186 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 /* check to see if we've gotten to a new RDN */
1189 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001190 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001191 /* yes, new RDN */
1192 /* add old RDN to DN */
1193 rdnt = PyList_AsTuple(rdn);
1194 Py_DECREF(rdn);
1195 if (rdnt == NULL)
1196 goto fail0;
1197 retcode = PyList_Append(dn, rdnt);
1198 Py_DECREF(rdnt);
1199 if (retcode < 0)
1200 goto fail0;
1201 /* create new RDN */
1202 rdn = PyList_New(0);
1203 if (rdn == NULL)
1204 goto fail0;
1205 }
1206 }
Christian Heimes598894f2016-09-05 23:19:05 +02001207 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 /* now add this attribute to the current RDN */
1210 name = X509_NAME_ENTRY_get_object(entry);
1211 value = X509_NAME_ENTRY_get_data(entry);
1212 attr = _create_tuple_for_attribute(name, value);
1213 /*
1214 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1215 entry->set,
1216 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1217 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1218 */
1219 if (attr == NULL)
1220 goto fail1;
1221 retcode = PyList_Append(rdn, attr);
1222 Py_DECREF(attr);
1223 if (retcode < 0)
1224 goto fail1;
1225 }
1226 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001227 if (rdn != NULL) {
1228 if (PyList_GET_SIZE(rdn) > 0) {
1229 rdnt = PyList_AsTuple(rdn);
1230 Py_DECREF(rdn);
1231 if (rdnt == NULL)
1232 goto fail0;
1233 retcode = PyList_Append(dn, rdnt);
1234 Py_DECREF(rdnt);
1235 if (retcode < 0)
1236 goto fail0;
1237 }
1238 else {
1239 Py_DECREF(rdn);
1240 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 /* convert list to tuple */
1244 rdnt = PyList_AsTuple(dn);
1245 Py_DECREF(dn);
1246 if (rdnt == NULL)
1247 return NULL;
1248 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249
1250 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252
1253 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 Py_XDECREF(dn);
1255 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256}
1257
1258static PyObject *
1259_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 /* this code follows the procedure outlined in
1262 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1263 function to extract the STACK_OF(GENERAL_NAME),
1264 then iterates through the stack to add the
1265 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001266
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001267 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001269 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001270 GENERAL_NAMES *names = NULL;
1271 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 BIO *biobuf = NULL;
1273 char buf[2048];
1274 char *vptr;
1275 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001276
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 if (certificate == NULL)
1278 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001280 /* get a memory buffer */
1281 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001282 if (biobuf == NULL) {
1283 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1284 return NULL;
1285 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001286
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001287 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1288 certificate, NID_subject_alt_name, NULL, NULL);
1289 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 if (peer_alt_names == Py_None) {
1291 peer_alt_names = PyList_New(0);
1292 if (peer_alt_names == NULL)
1293 goto fail;
1294 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001297 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001298 int gntype;
1299 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001301 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001302 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001303 switch (gntype) {
1304 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 /* we special-case DirName as a tuple of
1306 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001307
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 t = PyTuple_New(2);
1309 if (t == NULL) {
1310 goto fail;
1311 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001313 v = PyUnicode_FromString("DirName");
1314 if (v == NULL) {
1315 Py_DECREF(t);
1316 goto fail;
1317 }
1318 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001320 v = _create_tuple_for_X509_NAME (name->d.dirn);
1321 if (v == NULL) {
1322 Py_DECREF(t);
1323 goto fail;
1324 }
1325 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001326 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001327
Christian Heimes824f7f32013-08-17 00:54:47 +02001328 case GEN_EMAIL:
1329 case GEN_DNS:
1330 case GEN_URI:
1331 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1332 correctly, CVE-2013-4238 */
1333 t = PyTuple_New(2);
1334 if (t == NULL)
1335 goto fail;
1336 switch (gntype) {
1337 case GEN_EMAIL:
1338 v = PyUnicode_FromString("email");
1339 as = name->d.rfc822Name;
1340 break;
1341 case GEN_DNS:
1342 v = PyUnicode_FromString("DNS");
1343 as = name->d.dNSName;
1344 break;
1345 case GEN_URI:
1346 v = PyUnicode_FromString("URI");
1347 as = name->d.uniformResourceIdentifier;
1348 break;
1349 }
1350 if (v == NULL) {
1351 Py_DECREF(t);
1352 goto fail;
1353 }
1354 PyTuple_SET_ITEM(t, 0, v);
1355 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1356 ASN1_STRING_length(as));
1357 if (v == NULL) {
1358 Py_DECREF(t);
1359 goto fail;
1360 }
1361 PyTuple_SET_ITEM(t, 1, v);
1362 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001363
Christian Heimes1c03abd2016-09-06 23:25:35 +02001364 case GEN_RID:
1365 t = PyTuple_New(2);
1366 if (t == NULL)
1367 goto fail;
1368
1369 v = PyUnicode_FromString("Registered ID");
1370 if (v == NULL) {
1371 Py_DECREF(t);
1372 goto fail;
1373 }
1374 PyTuple_SET_ITEM(t, 0, v);
1375
1376 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1377 if (len < 0) {
1378 Py_DECREF(t);
1379 _setSSLError(NULL, 0, __FILE__, __LINE__);
1380 goto fail;
1381 } else if (len >= (int)sizeof(buf)) {
1382 v = PyUnicode_FromString("<INVALID>");
1383 } else {
1384 v = PyUnicode_FromStringAndSize(buf, len);
1385 }
1386 if (v == NULL) {
1387 Py_DECREF(t);
1388 goto fail;
1389 }
1390 PyTuple_SET_ITEM(t, 1, v);
1391 break;
1392
Christian Heimes824f7f32013-08-17 00:54:47 +02001393 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001395 switch (gntype) {
1396 /* check for new general name type */
1397 case GEN_OTHERNAME:
1398 case GEN_X400:
1399 case GEN_EDIPARTY:
1400 case GEN_IPADD:
1401 case GEN_RID:
1402 break;
1403 default:
1404 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1405 "Unknown general name type %d",
1406 gntype) == -1) {
1407 goto fail;
1408 }
1409 break;
1410 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 (void) BIO_reset(biobuf);
1412 GENERAL_NAME_print(biobuf, name);
1413 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1414 if (len < 0) {
1415 _setSSLError(NULL, 0, __FILE__, __LINE__);
1416 goto fail;
1417 }
1418 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001419 if (vptr == NULL) {
1420 PyErr_Format(PyExc_ValueError,
1421 "Invalid value %.200s",
1422 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001424 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 t = PyTuple_New(2);
1426 if (t == NULL)
1427 goto fail;
1428 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1429 if (v == NULL) {
1430 Py_DECREF(t);
1431 goto fail;
1432 }
1433 PyTuple_SET_ITEM(t, 0, v);
1434 v = PyUnicode_FromStringAndSize((vptr + 1),
1435 (len - (vptr - buf + 1)));
1436 if (v == NULL) {
1437 Py_DECREF(t);
1438 goto fail;
1439 }
1440 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001441 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001442 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001444 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001446 if (PyList_Append(peer_alt_names, t) < 0) {
1447 Py_DECREF(t);
1448 goto fail;
1449 }
1450 Py_DECREF(t);
1451 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001452 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 }
1454 BIO_free(biobuf);
1455 if (peer_alt_names != Py_None) {
1456 v = PyList_AsTuple(peer_alt_names);
1457 Py_DECREF(peer_alt_names);
1458 return v;
1459 } else {
1460 return peer_alt_names;
1461 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001462
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463
1464 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001465 if (biobuf != NULL)
1466 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001468 if (peer_alt_names != Py_None) {
1469 Py_XDECREF(peer_alt_names);
1470 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001473}
1474
1475static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001476_get_aia_uri(X509 *certificate, int nid) {
1477 PyObject *lst = NULL, *ostr = NULL;
1478 int i, result;
1479 AUTHORITY_INFO_ACCESS *info;
1480
1481 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001482 if (info == NULL)
1483 return Py_None;
1484 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1485 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001486 return Py_None;
1487 }
1488
1489 if ((lst = PyList_New(0)) == NULL) {
1490 goto fail;
1491 }
1492
1493 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1494 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1495 ASN1_IA5STRING *uri;
1496
1497 if ((OBJ_obj2nid(ad->method) != nid) ||
1498 (ad->location->type != GEN_URI)) {
1499 continue;
1500 }
1501 uri = ad->location->d.uniformResourceIdentifier;
1502 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1503 uri->length);
1504 if (ostr == NULL) {
1505 goto fail;
1506 }
1507 result = PyList_Append(lst, ostr);
1508 Py_DECREF(ostr);
1509 if (result < 0) {
1510 goto fail;
1511 }
1512 }
1513 AUTHORITY_INFO_ACCESS_free(info);
1514
1515 /* convert to tuple or None */
1516 if (PyList_Size(lst) == 0) {
1517 Py_DECREF(lst);
1518 return Py_None;
1519 } else {
1520 PyObject *tup;
1521 tup = PyList_AsTuple(lst);
1522 Py_DECREF(lst);
1523 return tup;
1524 }
1525
1526 fail:
1527 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001528 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 return NULL;
1530}
1531
1532static PyObject *
1533_get_crl_dp(X509 *certificate) {
1534 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001535 int i, j;
1536 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001537
Christian Heimes598894f2016-09-05 23:19:05 +02001538 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001539
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001540 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001541 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001542
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001543 lst = PyList_New(0);
1544 if (lst == NULL)
1545 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001546
1547 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1548 DIST_POINT *dp;
1549 STACK_OF(GENERAL_NAME) *gns;
1550
1551 dp = sk_DIST_POINT_value(dps, i);
Christian Heimesa37f5242019-01-15 23:47:42 +01001552 if (dp->distpoint == NULL) {
1553 /* Ignore empty DP value, CVE-2019-5010 */
1554 continue;
1555 }
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001556 gns = dp->distpoint->name.fullname;
1557
1558 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1559 GENERAL_NAME *gn;
1560 ASN1_IA5STRING *uri;
1561 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001562 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001563
1564 gn = sk_GENERAL_NAME_value(gns, j);
1565 if (gn->type != GEN_URI) {
1566 continue;
1567 }
1568 uri = gn->d.uniformResourceIdentifier;
1569 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1570 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001571 if (ouri == NULL)
1572 goto done;
1573
1574 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001575 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001576 if (err < 0)
1577 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001578 }
1579 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001580
1581 /* Convert to tuple. */
1582 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1583
1584 done:
1585 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001586 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001587 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001588}
1589
1590static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001591_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001592
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 PyObject *retval = NULL;
1594 BIO *biobuf = NULL;
1595 PyObject *peer;
1596 PyObject *peer_alt_names = NULL;
1597 PyObject *issuer;
1598 PyObject *version;
1599 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001600 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 ASN1_INTEGER *serialNumber;
1602 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001603 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 ASN1_TIME *notBefore, *notAfter;
1605 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001606
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 retval = PyDict_New();
1608 if (retval == NULL)
1609 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001611 peer = _create_tuple_for_X509_NAME(
1612 X509_get_subject_name(certificate));
1613 if (peer == NULL)
1614 goto fail0;
1615 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1616 Py_DECREF(peer);
1617 goto fail0;
1618 }
1619 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001620
Antoine Pitroufb046912010-11-09 20:21:19 +00001621 issuer = _create_tuple_for_X509_NAME(
1622 X509_get_issuer_name(certificate));
1623 if (issuer == NULL)
1624 goto fail0;
1625 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001627 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001629 Py_DECREF(issuer);
1630
1631 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001632 if (version == NULL)
1633 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001634 if (PyDict_SetItemString(retval, "version", version) < 0) {
1635 Py_DECREF(version);
1636 goto fail0;
1637 }
1638 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001640 /* get a memory buffer */
1641 biobuf = BIO_new(BIO_s_mem());
Zackery Spytz4c49da02018-12-07 03:11:30 -07001642 if (biobuf == NULL) {
1643 PyErr_SetString(PySSLErrorObject, "failed to allocate BIO");
1644 goto fail0;
1645 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001646
Antoine Pitroufb046912010-11-09 20:21:19 +00001647 (void) BIO_reset(biobuf);
1648 serialNumber = X509_get_serialNumber(certificate);
1649 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1650 i2a_ASN1_INTEGER(biobuf, serialNumber);
1651 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1652 if (len < 0) {
1653 _setSSLError(NULL, 0, __FILE__, __LINE__);
1654 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001656 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1657 if (sn_obj == NULL)
1658 goto fail1;
1659 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1660 Py_DECREF(sn_obj);
1661 goto fail1;
1662 }
1663 Py_DECREF(sn_obj);
1664
1665 (void) BIO_reset(biobuf);
1666 notBefore = X509_get_notBefore(certificate);
1667 ASN1_TIME_print(biobuf, notBefore);
1668 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1669 if (len < 0) {
1670 _setSSLError(NULL, 0, __FILE__, __LINE__);
1671 goto fail1;
1672 }
1673 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1674 if (pnotBefore == NULL)
1675 goto fail1;
1676 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1677 Py_DECREF(pnotBefore);
1678 goto fail1;
1679 }
1680 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001681
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001682 (void) BIO_reset(biobuf);
1683 notAfter = X509_get_notAfter(certificate);
1684 ASN1_TIME_print(biobuf, notAfter);
1685 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1686 if (len < 0) {
1687 _setSSLError(NULL, 0, __FILE__, __LINE__);
1688 goto fail1;
1689 }
1690 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1691 if (pnotAfter == NULL)
1692 goto fail1;
1693 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1694 Py_DECREF(pnotAfter);
1695 goto fail1;
1696 }
1697 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 peer_alt_names = _get_peer_alt_names(certificate);
1702 if (peer_alt_names == NULL)
1703 goto fail1;
1704 else if (peer_alt_names != Py_None) {
1705 if (PyDict_SetItemString(retval, "subjectAltName",
1706 peer_alt_names) < 0) {
1707 Py_DECREF(peer_alt_names);
1708 goto fail1;
1709 }
1710 Py_DECREF(peer_alt_names);
1711 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001712
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001713 /* Authority Information Access: OCSP URIs */
1714 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1715 if (obj == NULL) {
1716 goto fail1;
1717 } else if (obj != Py_None) {
1718 result = PyDict_SetItemString(retval, "OCSP", obj);
1719 Py_DECREF(obj);
1720 if (result < 0) {
1721 goto fail1;
1722 }
1723 }
1724
1725 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1726 if (obj == NULL) {
1727 goto fail1;
1728 } else if (obj != Py_None) {
1729 result = PyDict_SetItemString(retval, "caIssuers", obj);
1730 Py_DECREF(obj);
1731 if (result < 0) {
1732 goto fail1;
1733 }
1734 }
1735
1736 /* CDP (CRL distribution points) */
1737 obj = _get_crl_dp(certificate);
1738 if (obj == NULL) {
1739 goto fail1;
1740 } else if (obj != Py_None) {
1741 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1742 Py_DECREF(obj);
1743 if (result < 0) {
1744 goto fail1;
1745 }
1746 }
1747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 BIO_free(biobuf);
1749 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001750
1751 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 if (biobuf != NULL)
1753 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001754 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001755 Py_XDECREF(retval);
1756 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001757}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001758
Christian Heimes9a5395a2013-06-17 15:44:12 +02001759static PyObject *
1760_certificate_to_der(X509 *certificate)
1761{
1762 unsigned char *bytes_buf = NULL;
1763 int len;
1764 PyObject *retval;
1765
1766 bytes_buf = NULL;
1767 len = i2d_X509(certificate, &bytes_buf);
1768 if (len < 0) {
1769 _setSSLError(NULL, 0, __FILE__, __LINE__);
1770 return NULL;
1771 }
1772 /* this is actually an immutable bytes sequence */
1773 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1774 OPENSSL_free(bytes_buf);
1775 return retval;
1776}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001778/*[clinic input]
1779_ssl._test_decode_cert
1780 path: object(converter="PyUnicode_FSConverter")
1781 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001783[clinic start generated code]*/
1784
1785static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001786_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1787/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001788{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 X509 *x=NULL;
1791 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1794 PyErr_SetString(PySSLErrorObject,
1795 "Can't malloc memory to read file");
1796 goto fail0;
1797 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001798
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001799 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 PyErr_SetString(PySSLErrorObject,
1801 "Can't open file");
1802 goto fail0;
1803 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1806 if (x == NULL) {
1807 PyErr_SetString(PySSLErrorObject,
1808 "Error decoding PEM-encoded file");
1809 goto fail0;
1810 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001811
Antoine Pitroufb046912010-11-09 20:21:19 +00001812 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001813 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814
1815 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001816 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 if (cert != NULL) BIO_free(cert);
1818 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001819}
1820
1821
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001822/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001823_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001824 der as binary_mode: bool = False
1825 /
1826
1827Returns the certificate for the peer.
1828
1829If no certificate was provided, returns None. If a certificate was
1830provided, but not validated, returns an empty dictionary. Otherwise
1831returns a dict containing information about the peer certificate.
1832
1833If the optional argument is True, returns a DER-encoded copy of the
1834peer certificate, or None if no certificate was provided. This will
1835return the certificate even if it wasn't validated.
1836[clinic start generated code]*/
1837
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001838static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001839_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1840/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001841{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001843 X509 *peer_cert;
1844 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001845
Christian Heimes66dc33b2017-05-23 16:02:02 -07001846 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001847 PyErr_SetString(PyExc_ValueError,
1848 "handshake not done yet");
1849 return NULL;
1850 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001851 peer_cert = SSL_get_peer_certificate(self->ssl);
1852 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001854
Antoine Pitrou721738f2012-08-15 23:20:39 +02001855 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001856 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001857 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001859 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001860 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001861 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001862 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001863 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001864 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001865 X509_free(peer_cert);
1866 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001867}
1868
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001869static PyObject *
1870cipher_to_tuple(const SSL_CIPHER *cipher)
1871{
1872 const char *cipher_name, *cipher_protocol;
1873 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001874 if (retval == NULL)
1875 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001876
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001877 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001878 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001879 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 PyTuple_SET_ITEM(retval, 0, Py_None);
1881 } else {
1882 v = PyUnicode_FromString(cipher_name);
1883 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001884 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001885 PyTuple_SET_ITEM(retval, 0, v);
1886 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001887
1888 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001890 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 PyTuple_SET_ITEM(retval, 1, Py_None);
1892 } else {
1893 v = PyUnicode_FromString(cipher_protocol);
1894 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001895 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 PyTuple_SET_ITEM(retval, 1, v);
1897 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001898
1899 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001900 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001901 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001902 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001905
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001906 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 Py_DECREF(retval);
1908 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001909}
1910
Christian Heimes25bfcd52016-09-06 00:04:45 +02001911#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1912static PyObject *
1913cipher_to_dict(const SSL_CIPHER *cipher)
1914{
1915 const char *cipher_name, *cipher_protocol;
1916
1917 unsigned long cipher_id;
1918 int alg_bits, strength_bits, len;
1919 char buf[512] = {0};
1920#if OPENSSL_VERSION_1_1
1921 int aead, nid;
1922 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1923#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001924
1925 /* can be NULL */
1926 cipher_name = SSL_CIPHER_get_name(cipher);
1927 cipher_protocol = SSL_CIPHER_get_version(cipher);
1928 cipher_id = SSL_CIPHER_get_id(cipher);
1929 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001930 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1931 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001932 if (len > 1 && buf[len-1] == '\n')
1933 buf[len-1] = '\0';
1934 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1935
1936#if OPENSSL_VERSION_1_1
1937 aead = SSL_CIPHER_is_aead(cipher);
1938 nid = SSL_CIPHER_get_cipher_nid(cipher);
1939 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1940 nid = SSL_CIPHER_get_digest_nid(cipher);
1941 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1942 nid = SSL_CIPHER_get_kx_nid(cipher);
1943 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1944 nid = SSL_CIPHER_get_auth_nid(cipher);
1945 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1946#endif
1947
Victor Stinner410b9882016-09-12 12:00:23 +02001948 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001949 "{sksssssssisi"
1950#if OPENSSL_VERSION_1_1
1951 "sOssssssss"
1952#endif
1953 "}",
1954 "id", cipher_id,
1955 "name", cipher_name,
1956 "protocol", cipher_protocol,
1957 "description", buf,
1958 "strength_bits", strength_bits,
1959 "alg_bits", alg_bits
1960#if OPENSSL_VERSION_1_1
1961 ,"aead", aead ? Py_True : Py_False,
1962 "symmetric", skcipher,
1963 "digest", digest,
1964 "kea", kx,
1965 "auth", auth
1966#endif
1967 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001968}
1969#endif
1970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001971/*[clinic input]
1972_ssl._SSLSocket.shared_ciphers
1973[clinic start generated code]*/
1974
1975static PyObject *
1976_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1977/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001978{
1979 STACK_OF(SSL_CIPHER) *ciphers;
1980 int i;
1981 PyObject *res;
1982
Christian Heimes598894f2016-09-05 23:19:05 +02001983 ciphers = SSL_get_ciphers(self->ssl);
1984 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001985 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001986 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1987 if (!res)
1988 return NULL;
1989 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1990 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1991 if (!tup) {
1992 Py_DECREF(res);
1993 return NULL;
1994 }
1995 PyList_SET_ITEM(res, i, tup);
1996 }
1997 return res;
1998}
1999
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000/*[clinic input]
2001_ssl._SSLSocket.cipher
2002[clinic start generated code]*/
2003
2004static PyObject *
2005_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
2006/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06002007{
2008 const SSL_CIPHER *current;
2009
2010 if (self->ssl == NULL)
2011 Py_RETURN_NONE;
2012 current = SSL_get_current_cipher(self->ssl);
2013 if (current == NULL)
2014 Py_RETURN_NONE;
2015 return cipher_to_tuple(current);
2016}
2017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002018/*[clinic input]
2019_ssl._SSLSocket.version
2020[clinic start generated code]*/
2021
2022static PyObject *
2023_ssl__SSLSocket_version_impl(PySSLSocket *self)
2024/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02002025{
2026 const char *version;
2027
2028 if (self->ssl == NULL)
2029 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07002030 if (!SSL_is_init_finished(self->ssl)) {
2031 /* handshake not finished */
2032 Py_RETURN_NONE;
2033 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02002034 version = SSL_get_version(self->ssl);
2035 if (!strcmp(version, "unknown"))
2036 Py_RETURN_NONE;
2037 return PyUnicode_FromString(version);
2038}
2039
Christian Heimes29eab552018-02-25 12:31:33 +01002040#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002041/*[clinic input]
2042_ssl._SSLSocket.selected_npn_protocol
2043[clinic start generated code]*/
2044
2045static PyObject *
2046_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
2047/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
2048{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002049 const unsigned char *out;
2050 unsigned int outlen;
2051
Victor Stinner4569cd52013-06-23 14:58:43 +02002052 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002053 &out, &outlen);
2054
2055 if (out == NULL)
2056 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002057 return PyUnicode_FromStringAndSize((char *)out, outlen);
2058}
2059#endif
2060
Christian Heimes29eab552018-02-25 12:31:33 +01002061#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002062/*[clinic input]
2063_ssl._SSLSocket.selected_alpn_protocol
2064[clinic start generated code]*/
2065
2066static PyObject *
2067_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2068/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2069{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002070 const unsigned char *out;
2071 unsigned int outlen;
2072
2073 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2074
2075 if (out == NULL)
2076 Py_RETURN_NONE;
2077 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002078}
2079#endif
2080
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002081/*[clinic input]
2082_ssl._SSLSocket.compression
2083[clinic start generated code]*/
2084
2085static PyObject *
2086_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2087/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2088{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002089#ifdef OPENSSL_NO_COMP
2090 Py_RETURN_NONE;
2091#else
2092 const COMP_METHOD *comp_method;
2093 const char *short_name;
2094
2095 if (self->ssl == NULL)
2096 Py_RETURN_NONE;
2097 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002098 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002099 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002100 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002101 if (short_name == NULL)
2102 Py_RETURN_NONE;
2103 return PyUnicode_DecodeFSDefault(short_name);
2104#endif
2105}
2106
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002107static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2108 Py_INCREF(self->ctx);
2109 return self->ctx;
2110}
2111
2112static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2113 void *closure) {
2114
2115 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002116#if !HAVE_SNI
2117 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2118 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002119 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002120#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002121 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002122 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002123 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002124#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002125 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002126 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002127 return -1;
2128 }
2129
2130 return 0;
2131}
2132
2133PyDoc_STRVAR(PySSL_set_context_doc,
2134"_setter_context(ctx)\n\
2135\
2136This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002137used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002138on the SSLContext to change the certificate information associated with the\n\
2139SSLSocket before the cryptographic exchange handshake messages\n");
2140
2141
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002142static PyObject *
2143PySSL_get_server_side(PySSLSocket *self, void *c)
2144{
2145 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2146}
2147
2148PyDoc_STRVAR(PySSL_get_server_side_doc,
2149"Whether this is a server-side socket.");
2150
2151static PyObject *
2152PySSL_get_server_hostname(PySSLSocket *self, void *c)
2153{
2154 if (self->server_hostname == NULL)
2155 Py_RETURN_NONE;
2156 Py_INCREF(self->server_hostname);
2157 return self->server_hostname;
2158}
2159
2160PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2161"The currently set server hostname (for SNI).");
2162
2163static PyObject *
2164PySSL_get_owner(PySSLSocket *self, void *c)
2165{
2166 PyObject *owner;
2167
2168 if (self->owner == NULL)
2169 Py_RETURN_NONE;
2170
2171 owner = PyWeakref_GetObject(self->owner);
2172 Py_INCREF(owner);
2173 return owner;
2174}
2175
2176static int
2177PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2178{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002179 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002180 if (self->owner == NULL)
2181 return -1;
2182 return 0;
2183}
2184
2185PyDoc_STRVAR(PySSL_get_owner_doc,
2186"The Python-level owner of this object.\
2187Passed as \"self\" in servername callback.");
2188
Christian Heimesc7f70692019-05-31 11:44:05 +02002189static int
2190PySSL_traverse(PySSLSocket *self, visitproc visit, void *arg)
2191{
2192 Py_VISIT(self->exc_type);
2193 Py_VISIT(self->exc_value);
2194 Py_VISIT(self->exc_tb);
2195 return 0;
2196}
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002197
Christian Heimesc7f70692019-05-31 11:44:05 +02002198static int
2199PySSL_clear(PySSLSocket *self)
2200{
2201 Py_CLEAR(self->exc_type);
2202 Py_CLEAR(self->exc_value);
2203 Py_CLEAR(self->exc_tb);
2204 return 0;
2205}
2206
2207static void
2208PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002209{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 if (self->ssl)
2211 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002213 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002214 Py_XDECREF(self->server_hostname);
2215 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002217}
2218
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002219/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002220 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002221 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002222 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002223
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002224static int
Victor Stinner14690702015-04-06 22:46:13 +02002225PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002226{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002227 int rc;
2228#ifdef HAVE_POLL
2229 struct pollfd pollfd;
2230 _PyTime_t ms;
2231#else
2232 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 fd_set fds;
2234 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002235#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002238 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002239 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002240 else if (timeout < 0) {
2241 if (s->sock_timeout > 0)
2242 return SOCKET_HAS_TIMED_OUT;
2243 else
2244 return SOCKET_IS_BLOCKING;
2245 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002248 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 /* Prefer poll, if available, since you can poll() any fd
2252 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002253#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002254 pollfd.fd = s->sock_fd;
2255 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002256
Victor Stinner14690702015-04-06 22:46:13 +02002257 /* timeout is in seconds, poll() uses milliseconds */
2258 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002259 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002260
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002261 PySSL_BEGIN_ALLOW_THREADS
2262 rc = poll(&pollfd, 1, (int)ms);
2263 PySSL_END_ALLOW_THREADS
2264#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002266 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002268
Victor Stinner14690702015-04-06 22:46:13 +02002269 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 FD_ZERO(&fds);
2272 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002273
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002274 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002276 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002278 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002280 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002282#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002283
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2285 (when we are able to write or when there's something to read) */
2286 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002287}
2288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002289/*[clinic input]
2290_ssl._SSLSocket.write
2291 b: Py_buffer
2292 /
2293
2294Writes the bytes-like object b into the SSL object.
2295
2296Returns the number of bytes written.
2297[clinic start generated code]*/
2298
2299static PyObject *
2300_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2301/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002302{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 int len;
2304 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002305 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002307 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002308 _PyTime_t timeout, deadline = 0;
2309 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002310
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002311 if (sock != NULL) {
2312 if (((PyObject*)sock) == Py_None) {
2313 _setSSLError("Underlying socket connection gone",
2314 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2315 return NULL;
2316 }
2317 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 }
2319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002320 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002321 PyErr_Format(PyExc_OverflowError,
2322 "string longer than %d bytes", INT_MAX);
2323 goto error;
2324 }
2325
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002326 if (sock != NULL) {
2327 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002328 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002329 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2330 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2331 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332
Victor Stinner14690702015-04-06 22:46:13 +02002333 timeout = GET_SOCKET_TIMEOUT(sock);
2334 has_timeout = (timeout > 0);
2335 if (has_timeout)
2336 deadline = _PyTime_GetMonotonicClock() + timeout;
2337
2338 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002340 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 "The write operation timed out");
2342 goto error;
2343 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2344 PyErr_SetString(PySSLErrorObject,
2345 "Underlying socket has been closed.");
2346 goto error;
2347 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2348 PyErr_SetString(PySSLErrorObject,
2349 "Underlying socket too large for select().");
2350 goto error;
2351 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002352
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002355 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002356 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002358 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002359
2360 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002362
Victor Stinner14690702015-04-06 22:46:13 +02002363 if (has_timeout)
2364 timeout = deadline - _PyTime_GetMonotonicClock();
2365
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002366 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002367 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002368 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002369 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 } else {
2371 sockstate = SOCKET_OPERATION_OK;
2372 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002375 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002376 "The write operation timed out");
2377 goto error;
2378 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2379 PyErr_SetString(PySSLErrorObject,
2380 "Underlying socket has been closed.");
2381 goto error;
2382 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2383 break;
2384 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002385 } while (err.ssl == SSL_ERROR_WANT_READ ||
2386 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002387
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002388 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002389 if (len <= 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 return PySSL_SetError(self, len, __FILE__, __LINE__);
Christian Heimesc7f70692019-05-31 11:44:05 +02002391 if (PySSL_ChainExceptions(self) < 0)
2392 return NULL;
2393 return PyLong_FromLong(len);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002394error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002395 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002396 PySSL_ChainExceptions(self);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002397 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002398}
2399
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002400/*[clinic input]
2401_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002402
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002403Returns the number of already decrypted bytes available for read, pending on the connection.
2404[clinic start generated code]*/
2405
2406static PyObject *
2407_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2408/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002409{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002411 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 PySSL_BEGIN_ALLOW_THREADS
2414 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002415 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002416 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002417 self->err = err;
2418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419 if (count < 0)
2420 return PySSL_SetError(self, count, __FILE__, __LINE__);
2421 else
2422 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002423}
2424
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002425/*[clinic input]
2426_ssl._SSLSocket.read
2427 size as len: int
2428 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002429 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002430 ]
2431 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002432
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002433Read up to size bytes from the SSL socket.
2434[clinic start generated code]*/
2435
2436static PyObject *
2437_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2438 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002439/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002440{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002443 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002444 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002445 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002447 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002448 _PyTime_t timeout, deadline = 0;
2449 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002450
Martin Panter5503d472016-03-27 05:35:19 +00002451 if (!group_right_1 && len < 0) {
2452 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2453 return NULL;
2454 }
2455
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002456 if (sock != NULL) {
2457 if (((PyObject*)sock) == Py_None) {
2458 _setSSLError("Underlying socket connection gone",
2459 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2460 return NULL;
2461 }
2462 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002463 }
2464
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002465 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002466 dest = PyBytes_FromStringAndSize(NULL, len);
2467 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002468 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002469 if (len == 0) {
2470 Py_XDECREF(sock);
2471 return dest;
2472 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002473 mem = PyBytes_AS_STRING(dest);
2474 }
2475 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002476 mem = buffer->buf;
2477 if (len <= 0 || len > buffer->len) {
2478 len = (int) buffer->len;
2479 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002480 PyErr_SetString(PyExc_OverflowError,
2481 "maximum length can't fit in a C 'int'");
2482 goto error;
2483 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002484 if (len == 0) {
2485 count = 0;
2486 goto done;
2487 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002488 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002489 }
2490
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002491 if (sock != NULL) {
2492 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002493 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002494 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2495 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2496 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497
Victor Stinner14690702015-04-06 22:46:13 +02002498 timeout = GET_SOCKET_TIMEOUT(sock);
2499 has_timeout = (timeout > 0);
2500 if (has_timeout)
2501 deadline = _PyTime_GetMonotonicClock() + timeout;
2502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002503 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504 PySSL_BEGIN_ALLOW_THREADS
2505 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002506 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002507 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002508 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510 if (PyErr_CheckSignals())
2511 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002512
Victor Stinner14690702015-04-06 22:46:13 +02002513 if (has_timeout)
2514 timeout = deadline - _PyTime_GetMonotonicClock();
2515
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002516 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002517 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002518 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002519 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002520 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002521 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 {
2523 count = 0;
2524 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002526 else
2527 sockstate = SOCKET_OPERATION_OK;
2528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002529 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002530 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 "The read operation timed out");
2532 goto error;
2533 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2534 break;
2535 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002536 } while (err.ssl == SSL_ERROR_WANT_READ ||
2537 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 if (count <= 0) {
2540 PySSL_SetError(self, count, __FILE__, __LINE__);
2541 goto error;
2542 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002543 if (self->exc_type != NULL)
2544 goto error;
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002545
2546done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002547 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002548 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002549 _PyBytes_Resize(&dest, count);
2550 return dest;
2551 }
2552 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 return PyLong_FromLong(count);
2554 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002555
2556error:
Christian Heimesc7f70692019-05-31 11:44:05 +02002557 PySSL_ChainExceptions(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002558 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002559 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002560 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002562}
2563
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002564/*[clinic input]
2565_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002566
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002567Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002568[clinic start generated code]*/
2569
2570static PyObject *
2571_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002572/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002573{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002574 _PySSLError err;
2575 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002577 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002578 _PyTime_t timeout, deadline = 0;
2579 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002580
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002581 if (sock != NULL) {
2582 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002583 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002584 _setSSLError("Underlying socket connection gone",
2585 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2586 return NULL;
2587 }
2588 Py_INCREF(sock);
2589
2590 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002591 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002592 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2593 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002594 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002595
Victor Stinner14690702015-04-06 22:46:13 +02002596 timeout = GET_SOCKET_TIMEOUT(sock);
2597 has_timeout = (timeout > 0);
2598 if (has_timeout)
2599 deadline = _PyTime_GetMonotonicClock() + timeout;
2600
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002601 while (1) {
2602 PySSL_BEGIN_ALLOW_THREADS
2603 /* Disable read-ahead so that unwrap can work correctly.
2604 * Otherwise OpenSSL might read in too much data,
2605 * eating clear text data that happens to be
2606 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002607 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002608 * function is used and the shutdown_seen_zero != 0
2609 * condition is met.
2610 */
2611 if (self->shutdown_seen_zero)
2612 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002613 ret = SSL_shutdown(self->ssl);
2614 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002615 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002616 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002617
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002618 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002619 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002620 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002621 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002622 /* Don't loop endlessly; instead preserve legacy
2623 behaviour of trying SSL_shutdown() only twice.
2624 This looks necessary for OpenSSL < 0.9.8m */
2625 if (++zeros > 1)
2626 break;
2627 /* Shutdown was sent, now try receiving */
2628 self->shutdown_seen_zero = 1;
2629 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002630 }
2631
Victor Stinner14690702015-04-06 22:46:13 +02002632 if (has_timeout)
2633 timeout = deadline - _PyTime_GetMonotonicClock();
2634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002636 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002637 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002638 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002639 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002640 else
2641 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002643 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002644 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002645 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002646 "The read operation timed out");
2647 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002648 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002649 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002650 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002651 }
2652 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2653 PyErr_SetString(PySSLErrorObject,
2654 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002655 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002656 }
2657 else if (sockstate != SOCKET_OPERATION_OK)
2658 /* Retain the SSL error code */
2659 break;
2660 }
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002661 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002662 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002663 PySSL_SetError(self, ret, __FILE__, __LINE__);
2664 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002665 }
Christian Heimesc7f70692019-05-31 11:44:05 +02002666 if (self->exc_type != NULL)
2667 goto error;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002668 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002669 /* It's already INCREF'ed */
2670 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002671 else
2672 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002673
2674error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002675 Py_XDECREF(sock);
Christian Heimesc7f70692019-05-31 11:44:05 +02002676 PySSL_ChainExceptions(self);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002677 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002678}
2679
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002680/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002681_ssl._SSLSocket.get_channel_binding
2682 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002683
Christian Heimes141c5e82018-02-24 21:10:57 +01002684Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002685
Christian Heimes141c5e82018-02-24 21:10:57 +01002686Raise ValueError if the requested `cb_type` is not supported. Return bytes
2687of the data or None if the data is not available (e.g. before the handshake).
2688Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002689[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002690
Antoine Pitroud6494802011-07-21 01:11:30 +02002691static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002692_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2693 const char *cb_type)
2694/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002695{
Antoine Pitroud6494802011-07-21 01:11:30 +02002696 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002697 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002698
Christian Heimes141c5e82018-02-24 21:10:57 +01002699 if (strcmp(cb_type, "tls-unique") == 0) {
2700 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2701 /* if session is resumed XOR we are the client */
2702 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2703 }
2704 else {
2705 /* if a new session XOR we are the server */
2706 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2707 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002708 }
2709 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002710 PyErr_Format(
2711 PyExc_ValueError,
2712 "'%s' channel binding type not implemented",
2713 cb_type
2714 );
2715 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002716 }
2717
2718 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002719 if (len == 0)
2720 Py_RETURN_NONE;
2721
Christian Heimes141c5e82018-02-24 21:10:57 +01002722 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002723}
2724
Christian Heimes9fb051f2018-09-23 08:32:31 +02002725/*[clinic input]
2726_ssl._SSLSocket.verify_client_post_handshake
2727
2728Initiate TLS 1.3 post-handshake authentication
2729[clinic start generated code]*/
2730
2731static PyObject *
2732_ssl__SSLSocket_verify_client_post_handshake_impl(PySSLSocket *self)
2733/*[clinic end generated code: output=532147f3b1341425 input=6bfa874810a3d889]*/
2734{
2735#ifdef TLS1_3_VERSION
2736 int err = SSL_verify_client_post_handshake(self->ssl);
2737 if (err == 0)
2738 return _setSSLError(NULL, 0, __FILE__, __LINE__);
2739 else
2740 Py_RETURN_NONE;
2741#else
2742 PyErr_SetString(PyExc_NotImplementedError,
2743 "Post-handshake auth is not supported by your "
2744 "OpenSSL version.");
2745 return NULL;
2746#endif
2747}
2748
Christian Heimes99a65702016-09-10 23:44:53 +02002749#ifdef OPENSSL_VERSION_1_1
2750
2751static SSL_SESSION*
2752_ssl_session_dup(SSL_SESSION *session) {
2753 SSL_SESSION *newsession = NULL;
2754 int slen;
2755 unsigned char *senc = NULL, *p;
2756 const unsigned char *const_p;
2757
2758 if (session == NULL) {
2759 PyErr_SetString(PyExc_ValueError, "Invalid session");
2760 goto error;
2761 }
2762
2763 /* get length */
2764 slen = i2d_SSL_SESSION(session, NULL);
2765 if (slen == 0 || slen > 0xFF00) {
2766 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2767 goto error;
2768 }
2769 if ((senc = PyMem_Malloc(slen)) == NULL) {
2770 PyErr_NoMemory();
2771 goto error;
2772 }
2773 p = senc;
2774 if (!i2d_SSL_SESSION(session, &p)) {
2775 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2776 goto error;
2777 }
2778 const_p = senc;
2779 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2780 if (session == NULL) {
2781 goto error;
2782 }
2783 PyMem_Free(senc);
2784 return newsession;
2785 error:
2786 if (senc != NULL) {
2787 PyMem_Free(senc);
2788 }
2789 return NULL;
2790}
2791#endif
2792
2793static PyObject *
2794PySSL_get_session(PySSLSocket *self, void *closure) {
2795 /* get_session can return sessions from a server-side connection,
2796 * it does not check for handshake done or client socket. */
2797 PySSLSession *pysess;
2798 SSL_SESSION *session;
2799
2800#ifdef OPENSSL_VERSION_1_1
2801 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2802 * https://github.com/openssl/openssl/issues/1550 */
2803 session = SSL_get0_session(self->ssl); /* borrowed reference */
2804 if (session == NULL) {
2805 Py_RETURN_NONE;
2806 }
2807 if ((session = _ssl_session_dup(session)) == NULL) {
2808 return NULL;
2809 }
2810#else
2811 session = SSL_get1_session(self->ssl);
2812 if (session == NULL) {
2813 Py_RETURN_NONE;
2814 }
2815#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002816 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002817 if (pysess == NULL) {
2818 SSL_SESSION_free(session);
2819 return NULL;
2820 }
2821
2822 assert(self->ctx);
2823 pysess->ctx = self->ctx;
2824 Py_INCREF(pysess->ctx);
2825 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002826 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002827 return (PyObject *)pysess;
2828}
2829
2830static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2831 void *closure)
2832 {
2833 PySSLSession *pysess;
2834#ifdef OPENSSL_VERSION_1_1
2835 SSL_SESSION *session;
2836#endif
2837 int result;
2838
2839 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002840 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002841 return -1;
2842 }
2843 pysess = (PySSLSession *)value;
2844
2845 if (self->ctx->ctx != pysess->ctx->ctx) {
2846 PyErr_SetString(PyExc_ValueError,
2847 "Session refers to a different SSLContext.");
2848 return -1;
2849 }
2850 if (self->socket_type != PY_SSL_CLIENT) {
2851 PyErr_SetString(PyExc_ValueError,
2852 "Cannot set session for server-side SSLSocket.");
2853 return -1;
2854 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002855 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002856 PyErr_SetString(PyExc_ValueError,
2857 "Cannot set session after handshake.");
2858 return -1;
2859 }
2860#ifdef OPENSSL_VERSION_1_1
2861 /* duplicate session */
2862 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2863 return -1;
2864 }
2865 result = SSL_set_session(self->ssl, session);
2866 /* free duplicate, SSL_set_session() bumps ref count */
2867 SSL_SESSION_free(session);
2868#else
2869 result = SSL_set_session(self->ssl, pysess->session);
2870#endif
2871 if (result == 0) {
2872 _setSSLError(NULL, 0, __FILE__, __LINE__);
2873 return -1;
2874 }
2875 return 0;
2876}
2877
2878PyDoc_STRVAR(PySSL_set_session_doc,
2879"_setter_session(session)\n\
2880\
2881Get / set SSLSession.");
2882
2883static PyObject *
2884PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2885 if (SSL_session_reused(self->ssl)) {
2886 Py_RETURN_TRUE;
2887 } else {
2888 Py_RETURN_FALSE;
2889 }
2890}
2891
2892PyDoc_STRVAR(PySSL_get_session_reused_doc,
2893"Was the client session reused during handshake?");
2894
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002895static PyGetSetDef ssl_getsetlist[] = {
2896 {"context", (getter) PySSL_get_context,
2897 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002898 {"server_side", (getter) PySSL_get_server_side, NULL,
2899 PySSL_get_server_side_doc},
2900 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2901 PySSL_get_server_hostname_doc},
2902 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2903 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002904 {"session", (getter) PySSL_get_session,
2905 (setter) PySSL_set_session, PySSL_set_session_doc},
2906 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2907 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002908 {NULL}, /* sentinel */
2909};
2910
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002911static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002912 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2913 _SSL__SSLSOCKET_WRITE_METHODDEF
2914 _SSL__SSLSOCKET_READ_METHODDEF
2915 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002916 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2917 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002918 _SSL__SSLSOCKET_CIPHER_METHODDEF
2919 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2920 _SSL__SSLSOCKET_VERSION_METHODDEF
2921 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2922 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2923 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2924 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Christian Heimes9fb051f2018-09-23 08:32:31 +02002925 _SSL__SSLSOCKET_VERIFY_CLIENT_POST_HANDSHAKE_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002926 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002927};
2928
Antoine Pitrou152efa22010-05-16 18:19:27 +00002929static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002930 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002931 "_ssl._SSLSocket", /*tp_name*/
2932 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002933 0, /*tp_itemsize*/
2934 /* methods */
2935 (destructor)PySSL_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002936 0, /*tp_vectorcall_offset*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002937 0, /*tp_getattr*/
2938 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02002939 0, /*tp_as_async*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002940 0, /*tp_repr*/
2941 0, /*tp_as_number*/
2942 0, /*tp_as_sequence*/
2943 0, /*tp_as_mapping*/
2944 0, /*tp_hash*/
2945 0, /*tp_call*/
2946 0, /*tp_str*/
2947 0, /*tp_getattro*/
2948 0, /*tp_setattro*/
2949 0, /*tp_as_buffer*/
2950 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2951 0, /*tp_doc*/
Christian Heimesc7f70692019-05-31 11:44:05 +02002952 (traverseproc) PySSL_traverse, /*tp_traverse*/
2953 (inquiry) PySSL_clear, /*tp_clear*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002954 0, /*tp_richcompare*/
2955 0, /*tp_weaklistoffset*/
2956 0, /*tp_iter*/
2957 0, /*tp_iternext*/
2958 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002959 0, /*tp_members*/
2960 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002961};
2962
Antoine Pitrou152efa22010-05-16 18:19:27 +00002963
2964/*
2965 * _SSLContext objects
2966 */
2967
Christian Heimes5fe668c2016-09-12 00:01:11 +02002968static int
Christian Heimes9fb051f2018-09-23 08:32:31 +02002969_set_verify_mode(PySSLContext *self, enum py_ssl_cert_requirements n)
Christian Heimes5fe668c2016-09-12 00:01:11 +02002970{
2971 int mode;
2972 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2973
2974 switch(n) {
2975 case PY_SSL_CERT_NONE:
2976 mode = SSL_VERIFY_NONE;
2977 break;
2978 case PY_SSL_CERT_OPTIONAL:
2979 mode = SSL_VERIFY_PEER;
2980 break;
2981 case PY_SSL_CERT_REQUIRED:
2982 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2983 break;
2984 default:
2985 PyErr_SetString(PyExc_ValueError,
2986 "invalid value for verify_mode");
2987 return -1;
2988 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02002989#ifdef TLS1_3_VERSION
2990 if (self->post_handshake_auth)
2991 mode |= SSL_VERIFY_POST_HANDSHAKE;
2992#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002993 /* keep current verify cb */
Christian Heimes9fb051f2018-09-23 08:32:31 +02002994 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
2995 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
Christian Heimes5fe668c2016-09-12 00:01:11 +02002996 return 0;
2997}
2998
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002999/*[clinic input]
3000@classmethod
3001_ssl._SSLContext.__new__
3002 protocol as proto_version: int
3003 /
3004[clinic start generated code]*/
3005
Antoine Pitrou152efa22010-05-16 18:19:27 +00003006static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003007_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
3008/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003010 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003011 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003012 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01003013 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02003014 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003015#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003016 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03003017#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003018
Antoine Pitrou152efa22010-05-16 18:19:27 +00003019 PySSL_BEGIN_ALLOW_THREADS
3020 if (proto_version == PY_SSL_VERSION_TLS1)
3021 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01003022#if HAVE_TLSv1_2
3023 else if (proto_version == PY_SSL_VERSION_TLS1_1)
3024 ctx = SSL_CTX_new(TLSv1_1_method());
3025 else if (proto_version == PY_SSL_VERSION_TLS1_2)
3026 ctx = SSL_CTX_new(TLSv1_2_method());
3027#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05003028#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00003029 else if (proto_version == PY_SSL_VERSION_SSL3)
3030 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05003031#endif
Victor Stinner3de49192011-05-09 00:42:58 +02003032#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033 else if (proto_version == PY_SSL_VERSION_SSL2)
3034 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02003035#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02003036 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02003037 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02003038 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
3039 ctx = SSL_CTX_new(TLS_client_method());
3040 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
3041 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00003042 else
3043 proto_version = -1;
3044 PySSL_END_ALLOW_THREADS
3045
3046 if (proto_version == -1) {
3047 PyErr_SetString(PyExc_ValueError,
3048 "invalid protocol version");
3049 return NULL;
3050 }
3051 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07003052 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003053 return NULL;
3054 }
3055
3056 assert(type != NULL && type->tp_alloc != NULL);
3057 self = (PySSLContext *) type->tp_alloc(type, 0);
3058 if (self == NULL) {
3059 SSL_CTX_free(ctx);
3060 return NULL;
3061 }
3062 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01003063 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01003064 self->protocol = proto_version;
Christian Heimesc7f70692019-05-31 11:44:05 +02003065 self->msg_cb = NULL;
3066#ifdef HAVE_OPENSSL_KEYLOG
3067 self->keylog_filename = NULL;
3068 self->keylog_bio = NULL;
3069#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003070#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02003071 self->npn_protocols = NULL;
3072#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003073#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003074 self->alpn_protocols = NULL;
3075#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003076#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003077 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003078#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01003079 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02003080 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
3081 self->check_hostname = 1;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003082 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003083 Py_DECREF(self);
3084 return NULL;
3085 }
3086 } else {
3087 self->check_hostname = 0;
Christian Heimes9fb051f2018-09-23 08:32:31 +02003088 if (_set_verify_mode(self, PY_SSL_CERT_NONE) == -1) {
Christian Heimes5fe668c2016-09-12 00:01:11 +02003089 Py_DECREF(self);
3090 return NULL;
3091 }
3092 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003093 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003094 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
3095 if (proto_version != PY_SSL_VERSION_SSL2)
3096 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08003097 if (proto_version != PY_SSL_VERSION_SSL3)
3098 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02003099 /* Minimal security flags for server and client side context.
3100 * Client sockets ignore server-side parameters. */
3101#ifdef SSL_OP_NO_COMPRESSION
3102 options |= SSL_OP_NO_COMPRESSION;
3103#endif
3104#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
3105 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
3106#endif
3107#ifdef SSL_OP_SINGLE_DH_USE
3108 options |= SSL_OP_SINGLE_DH_USE;
3109#endif
3110#ifdef SSL_OP_SINGLE_ECDH_USE
3111 options |= SSL_OP_SINGLE_ECDH_USE;
3112#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003113 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003114
Semen Zhydenko1295e112017-10-15 21:28:31 +02003115 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003116 * It's far from perfect but gives users a better head start. */
3117 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003118#if PY_SSL_DEFAULT_CIPHERS == 2
3119 /* stick to OpenSSL's default settings */
3120 result = 1;
3121#else
3122 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3123#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003124 } else {
3125 /* SSLv2 needs MD5 */
3126 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3127 }
3128 if (result == 0) {
3129 Py_DECREF(self);
3130 ERR_clear_error();
3131 PyErr_SetString(PySSLErrorObject,
3132 "No cipher can be selected.");
3133 return NULL;
3134 }
3135
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003136#if defined(SSL_MODE_RELEASE_BUFFERS)
3137 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3138 usage for no cost at all. However, don't do this for OpenSSL versions
3139 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3140 2014-0198. I can't find exactly which beta fixed this CVE, so be
3141 conservative and assume it wasn't fixed until release. We do this check
3142 at runtime to avoid problems from the dynamic linker.
3143 See #25672 for more on this. */
3144 libver = SSLeay();
3145 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3146 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3147 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3148 }
3149#endif
3150
3151
Donald Stufft8ae264c2017-03-02 11:45:29 -05003152#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003153 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3154 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003155 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3156 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003157#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003158 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3159#else
3160 {
3161 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3162 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3163 EC_KEY_free(key);
3164 }
3165#endif
3166#endif
3167
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003168#define SID_CTX "Python"
3169 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3170 sizeof(SID_CTX));
3171#undef SID_CTX
3172
Christian Heimes61d478c2018-01-27 15:51:38 +01003173 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003174#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003175 /* Improve trust chain building when cross-signed intermediate
3176 certificates are present. See https://bugs.python.org/issue23476. */
3177 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003178#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003179 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003180
Christian Heimes9fb051f2018-09-23 08:32:31 +02003181#ifdef TLS1_3_VERSION
3182 self->post_handshake_auth = 0;
3183 SSL_CTX_set_post_handshake_auth(self->ctx, self->post_handshake_auth);
3184#endif
3185
Antoine Pitrou152efa22010-05-16 18:19:27 +00003186 return (PyObject *)self;
3187}
3188
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003189static int
3190context_traverse(PySSLContext *self, visitproc visit, void *arg)
3191{
3192#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003193 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003194#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003195 Py_VISIT(self->msg_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003196 return 0;
3197}
3198
3199static int
3200context_clear(PySSLContext *self)
3201{
3202#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003203 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003204#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02003205 Py_CLEAR(self->msg_cb);
3206#ifdef HAVE_OPENSSL_KEYLOG
3207 Py_CLEAR(self->keylog_filename);
3208 if (self->keylog_bio != NULL) {
3209 PySSL_BEGIN_ALLOW_THREADS
3210 BIO_free_all(self->keylog_bio);
3211 PySSL_END_ALLOW_THREADS
3212 self->keylog_bio = NULL;
3213 }
3214#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003215 return 0;
3216}
3217
Antoine Pitrou152efa22010-05-16 18:19:27 +00003218static void
3219context_dealloc(PySSLContext *self)
3220{
INADA Naokia6296d32017-08-24 14:55:17 +09003221 /* bpo-31095: UnTrack is needed before calling any callbacks */
3222 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003223 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003224 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003225#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226 PyMem_FREE(self->npn_protocols);
3227#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003228#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003229 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003230#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003231 Py_TYPE(self)->tp_free(self);
3232}
3233
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003234/*[clinic input]
3235_ssl._SSLContext.set_ciphers
3236 cipherlist: str
3237 /
3238[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003239
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240static PyObject *
3241_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3242/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3243{
3244 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003245 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003246 /* Clearing the error queue is necessary on some OpenSSL versions,
3247 otherwise the error will be reported again when another SSL call
3248 is done. */
3249 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003250 PyErr_SetString(PySSLErrorObject,
3251 "No cipher can be selected.");
3252 return NULL;
3253 }
3254 Py_RETURN_NONE;
3255}
3256
Christian Heimes25bfcd52016-09-06 00:04:45 +02003257#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3258/*[clinic input]
3259_ssl._SSLContext.get_ciphers
3260[clinic start generated code]*/
3261
3262static PyObject *
3263_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3264/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3265{
3266 SSL *ssl = NULL;
3267 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003268 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003269 int i=0;
3270 PyObject *result = NULL, *dct;
3271
3272 ssl = SSL_new(self->ctx);
3273 if (ssl == NULL) {
3274 _setSSLError(NULL, 0, __FILE__, __LINE__);
3275 goto exit;
3276 }
3277 sk = SSL_get_ciphers(ssl);
3278
3279 result = PyList_New(sk_SSL_CIPHER_num(sk));
3280 if (result == NULL) {
3281 goto exit;
3282 }
3283
3284 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3285 cipher = sk_SSL_CIPHER_value(sk, i);
3286 dct = cipher_to_dict(cipher);
3287 if (dct == NULL) {
3288 Py_CLEAR(result);
3289 goto exit;
3290 }
3291 PyList_SET_ITEM(result, i, dct);
3292 }
3293
3294 exit:
3295 if (ssl != NULL)
3296 SSL_free(ssl);
3297 return result;
3298
3299}
3300#endif
3301
3302
Christian Heimes29eab552018-02-25 12:31:33 +01003303#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003304static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003305do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3306 const unsigned char *server_protocols, unsigned int server_protocols_len,
3307 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003308{
Benjamin Peterson88615022015-01-23 17:30:26 -05003309 int ret;
3310 if (client_protocols == NULL) {
3311 client_protocols = (unsigned char *)"";
3312 client_protocols_len = 0;
3313 }
3314 if (server_protocols == NULL) {
3315 server_protocols = (unsigned char *)"";
3316 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003317 }
3318
Benjamin Peterson88615022015-01-23 17:30:26 -05003319 ret = SSL_select_next_proto(out, outlen,
3320 server_protocols, server_protocols_len,
3321 client_protocols, client_protocols_len);
3322 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3323 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003324
3325 return SSL_TLSEXT_ERR_OK;
3326}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003327#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003328
Christian Heimes29eab552018-02-25 12:31:33 +01003329#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003330/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3331static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003332_advertiseNPN_cb(SSL *s,
3333 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003334 void *args)
3335{
3336 PySSLContext *ssl_ctx = (PySSLContext *) args;
3337
3338 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003339 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003340 *len = 0;
3341 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003342 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003343 *len = ssl_ctx->npn_protocols_len;
3344 }
3345
3346 return SSL_TLSEXT_ERR_OK;
3347}
3348/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3349static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003350_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003351 unsigned char **out, unsigned char *outlen,
3352 const unsigned char *server, unsigned int server_len,
3353 void *args)
3354{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003355 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003356 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003357 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003358}
3359#endif
3360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003361/*[clinic input]
3362_ssl._SSLContext._set_npn_protocols
3363 protos: Py_buffer
3364 /
3365[clinic start generated code]*/
3366
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003367static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003368_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3369 Py_buffer *protos)
3370/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003371{
Christian Heimes29eab552018-02-25 12:31:33 +01003372#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003373 PyMem_Free(self->npn_protocols);
3374 self->npn_protocols = PyMem_Malloc(protos->len);
3375 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003376 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003377 memcpy(self->npn_protocols, protos->buf, protos->len);
3378 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003379
3380 /* set both server and client callbacks, because the context can
3381 * be used to create both types of sockets */
3382 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3383 _advertiseNPN_cb,
3384 self);
3385 SSL_CTX_set_next_proto_select_cb(self->ctx,
3386 _selectNPN_cb,
3387 self);
3388
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003389 Py_RETURN_NONE;
3390#else
3391 PyErr_SetString(PyExc_NotImplementedError,
3392 "The NPN extension requires OpenSSL 1.0.1 or later.");
3393 return NULL;
3394#endif
3395}
3396
Christian Heimes29eab552018-02-25 12:31:33 +01003397#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003398static int
3399_selectALPN_cb(SSL *s,
3400 const unsigned char **out, unsigned char *outlen,
3401 const unsigned char *client_protocols, unsigned int client_protocols_len,
3402 void *args)
3403{
3404 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003405 return do_protocol_selection(1, (unsigned char **)out, outlen,
3406 ctx->alpn_protocols, ctx->alpn_protocols_len,
3407 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003408}
3409#endif
3410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003411/*[clinic input]
3412_ssl._SSLContext._set_alpn_protocols
3413 protos: Py_buffer
3414 /
3415[clinic start generated code]*/
3416
Benjamin Petersoncca27322015-01-23 16:35:37 -05003417static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003418_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3419 Py_buffer *protos)
3420/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003421{
Christian Heimes29eab552018-02-25 12:31:33 +01003422#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003423 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003424 PyErr_Format(PyExc_OverflowError,
Serhiy Storchakad53fe5f2019-03-13 22:59:55 +02003425 "protocols longer than %u bytes", UINT_MAX);
Segev Finer5cff6372017-07-27 01:19:17 +03003426 return NULL;
3427 }
3428
Benjamin Petersoncca27322015-01-23 16:35:37 -05003429 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003430 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003431 if (!self->alpn_protocols)
3432 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003433 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003434 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003435
3436 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3437 return PyErr_NoMemory();
3438 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3439
Benjamin Petersoncca27322015-01-23 16:35:37 -05003440 Py_RETURN_NONE;
3441#else
3442 PyErr_SetString(PyExc_NotImplementedError,
3443 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3444 return NULL;
3445#endif
3446}
3447
Antoine Pitrou152efa22010-05-16 18:19:27 +00003448static PyObject *
3449get_verify_mode(PySSLContext *self, void *c)
3450{
Christian Heimes9fb051f2018-09-23 08:32:31 +02003451 /* ignore SSL_VERIFY_CLIENT_ONCE and SSL_VERIFY_POST_HANDSHAKE */
3452 int mask = (SSL_VERIFY_NONE | SSL_VERIFY_PEER |
3453 SSL_VERIFY_FAIL_IF_NO_PEER_CERT);
3454 switch (SSL_CTX_get_verify_mode(self->ctx) & mask) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003455 case SSL_VERIFY_NONE:
3456 return PyLong_FromLong(PY_SSL_CERT_NONE);
3457 case SSL_VERIFY_PEER:
3458 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3459 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3460 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3461 }
3462 PyErr_SetString(PySSLErrorObject,
3463 "invalid return value from SSL_CTX_get_verify_mode");
3464 return NULL;
3465}
3466
3467static int
3468set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3469{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003470 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003471 if (!PyArg_Parse(arg, "i", &n))
3472 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003473 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003474 PyErr_SetString(PyExc_ValueError,
3475 "Cannot set verify_mode to CERT_NONE when "
3476 "check_hostname is enabled.");
3477 return -1;
3478 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003479 return _set_verify_mode(self, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003480}
3481
3482static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003483get_verify_flags(PySSLContext *self, void *c)
3484{
Christian Heimes598894f2016-09-05 23:19:05 +02003485 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003486 unsigned long flags;
3487
Christian Heimes61d478c2018-01-27 15:51:38 +01003488 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003489 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003490 return PyLong_FromUnsignedLong(flags);
3491}
3492
3493static int
3494set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3495{
Christian Heimes598894f2016-09-05 23:19:05 +02003496 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003497 unsigned long new_flags, flags, set, clear;
3498
3499 if (!PyArg_Parse(arg, "k", &new_flags))
3500 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003501 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003502 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003503 clear = flags & ~new_flags;
3504 set = ~flags & new_flags;
3505 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003506 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003507 _setSSLError(NULL, 0, __FILE__, __LINE__);
3508 return -1;
3509 }
3510 }
3511 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003512 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003513 _setSSLError(NULL, 0, __FILE__, __LINE__);
3514 return -1;
3515 }
3516 }
3517 return 0;
3518}
3519
Christian Heimes698dde12018-02-27 11:54:43 +01003520/* Getter and setter for protocol version */
3521#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3522
3523
3524static int
3525set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3526{
3527 long v;
3528 int result;
3529
3530 if (!PyArg_Parse(arg, "l", &v))
3531 return -1;
3532 if (v > INT_MAX) {
3533 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3534 return -1;
3535 }
3536
3537 switch(self->protocol) {
3538 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3539 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3540 case PY_SSL_VERSION_TLS:
3541 break;
3542 default:
3543 PyErr_SetString(
3544 PyExc_ValueError,
3545 "The context's protocol doesn't support modification of "
3546 "highest and lowest version."
3547 );
3548 return -1;
3549 }
3550
3551 if (what == 0) {
3552 switch(v) {
3553 case PY_PROTO_MINIMUM_SUPPORTED:
3554 v = 0;
3555 break;
3556 case PY_PROTO_MAXIMUM_SUPPORTED:
3557 /* Emulate max for set_min_proto_version */
3558 v = PY_PROTO_MAXIMUM_AVAILABLE;
3559 break;
3560 default:
3561 break;
3562 }
3563 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3564 }
3565 else {
3566 switch(v) {
3567 case PY_PROTO_MAXIMUM_SUPPORTED:
3568 v = 0;
3569 break;
3570 case PY_PROTO_MINIMUM_SUPPORTED:
3571 /* Emulate max for set_min_proto_version */
3572 v = PY_PROTO_MINIMUM_AVAILABLE;
3573 break;
3574 default:
3575 break;
3576 }
3577 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3578 }
3579 if (result == 0) {
3580 PyErr_Format(PyExc_ValueError,
3581 "Unsupported protocol version 0x%x", v);
3582 return -1;
3583 }
3584 return 0;
3585}
3586
3587static PyObject *
3588get_minimum_version(PySSLContext *self, void *c)
3589{
3590 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3591 if (v == 0) {
3592 v = PY_PROTO_MINIMUM_SUPPORTED;
3593 }
3594 return PyLong_FromLong(v);
3595}
3596
3597static int
3598set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3599{
3600 return set_min_max_proto_version(self, arg, 0);
3601}
3602
3603static PyObject *
3604get_maximum_version(PySSLContext *self, void *c)
3605{
3606 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3607 if (v == 0) {
3608 v = PY_PROTO_MAXIMUM_SUPPORTED;
3609 }
3610 return PyLong_FromLong(v);
3611}
3612
3613static int
3614set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3615{
3616 return set_min_max_proto_version(self, arg, 1);
3617}
3618#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3619
Christian Heimes78c7d522019-06-03 21:00:10 +02003620#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
3621static PyObject *
3622get_num_tickets(PySSLContext *self, void *c)
3623{
3624 return PyLong_FromLong(SSL_CTX_get_num_tickets(self->ctx));
3625}
3626
3627static int
3628set_num_tickets(PySSLContext *self, PyObject *arg, void *c)
3629{
3630 long num;
3631 if (!PyArg_Parse(arg, "l", &num))
3632 return -1;
3633 if (num < 0) {
3634 PyErr_SetString(PyExc_ValueError, "value must be non-negative");
3635 return -1;
3636 }
3637 if (self->protocol != PY_SSL_VERSION_TLS_SERVER) {
3638 PyErr_SetString(PyExc_ValueError,
3639 "SSLContext is not a server context.");
3640 return -1;
3641 }
3642 if (SSL_CTX_set_num_tickets(self->ctx, num) != 1) {
3643 PyErr_SetString(PyExc_ValueError, "failed to set num tickets.");
3644 return -1;
3645 }
3646 return 0;
3647}
3648
3649PyDoc_STRVAR(PySSLContext_num_tickets_doc,
3650"Control the number of TLSv1.3 session tickets");
3651#endif /* OpenSSL 1.1.1 */
3652
Christian Heimes22587792013-11-21 23:56:13 +01003653static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003654get_options(PySSLContext *self, void *c)
3655{
3656 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3657}
3658
3659static int
3660set_options(PySSLContext *self, PyObject *arg, void *c)
3661{
3662 long new_opts, opts, set, clear;
3663 if (!PyArg_Parse(arg, "l", &new_opts))
3664 return -1;
3665 opts = SSL_CTX_get_options(self->ctx);
3666 clear = opts & ~new_opts;
3667 set = ~opts & new_opts;
3668 if (clear) {
3669#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3670 SSL_CTX_clear_options(self->ctx, clear);
3671#else
3672 PyErr_SetString(PyExc_ValueError,
3673 "can't clear options before OpenSSL 0.9.8m");
3674 return -1;
3675#endif
3676 }
3677 if (set)
3678 SSL_CTX_set_options(self->ctx, set);
3679 return 0;
3680}
3681
Christian Heimes1aa9a752013-12-02 02:41:19 +01003682static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003683get_host_flags(PySSLContext *self, void *c)
3684{
3685 return PyLong_FromUnsignedLong(self->hostflags);
3686}
3687
3688static int
3689set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3690{
3691 X509_VERIFY_PARAM *param;
3692 unsigned int new_flags = 0;
3693
3694 if (!PyArg_Parse(arg, "I", &new_flags))
3695 return -1;
3696
3697 param = SSL_CTX_get0_param(self->ctx);
3698 self->hostflags = new_flags;
3699 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3700 return 0;
3701}
3702
3703static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003704get_check_hostname(PySSLContext *self, void *c)
3705{
3706 return PyBool_FromLong(self->check_hostname);
3707}
3708
3709static int
3710set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3711{
3712 int check_hostname;
3713 if (!PyArg_Parse(arg, "p", &check_hostname))
3714 return -1;
3715 if (check_hostname &&
3716 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003717 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
Christian Heimes9fb051f2018-09-23 08:32:31 +02003718 if (_set_verify_mode(self, PY_SSL_CERT_REQUIRED) == -1) {
Christian Heimese82c0342017-09-15 20:29:57 +02003719 return -1;
3720 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003721 }
3722 self->check_hostname = check_hostname;
3723 return 0;
3724}
3725
Christian Heimes11a14932018-02-24 02:35:08 +01003726static PyObject *
Christian Heimes9fb051f2018-09-23 08:32:31 +02003727get_post_handshake_auth(PySSLContext *self, void *c) {
3728#if TLS1_3_VERSION
3729 return PyBool_FromLong(self->post_handshake_auth);
3730#else
3731 Py_RETURN_NONE;
3732#endif
3733}
3734
3735#if TLS1_3_VERSION
3736static int
3737set_post_handshake_auth(PySSLContext *self, PyObject *arg, void *c) {
3738 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
3739 int mode = SSL_CTX_get_verify_mode(self->ctx);
Zackery Spytz842acaa2018-12-17 07:52:45 -07003740 if (arg == NULL) {
3741 PyErr_SetString(PyExc_AttributeError, "cannot delete attribute");
3742 return -1;
3743 }
Christian Heimes9fb051f2018-09-23 08:32:31 +02003744 int pha = PyObject_IsTrue(arg);
3745
3746 if (pha == -1) {
3747 return -1;
3748 }
3749 self->post_handshake_auth = pha;
3750
3751 /* client-side socket setting, ignored by server-side */
3752 SSL_CTX_set_post_handshake_auth(self->ctx, pha);
3753
3754 /* server-side socket setting, ignored by client-side */
3755 verify_cb = SSL_CTX_get_verify_callback(self->ctx);
3756 if (pha) {
3757 mode |= SSL_VERIFY_POST_HANDSHAKE;
3758 } else {
3759 mode ^= SSL_VERIFY_POST_HANDSHAKE;
3760 }
3761 SSL_CTX_set_verify(self->ctx, mode, verify_cb);
3762
3763 return 0;
3764}
3765#endif
3766
3767static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01003768get_protocol(PySSLContext *self, void *c) {
3769 return PyLong_FromLong(self->protocol);
3770}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003771
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003772typedef struct {
3773 PyThreadState *thread_state;
3774 PyObject *callable;
3775 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003776 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003777 int error;
3778} _PySSLPasswordInfo;
3779
3780static int
3781_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3782 const char *bad_type_error)
3783{
3784 /* Set the password and size fields of a _PySSLPasswordInfo struct
3785 from a unicode, bytes, or byte array object.
3786 The password field will be dynamically allocated and must be freed
3787 by the caller */
3788 PyObject *password_bytes = NULL;
3789 const char *data = NULL;
3790 Py_ssize_t size;
3791
3792 if (PyUnicode_Check(password)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003793 password_bytes = PyUnicode_AsUTF8String(password);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003794 if (!password_bytes) {
3795 goto error;
3796 }
3797 data = PyBytes_AS_STRING(password_bytes);
3798 size = PyBytes_GET_SIZE(password_bytes);
3799 } else if (PyBytes_Check(password)) {
3800 data = PyBytes_AS_STRING(password);
3801 size = PyBytes_GET_SIZE(password);
3802 } else if (PyByteArray_Check(password)) {
3803 data = PyByteArray_AS_STRING(password);
3804 size = PyByteArray_GET_SIZE(password);
3805 } else {
3806 PyErr_SetString(PyExc_TypeError, bad_type_error);
3807 goto error;
3808 }
3809
Victor Stinner9ee02032013-06-23 15:08:23 +02003810 if (size > (Py_ssize_t)INT_MAX) {
3811 PyErr_Format(PyExc_ValueError,
3812 "password cannot be longer than %d bytes", INT_MAX);
3813 goto error;
3814 }
3815
Victor Stinner11ebff22013-07-07 17:07:52 +02003816 PyMem_Free(pw_info->password);
3817 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003818 if (!pw_info->password) {
3819 PyErr_SetString(PyExc_MemoryError,
3820 "unable to allocate password buffer");
3821 goto error;
3822 }
3823 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003824 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003825
3826 Py_XDECREF(password_bytes);
3827 return 1;
3828
3829error:
3830 Py_XDECREF(password_bytes);
3831 return 0;
3832}
3833
3834static int
3835_password_callback(char *buf, int size, int rwflag, void *userdata)
3836{
3837 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3838 PyObject *fn_ret = NULL;
3839
3840 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3841
3842 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003843 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003844 if (!fn_ret) {
3845 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3846 core python API, so we could use it to add a frame here */
3847 goto error;
3848 }
3849
3850 if (!_pwinfo_set(pw_info, fn_ret,
3851 "password callback must return a string")) {
3852 goto error;
3853 }
3854 Py_CLEAR(fn_ret);
3855 }
3856
3857 if (pw_info->size > size) {
3858 PyErr_Format(PyExc_ValueError,
3859 "password cannot be longer than %d bytes", size);
3860 goto error;
3861 }
3862
3863 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3864 memcpy(buf, pw_info->password, pw_info->size);
3865 return pw_info->size;
3866
3867error:
3868 Py_XDECREF(fn_ret);
3869 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3870 pw_info->error = 1;
3871 return -1;
3872}
3873
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003874/*[clinic input]
3875_ssl._SSLContext.load_cert_chain
3876 certfile: object
3877 keyfile: object = NULL
3878 password: object = NULL
3879
3880[clinic start generated code]*/
3881
Antoine Pitroub5218772010-05-21 09:56:06 +00003882static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003883_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3884 PyObject *keyfile, PyObject *password)
3885/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003886{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003887 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003888 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3889 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003890 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003891 int r;
3892
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003893 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003894 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003895 if (keyfile == Py_None)
3896 keyfile = NULL;
3897 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003898 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3899 PyErr_SetString(PyExc_TypeError,
3900 "certfile should be a valid filesystem path");
3901 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003902 return NULL;
3903 }
3904 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03003905 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
3906 PyErr_SetString(PyExc_TypeError,
3907 "keyfile should be a valid filesystem path");
3908 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003909 goto error;
3910 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003911 if (password && password != Py_None) {
3912 if (PyCallable_Check(password)) {
3913 pw_info.callable = password;
3914 } else if (!_pwinfo_set(&pw_info, password,
3915 "password should be a string or callable")) {
3916 goto error;
3917 }
3918 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3919 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3920 }
3921 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003922 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3923 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003924 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003925 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003926 if (pw_info.error) {
3927 ERR_clear_error();
3928 /* the password callback has already set the error information */
3929 }
3930 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003931 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003932 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003933 }
3934 else {
3935 _setSSLError(NULL, 0, __FILE__, __LINE__);
3936 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003937 goto error;
3938 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003939 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003940 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003941 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3942 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003943 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3944 Py_CLEAR(keyfile_bytes);
3945 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003946 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003947 if (pw_info.error) {
3948 ERR_clear_error();
3949 /* the password callback has already set the error information */
3950 }
3951 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003952 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003953 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003954 }
3955 else {
3956 _setSSLError(NULL, 0, __FILE__, __LINE__);
3957 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003958 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003959 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003960 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003961 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003962 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003963 if (r != 1) {
3964 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003965 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003967 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3968 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003969 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003970 Py_RETURN_NONE;
3971
3972error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003973 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3974 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003975 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976 Py_XDECREF(keyfile_bytes);
3977 Py_XDECREF(certfile_bytes);
3978 return NULL;
3979}
3980
Christian Heimesefff7062013-11-21 03:35:02 +01003981/* internal helper function, returns -1 on error
3982 */
3983static int
3984_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3985 int filetype)
3986{
3987 BIO *biobuf = NULL;
3988 X509_STORE *store;
3989 int retval = 0, err, loaded = 0;
3990
3991 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3992
3993 if (len <= 0) {
3994 PyErr_SetString(PyExc_ValueError,
3995 "Empty certificate data");
3996 return -1;
3997 } else if (len > INT_MAX) {
3998 PyErr_SetString(PyExc_OverflowError,
3999 "Certificate data is too long.");
4000 return -1;
4001 }
4002
Christian Heimes1dbf61f2013-11-22 00:34:18 +01004003 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01004004 if (biobuf == NULL) {
4005 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
4006 return -1;
4007 }
4008
4009 store = SSL_CTX_get_cert_store(self->ctx);
4010 assert(store != NULL);
4011
4012 while (1) {
4013 X509 *cert = NULL;
4014 int r;
4015
4016 if (filetype == SSL_FILETYPE_ASN1) {
4017 cert = d2i_X509_bio(biobuf, NULL);
4018 } else {
4019 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02004020 SSL_CTX_get_default_passwd_cb(self->ctx),
4021 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
4022 );
Christian Heimesefff7062013-11-21 03:35:02 +01004023 }
4024 if (cert == NULL) {
4025 break;
4026 }
4027 r = X509_STORE_add_cert(store, cert);
4028 X509_free(cert);
4029 if (!r) {
4030 err = ERR_peek_last_error();
4031 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
4032 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
4033 /* cert already in hash table, not an error */
4034 ERR_clear_error();
4035 } else {
4036 break;
4037 }
4038 }
4039 loaded++;
4040 }
4041
4042 err = ERR_peek_last_error();
4043 if ((filetype == SSL_FILETYPE_ASN1) &&
4044 (loaded > 0) &&
4045 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
4046 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
4047 /* EOF ASN1 file, not an error */
4048 ERR_clear_error();
4049 retval = 0;
4050 } else if ((filetype == SSL_FILETYPE_PEM) &&
4051 (loaded > 0) &&
4052 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
4053 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
4054 /* EOF PEM file, not an error */
4055 ERR_clear_error();
4056 retval = 0;
4057 } else {
4058 _setSSLError(NULL, 0, __FILE__, __LINE__);
4059 retval = -1;
4060 }
4061
4062 BIO_free(biobuf);
4063 return retval;
4064}
4065
4066
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004067/*[clinic input]
4068_ssl._SSLContext.load_verify_locations
4069 cafile: object = NULL
4070 capath: object = NULL
4071 cadata: object = NULL
4072
4073[clinic start generated code]*/
4074
Antoine Pitrou152efa22010-05-16 18:19:27 +00004075static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
4077 PyObject *cafile,
4078 PyObject *capath,
4079 PyObject *cadata)
4080/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004081{
Antoine Pitrou152efa22010-05-16 18:19:27 +00004082 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
4083 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004084 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004085
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00004086 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004087 if (cafile == Py_None)
4088 cafile = NULL;
4089 if (capath == Py_None)
4090 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01004091 if (cadata == Py_None)
4092 cadata = NULL;
4093
4094 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004095 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01004096 "cafile, capath and cadata cannot be all omitted");
4097 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004098 }
4099 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004100 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4101 PyErr_SetString(PyExc_TypeError,
4102 "cafile should be a valid filesystem path");
4103 }
Christian Heimesefff7062013-11-21 03:35:02 +01004104 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004105 }
4106 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004107 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
4108 PyErr_SetString(PyExc_TypeError,
4109 "capath should be a valid filesystem path");
4110 }
Christian Heimesefff7062013-11-21 03:35:02 +01004111 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004112 }
Christian Heimesefff7062013-11-21 03:35:02 +01004113
4114 /* validata cadata type and load cadata */
4115 if (cadata) {
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004116 if (PyUnicode_Check(cadata)) {
4117 PyObject *cadata_ascii = PyUnicode_AsASCIIString(cadata);
4118 if (cadata_ascii == NULL) {
4119 if (PyErr_ExceptionMatches(PyExc_UnicodeEncodeError)) {
4120 goto invalid_cadata;
4121 }
4122 goto error;
4123 }
4124 r = _add_ca_certs(self,
4125 PyBytes_AS_STRING(cadata_ascii),
4126 PyBytes_GET_SIZE(cadata_ascii),
4127 SSL_FILETYPE_PEM);
4128 Py_DECREF(cadata_ascii);
4129 if (r == -1) {
4130 goto error;
4131 }
4132 }
4133 else if (PyObject_CheckBuffer(cadata)) {
4134 Py_buffer buf;
4135 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE)) {
4136 goto error;
4137 }
Christian Heimesefff7062013-11-21 03:35:02 +01004138 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
4139 PyBuffer_Release(&buf);
4140 PyErr_SetString(PyExc_TypeError,
4141 "cadata should be a contiguous buffer with "
4142 "a single dimension");
4143 goto error;
4144 }
4145 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
4146 PyBuffer_Release(&buf);
4147 if (r == -1) {
4148 goto error;
4149 }
Serhiy Storchaka65fb2c02019-05-31 10:39:15 +03004150 }
4151 else {
4152 invalid_cadata:
4153 PyErr_SetString(PyExc_TypeError,
4154 "cadata should be an ASCII string or a "
4155 "bytes-like object");
4156 goto error;
Christian Heimesefff7062013-11-21 03:35:02 +01004157 }
4158 }
4159
4160 /* load cafile or capath */
4161 if (cafile || capath) {
4162 if (cafile)
4163 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
4164 if (capath)
4165 capath_buf = PyBytes_AS_STRING(capath_bytes);
4166 PySSL_BEGIN_ALLOW_THREADS
4167 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
4168 PySSL_END_ALLOW_THREADS
4169 if (r != 1) {
4170 ok = 0;
4171 if (errno != 0) {
4172 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03004173 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01004174 }
4175 else {
4176 _setSSLError(NULL, 0, __FILE__, __LINE__);
4177 }
4178 goto error;
4179 }
4180 }
4181 goto end;
4182
4183 error:
4184 ok = 0;
4185 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00004186 Py_XDECREF(cafile_bytes);
4187 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01004188 if (ok) {
4189 Py_RETURN_NONE;
4190 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00004191 return NULL;
4192 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004193}
4194
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004195/*[clinic input]
4196_ssl._SSLContext.load_dh_params
4197 path as filepath: object
4198 /
4199
4200[clinic start generated code]*/
4201
Antoine Pitrou152efa22010-05-16 18:19:27 +00004202static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
4204/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004205{
4206 FILE *f;
4207 DH *dh;
4208
Victor Stinnerdaf45552013-08-28 00:53:59 +02004209 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01004210 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004211 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01004212
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004213 errno = 0;
4214 PySSL_BEGIN_ALLOW_THREADS
4215 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01004216 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004217 PySSL_END_ALLOW_THREADS
4218 if (dh == NULL) {
4219 if (errno != 0) {
4220 ERR_clear_error();
4221 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4222 }
4223 else {
4224 _setSSLError(NULL, 0, __FILE__, __LINE__);
4225 }
4226 return NULL;
4227 }
4228 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4229 _setSSLError(NULL, 0, __FILE__, __LINE__);
4230 DH_free(dh);
4231 Py_RETURN_NONE;
4232}
4233
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004234/*[clinic input]
4235_ssl._SSLContext._wrap_socket
4236 sock: object(subclass_of="PySocketModule.Sock_Type")
4237 server_side: int
4238 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004239 *
4240 owner: object = None
4241 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004242
4243[clinic start generated code]*/
4244
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004245static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004246_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004247 int server_side, PyObject *hostname_obj,
4248 PyObject *owner, PyObject *session)
4249/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004250{
Antoine Pitroud5323212010-10-22 18:19:07 +00004251 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004252 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004253
Antoine Pitroud5323212010-10-22 18:19:07 +00004254 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004255 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004256 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004257 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004258 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004259 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004260
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004261 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4262 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004263 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004264 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004265 if (hostname != NULL)
4266 PyMem_Free(hostname);
4267 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004268}
4269
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004270/*[clinic input]
4271_ssl._SSLContext._wrap_bio
4272 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4273 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4274 server_side: int
4275 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004276 *
4277 owner: object = None
4278 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004279
4280[clinic start generated code]*/
4281
Antoine Pitroub0182c82010-10-12 20:09:02 +00004282static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004283_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4284 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004285 PyObject *hostname_obj, PyObject *owner,
4286 PyObject *session)
4287/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004288{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004289 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004290 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004291
4292 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004293 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004294 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004295 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004296 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004297 }
4298
4299 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004300 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004301 incoming, outgoing);
4302
4303 PyMem_Free(hostname);
4304 return res;
4305}
4306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004307/*[clinic input]
4308_ssl._SSLContext.session_stats
4309[clinic start generated code]*/
4310
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004311static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004312_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4313/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004314{
4315 int r;
4316 PyObject *value, *stats = PyDict_New();
4317 if (!stats)
4318 return NULL;
4319
4320#define ADD_STATS(SSL_NAME, KEY_NAME) \
4321 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4322 if (value == NULL) \
4323 goto error; \
4324 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4325 Py_DECREF(value); \
4326 if (r < 0) \
4327 goto error;
4328
4329 ADD_STATS(number, "number");
4330 ADD_STATS(connect, "connect");
4331 ADD_STATS(connect_good, "connect_good");
4332 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4333 ADD_STATS(accept, "accept");
4334 ADD_STATS(accept_good, "accept_good");
4335 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4336 ADD_STATS(accept, "accept");
4337 ADD_STATS(hits, "hits");
4338 ADD_STATS(misses, "misses");
4339 ADD_STATS(timeouts, "timeouts");
4340 ADD_STATS(cache_full, "cache_full");
4341
4342#undef ADD_STATS
4343
4344 return stats;
4345
4346error:
4347 Py_DECREF(stats);
4348 return NULL;
4349}
4350
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004351/*[clinic input]
4352_ssl._SSLContext.set_default_verify_paths
4353[clinic start generated code]*/
4354
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004355static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004356_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4357/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004358{
4359 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4360 _setSSLError(NULL, 0, __FILE__, __LINE__);
4361 return NULL;
4362 }
4363 Py_RETURN_NONE;
4364}
4365
Antoine Pitrou501da612011-12-21 09:27:41 +01004366#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004367/*[clinic input]
4368_ssl._SSLContext.set_ecdh_curve
4369 name: object
4370 /
4371
4372[clinic start generated code]*/
4373
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004374static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004375_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4376/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004377{
4378 PyObject *name_bytes;
4379 int nid;
4380 EC_KEY *key;
4381
4382 if (!PyUnicode_FSConverter(name, &name_bytes))
4383 return NULL;
4384 assert(PyBytes_Check(name_bytes));
4385 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4386 Py_DECREF(name_bytes);
4387 if (nid == 0) {
4388 PyErr_Format(PyExc_ValueError,
4389 "unknown elliptic curve name %R", name);
4390 return NULL;
4391 }
4392 key = EC_KEY_new_by_curve_name(nid);
4393 if (key == NULL) {
4394 _setSSLError(NULL, 0, __FILE__, __LINE__);
4395 return NULL;
4396 }
4397 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4398 EC_KEY_free(key);
4399 Py_RETURN_NONE;
4400}
Antoine Pitrou501da612011-12-21 09:27:41 +01004401#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004402
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004403#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004404static int
4405_servername_callback(SSL *s, int *al, void *args)
4406{
4407 int ret;
4408 PySSLContext *ssl_ctx = (PySSLContext *) args;
4409 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004410 PyObject *result;
4411 /* The high-level ssl.SSLSocket object */
4412 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004413 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004414 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004415
Christian Heimes11a14932018-02-24 02:35:08 +01004416 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004417 /* remove race condition in this the call back while if removing the
4418 * callback is in progress */
4419 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004420 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004421 }
4422
4423 ssl = SSL_get_app_data(s);
4424 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004425
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004426 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004427 * SSL connection and that has a .context attribute that can be changed to
4428 * identify the requested hostname. Since the official API is the Python
4429 * level API we want to pass the callback a Python level object rather than
4430 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4431 * SSLObject) that will be passed. Otherwise if there's a socket then that
4432 * will be passed. If both do not exist only then the C-level object is
4433 * passed. */
4434 if (ssl->owner)
4435 ssl_socket = PyWeakref_GetObject(ssl->owner);
4436 else if (ssl->Socket)
4437 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4438 else
4439 ssl_socket = (PyObject *) ssl;
4440
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004441 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004442 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004443 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004444
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004445 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004446 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004447 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004448 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004449 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004450 PyObject *servername_bytes;
4451 PyObject *servername_str;
4452
4453 servername_bytes = PyBytes_FromString(servername);
4454 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004455 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4456 goto error;
4457 }
Christian Heimes11a14932018-02-24 02:35:08 +01004458 /* server_hostname was encoded to an A-label by our caller; put it
4459 * back into a str object, but still as an A-label (bpo-28414)
4460 */
4461 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4462 Py_DECREF(servername_bytes);
4463 if (servername_str == NULL) {
4464 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004465 goto error;
4466 }
Christian Heimes11a14932018-02-24 02:35:08 +01004467 result = PyObject_CallFunctionObjArgs(
4468 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4469 ssl_ctx, NULL);
4470 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004471 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004472 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004473
4474 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004475 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004476 *al = SSL_AD_HANDSHAKE_FAILURE;
4477 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4478 }
4479 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004480 /* Result may be None, a SSLContext or an integer
4481 * None and SSLContext are OK, integer or other values are an error.
4482 */
4483 if (result == Py_None) {
4484 ret = SSL_TLSEXT_ERR_OK;
4485 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004486 *al = (int) PyLong_AsLong(result);
4487 if (PyErr_Occurred()) {
4488 PyErr_WriteUnraisable(result);
4489 *al = SSL_AD_INTERNAL_ERROR;
4490 }
4491 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4492 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004493 Py_DECREF(result);
4494 }
4495
4496 PyGILState_Release(gstate);
4497 return ret;
4498
4499error:
4500 Py_DECREF(ssl_socket);
4501 *al = SSL_AD_INTERNAL_ERROR;
4502 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4503 PyGILState_Release(gstate);
4504 return ret;
4505}
Antoine Pitroua5963382013-03-30 16:39:00 +01004506#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004507
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004509get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004510{
Christian Heimes11a14932018-02-24 02:35:08 +01004511 PyObject *cb = self->set_sni_cb;
4512 if (cb == NULL) {
4513 Py_RETURN_NONE;
4514 }
4515 Py_INCREF(cb);
4516 return cb;
4517}
4518
4519static int
4520set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4521{
4522 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4523 PyErr_SetString(PyExc_ValueError,
4524 "sni_callback cannot be set on TLS_CLIENT context");
4525 return -1;
4526 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004527#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004528 Py_CLEAR(self->set_sni_cb);
4529 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004530 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4531 }
4532 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004533 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004534 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4535 PyErr_SetString(PyExc_TypeError,
4536 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004537 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004538 }
Christian Heimes11a14932018-02-24 02:35:08 +01004539 Py_INCREF(arg);
4540 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004541 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4542 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4543 }
Christian Heimes11a14932018-02-24 02:35:08 +01004544 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004545#else
4546 PyErr_SetString(PyExc_NotImplementedError,
4547 "The TLS extension servername callback, "
4548 "SSL_CTX_set_tlsext_servername_callback, "
4549 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004550 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004551#endif
4552}
4553
Christian Heimes11a14932018-02-24 02:35:08 +01004554PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4555"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4556\n\
4557If the argument is None then the callback is disabled. The method is called\n\
4558with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4559See RFC 6066 for details of the SNI extension.");
4560
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561/*[clinic input]
4562_ssl._SSLContext.cert_store_stats
4563
4564Returns quantities of loaded X.509 certificates.
4565
4566X.509 certificates with a CA extension and certificate revocation lists
4567inside the context's cert store.
4568
4569NOTE: Certificates in a capath directory aren't loaded unless they have
4570been used at least once.
4571[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004572
4573static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004574_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4575/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004576{
4577 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004578 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004579 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004580 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004581
4582 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004583 objs = X509_STORE_get0_objects(store);
4584 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4585 obj = sk_X509_OBJECT_value(objs, i);
4586 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004587 case X509_LU_X509:
4588 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004589 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004590 ca++;
4591 }
4592 break;
4593 case X509_LU_CRL:
4594 crl++;
4595 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004596 default:
4597 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4598 * As far as I can tell they are internal states and never
4599 * stored in a cert store */
4600 break;
4601 }
4602 }
4603 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4604 "x509_ca", ca);
4605}
4606
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004607/*[clinic input]
4608_ssl._SSLContext.get_ca_certs
4609 binary_form: bool = False
4610
4611Returns a list of dicts with information of loaded CA certs.
4612
4613If the optional argument is True, returns a DER-encoded copy of the CA
4614certificate.
4615
4616NOTE: Certificates in a capath directory aren't loaded unless they have
4617been used at least once.
4618[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004619
4620static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004621_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4622/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004623{
4624 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004625 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004626 PyObject *ci = NULL, *rlist = NULL;
4627 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004628
4629 if ((rlist = PyList_New(0)) == NULL) {
4630 return NULL;
4631 }
4632
4633 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004634 objs = X509_STORE_get0_objects(store);
4635 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004636 X509_OBJECT *obj;
4637 X509 *cert;
4638
Christian Heimes598894f2016-09-05 23:19:05 +02004639 obj = sk_X509_OBJECT_value(objs, i);
4640 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004641 /* not a x509 cert */
4642 continue;
4643 }
4644 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004645 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004646 if (!X509_check_ca(cert)) {
4647 continue;
4648 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004650 ci = _certificate_to_der(cert);
4651 } else {
4652 ci = _decode_certificate(cert);
4653 }
4654 if (ci == NULL) {
4655 goto error;
4656 }
4657 if (PyList_Append(rlist, ci) == -1) {
4658 goto error;
4659 }
4660 Py_CLEAR(ci);
4661 }
4662 return rlist;
4663
4664 error:
4665 Py_XDECREF(ci);
4666 Py_XDECREF(rlist);
4667 return NULL;
4668}
4669
4670
Antoine Pitrou152efa22010-05-16 18:19:27 +00004671static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004672 {"check_hostname", (getter) get_check_hostname,
4673 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004674 {"_host_flags", (getter) get_host_flags,
4675 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004676#if SSL_CTRL_GET_MAX_PROTO_VERSION
4677 {"minimum_version", (getter) get_minimum_version,
4678 (setter) set_minimum_version, NULL},
4679 {"maximum_version", (getter) get_maximum_version,
4680 (setter) set_maximum_version, NULL},
4681#endif
Christian Heimesc7f70692019-05-31 11:44:05 +02004682#ifdef HAVE_OPENSSL_KEYLOG
4683 {"keylog_filename", (getter) _PySSLContext_get_keylog_filename,
4684 (setter) _PySSLContext_set_keylog_filename, NULL},
4685#endif
4686 {"_msg_callback", (getter) _PySSLContext_get_msg_callback,
4687 (setter) _PySSLContext_set_msg_callback, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004688 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004689 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Christian Heimes78c7d522019-06-03 21:00:10 +02004690#if (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
4691 {"num_tickets", (getter) get_num_tickets,
4692 (setter) set_num_tickets, PySSLContext_num_tickets_doc},
4693#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00004694 {"options", (getter) get_options,
4695 (setter) set_options, NULL},
Christian Heimes9fb051f2018-09-23 08:32:31 +02004696 {"post_handshake_auth", (getter) get_post_handshake_auth,
4697#ifdef TLS1_3_VERSION
4698 (setter) set_post_handshake_auth,
4699#else
4700 NULL,
4701#endif
4702 NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004703 {"protocol", (getter) get_protocol,
4704 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004705 {"verify_flags", (getter) get_verify_flags,
4706 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004707 {"verify_mode", (getter) get_verify_mode,
4708 (setter) set_verify_mode, NULL},
4709 {NULL}, /* sentinel */
4710};
4711
4712static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004713 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4714 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4715 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4716 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4717 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4718 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4719 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4720 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4721 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4722 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4723 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004724 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4725 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004726 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004727 {NULL, NULL} /* sentinel */
4728};
4729
4730static PyTypeObject PySSLContext_Type = {
4731 PyVarObject_HEAD_INIT(NULL, 0)
4732 "_ssl._SSLContext", /*tp_name*/
4733 sizeof(PySSLContext), /*tp_basicsize*/
4734 0, /*tp_itemsize*/
4735 (destructor)context_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004736 0, /*tp_vectorcall_offset*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004737 0, /*tp_getattr*/
4738 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004739 0, /*tp_as_async*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004740 0, /*tp_repr*/
4741 0, /*tp_as_number*/
4742 0, /*tp_as_sequence*/
4743 0, /*tp_as_mapping*/
4744 0, /*tp_hash*/
4745 0, /*tp_call*/
4746 0, /*tp_str*/
4747 0, /*tp_getattro*/
4748 0, /*tp_setattro*/
4749 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004750 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004751 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004752 (traverseproc) context_traverse, /*tp_traverse*/
4753 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004754 0, /*tp_richcompare*/
4755 0, /*tp_weaklistoffset*/
4756 0, /*tp_iter*/
4757 0, /*tp_iternext*/
4758 context_methods, /*tp_methods*/
4759 0, /*tp_members*/
4760 context_getsetlist, /*tp_getset*/
4761 0, /*tp_base*/
4762 0, /*tp_dict*/
4763 0, /*tp_descr_get*/
4764 0, /*tp_descr_set*/
4765 0, /*tp_dictoffset*/
4766 0, /*tp_init*/
4767 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004768 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004769};
4770
4771
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004772/*
4773 * MemoryBIO objects
4774 */
4775
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004776/*[clinic input]
4777@classmethod
4778_ssl.MemoryBIO.__new__
4779
4780[clinic start generated code]*/
4781
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004782static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004783_ssl_MemoryBIO_impl(PyTypeObject *type)
4784/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004785{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004786 BIO *bio;
4787 PySSLMemoryBIO *self;
4788
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004789 bio = BIO_new(BIO_s_mem());
4790 if (bio == NULL) {
4791 PyErr_SetString(PySSLErrorObject,
4792 "failed to allocate BIO");
4793 return NULL;
4794 }
4795 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4796 * just that no data is currently available. The SSL routines should retry
4797 * the read, which we can achieve by calling BIO_set_retry_read(). */
4798 BIO_set_retry_read(bio);
4799 BIO_set_mem_eof_return(bio, -1);
4800
4801 assert(type != NULL && type->tp_alloc != NULL);
4802 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4803 if (self == NULL) {
4804 BIO_free(bio);
4805 return NULL;
4806 }
4807 self->bio = bio;
4808 self->eof_written = 0;
4809
4810 return (PyObject *) self;
4811}
4812
4813static void
4814memory_bio_dealloc(PySSLMemoryBIO *self)
4815{
4816 BIO_free(self->bio);
4817 Py_TYPE(self)->tp_free(self);
4818}
4819
4820static PyObject *
4821memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4822{
Segev Finer5cff6372017-07-27 01:19:17 +03004823 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004824}
4825
4826PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4827"The number of bytes pending in the memory BIO.");
4828
4829static PyObject *
4830memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4831{
4832 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4833 && self->eof_written);
4834}
4835
4836PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4837"Whether the memory BIO is at EOF.");
4838
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004839/*[clinic input]
4840_ssl.MemoryBIO.read
4841 size as len: int = -1
4842 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004843
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004844Read up to size bytes from the memory BIO.
4845
4846If size is not specified, read the entire buffer.
4847If the return value is an empty bytes instance, this means either
4848EOF or that no data is available. Use the "eof" property to
4849distinguish between the two.
4850[clinic start generated code]*/
4851
4852static PyObject *
4853_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4854/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4855{
4856 int avail, nbytes;
4857 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004858
Segev Finer5cff6372017-07-27 01:19:17 +03004859 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004860 if ((len < 0) || (len > avail))
4861 len = avail;
4862
4863 result = PyBytes_FromStringAndSize(NULL, len);
4864 if ((result == NULL) || (len == 0))
4865 return result;
4866
4867 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004868 if (nbytes < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004869 Py_DECREF(result);
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004870 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004871 return NULL;
4872 }
4873
Zackery Spytz365ad2e2018-10-06 11:41:45 -06004874 /* There should never be any short reads but check anyway. */
4875 if (nbytes < len) {
4876 _PyBytes_Resize(&result, nbytes);
4877 }
4878
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004879 return result;
4880}
4881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004882/*[clinic input]
4883_ssl.MemoryBIO.write
4884 b: Py_buffer
4885 /
4886
4887Writes the bytes b into the memory BIO.
4888
4889Returns the number of bytes written.
4890[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004891
4892static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004893_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4894/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004895{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004896 int nbytes;
4897
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004898 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004899 PyErr_Format(PyExc_OverflowError,
4900 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004901 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004902 }
4903
4904 if (self->eof_written) {
4905 PyErr_SetString(PySSLErrorObject,
4906 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004907 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004908 }
4909
Segev Finer5cff6372017-07-27 01:19:17 +03004910 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004911 if (nbytes < 0) {
4912 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004913 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004914 }
4915
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004916 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004917}
4918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004919/*[clinic input]
4920_ssl.MemoryBIO.write_eof
4921
4922Write an EOF marker to the memory BIO.
4923
4924When all data has been read, the "eof" property will be True.
4925[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004926
4927static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004928_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4929/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004930{
4931 self->eof_written = 1;
4932 /* After an EOF is written, a zero return from read() should be a real EOF
4933 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4934 BIO_clear_retry_flags(self->bio);
4935 BIO_set_mem_eof_return(self->bio, 0);
4936
4937 Py_RETURN_NONE;
4938}
4939
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004940static PyGetSetDef memory_bio_getsetlist[] = {
4941 {"pending", (getter) memory_bio_get_pending, NULL,
4942 PySSL_memory_bio_pending_doc},
4943 {"eof", (getter) memory_bio_get_eof, NULL,
4944 PySSL_memory_bio_eof_doc},
4945 {NULL}, /* sentinel */
4946};
4947
4948static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004949 _SSL_MEMORYBIO_READ_METHODDEF
4950 _SSL_MEMORYBIO_WRITE_METHODDEF
4951 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004952 {NULL, NULL} /* sentinel */
4953};
4954
4955static PyTypeObject PySSLMemoryBIO_Type = {
4956 PyVarObject_HEAD_INIT(NULL, 0)
4957 "_ssl.MemoryBIO", /*tp_name*/
4958 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4959 0, /*tp_itemsize*/
4960 (destructor)memory_bio_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004961 0, /*tp_vectorcall_offset*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004962 0, /*tp_getattr*/
4963 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02004964 0, /*tp_as_async*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004965 0, /*tp_repr*/
4966 0, /*tp_as_number*/
4967 0, /*tp_as_sequence*/
4968 0, /*tp_as_mapping*/
4969 0, /*tp_hash*/
4970 0, /*tp_call*/
4971 0, /*tp_str*/
4972 0, /*tp_getattro*/
4973 0, /*tp_setattro*/
4974 0, /*tp_as_buffer*/
4975 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4976 0, /*tp_doc*/
4977 0, /*tp_traverse*/
4978 0, /*tp_clear*/
4979 0, /*tp_richcompare*/
4980 0, /*tp_weaklistoffset*/
4981 0, /*tp_iter*/
4982 0, /*tp_iternext*/
4983 memory_bio_methods, /*tp_methods*/
4984 0, /*tp_members*/
4985 memory_bio_getsetlist, /*tp_getset*/
4986 0, /*tp_base*/
4987 0, /*tp_dict*/
4988 0, /*tp_descr_get*/
4989 0, /*tp_descr_set*/
4990 0, /*tp_dictoffset*/
4991 0, /*tp_init*/
4992 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004993 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004994};
4995
Antoine Pitrou152efa22010-05-16 18:19:27 +00004996
Christian Heimes99a65702016-09-10 23:44:53 +02004997/*
4998 * SSL Session object
4999 */
5000
5001static void
5002PySSLSession_dealloc(PySSLSession *self)
5003{
INADA Naokia6296d32017-08-24 14:55:17 +09005004 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02005005 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005006 Py_XDECREF(self->ctx);
5007 if (self->session != NULL) {
5008 SSL_SESSION_free(self->session);
5009 }
Christian Heimesa5d07652016-09-24 10:48:05 +02005010 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02005011}
5012
5013static PyObject *
5014PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
5015{
5016 int result;
5017
5018 if (left == NULL || right == NULL) {
5019 PyErr_BadInternalCall();
5020 return NULL;
5021 }
5022
5023 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
5024 Py_RETURN_NOTIMPLEMENTED;
5025 }
5026
5027 if (left == right) {
5028 result = 0;
5029 } else {
5030 const unsigned char *left_id, *right_id;
5031 unsigned int left_len, right_len;
5032 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
5033 &left_len);
5034 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
5035 &right_len);
5036 if (left_len == right_len) {
5037 result = memcmp(left_id, right_id, left_len);
5038 } else {
5039 result = 1;
5040 }
5041 }
5042
5043 switch (op) {
5044 case Py_EQ:
5045 if (result == 0) {
5046 Py_RETURN_TRUE;
5047 } else {
5048 Py_RETURN_FALSE;
5049 }
5050 break;
5051 case Py_NE:
5052 if (result != 0) {
5053 Py_RETURN_TRUE;
5054 } else {
5055 Py_RETURN_FALSE;
5056 }
5057 break;
5058 case Py_LT:
5059 case Py_LE:
5060 case Py_GT:
5061 case Py_GE:
5062 Py_RETURN_NOTIMPLEMENTED;
5063 break;
5064 default:
5065 PyErr_BadArgument();
5066 return NULL;
5067 }
5068}
5069
5070static int
5071PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
5072{
5073 Py_VISIT(self->ctx);
5074 return 0;
5075}
5076
5077static int
5078PySSLSession_clear(PySSLSession *self)
5079{
5080 Py_CLEAR(self->ctx);
5081 return 0;
5082}
5083
5084
5085static PyObject *
5086PySSLSession_get_time(PySSLSession *self, void *closure) {
5087 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
5088}
5089
5090PyDoc_STRVAR(PySSLSession_get_time_doc,
5091"Session creation time (seconds since epoch).");
5092
5093
5094static PyObject *
5095PySSLSession_get_timeout(PySSLSession *self, void *closure) {
5096 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
5097}
5098
5099PyDoc_STRVAR(PySSLSession_get_timeout_doc,
5100"Session timeout (delta in seconds).");
5101
5102
5103static PyObject *
5104PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
5105 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
5106 return PyLong_FromUnsignedLong(hint);
5107}
5108
5109PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
5110"Ticket life time hint.");
5111
5112
5113static PyObject *
5114PySSLSession_get_session_id(PySSLSession *self, void *closure) {
5115 const unsigned char *id;
5116 unsigned int len;
5117 id = SSL_SESSION_get_id(self->session, &len);
5118 return PyBytes_FromStringAndSize((const char *)id, len);
5119}
5120
5121PyDoc_STRVAR(PySSLSession_get_session_id_doc,
5122"Session id");
5123
5124
5125static PyObject *
5126PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
5127 if (SSL_SESSION_has_ticket(self->session)) {
5128 Py_RETURN_TRUE;
5129 } else {
5130 Py_RETURN_FALSE;
5131 }
5132}
5133
5134PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
5135"Does the session contain a ticket?");
5136
5137
5138static PyGetSetDef PySSLSession_getsetlist[] = {
5139 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
5140 PySSLSession_get_has_ticket_doc},
5141 {"id", (getter) PySSLSession_get_session_id, NULL,
5142 PySSLSession_get_session_id_doc},
5143 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
5144 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
5145 {"time", (getter) PySSLSession_get_time, NULL,
5146 PySSLSession_get_time_doc},
5147 {"timeout", (getter) PySSLSession_get_timeout, NULL,
5148 PySSLSession_get_timeout_doc},
5149 {NULL}, /* sentinel */
5150};
5151
5152static PyTypeObject PySSLSession_Type = {
5153 PyVarObject_HEAD_INIT(NULL, 0)
5154 "_ssl.Session", /*tp_name*/
5155 sizeof(PySSLSession), /*tp_basicsize*/
5156 0, /*tp_itemsize*/
5157 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005158 0, /*tp_vectorcall_offset*/
Christian Heimes99a65702016-09-10 23:44:53 +02005159 0, /*tp_getattr*/
5160 0, /*tp_setattr*/
Jeroen Demeyer530f5062019-05-31 04:13:39 +02005161 0, /*tp_as_async*/
Christian Heimes99a65702016-09-10 23:44:53 +02005162 0, /*tp_repr*/
5163 0, /*tp_as_number*/
5164 0, /*tp_as_sequence*/
5165 0, /*tp_as_mapping*/
5166 0, /*tp_hash*/
5167 0, /*tp_call*/
5168 0, /*tp_str*/
5169 0, /*tp_getattro*/
5170 0, /*tp_setattro*/
5171 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02005172 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02005173 0, /*tp_doc*/
5174 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
5175 (inquiry)PySSLSession_clear, /*tp_clear*/
5176 PySSLSession_richcompare, /*tp_richcompare*/
5177 0, /*tp_weaklistoffset*/
5178 0, /*tp_iter*/
5179 0, /*tp_iternext*/
5180 0, /*tp_methods*/
5181 0, /*tp_members*/
5182 PySSLSession_getsetlist, /*tp_getset*/
5183};
5184
5185
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005186/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005187/*[clinic input]
5188_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07005189 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005190 entropy: double
5191 /
5192
5193Mix string into the OpenSSL PRNG state.
5194
5195entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05305196string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005197[clinic start generated code]*/
5198
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005199static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005200_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03005201/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005202{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02005203 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005204 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005205
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005206 buf = (const char *)view->buf;
5207 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02005208 do {
5209 written = Py_MIN(len, INT_MAX);
5210 RAND_add(buf, (int)written, entropy);
5211 buf += written;
5212 len -= written;
5213 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02005214 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005215}
5216
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005217static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02005218PySSL_RAND(int len, int pseudo)
5219{
5220 int ok;
5221 PyObject *bytes;
5222 unsigned long err;
5223 const char *errstr;
5224 PyObject *v;
5225
Victor Stinner1e81a392013-12-19 16:47:04 +01005226 if (len < 0) {
5227 PyErr_SetString(PyExc_ValueError, "num must be positive");
5228 return NULL;
5229 }
5230
Victor Stinner99c8b162011-05-24 12:05:19 +02005231 bytes = PyBytes_FromStringAndSize(NULL, len);
5232 if (bytes == NULL)
5233 return NULL;
5234 if (pseudo) {
5235 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5236 if (ok == 0 || ok == 1)
5237 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
5238 }
5239 else {
5240 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
5241 if (ok == 1)
5242 return bytes;
5243 }
5244 Py_DECREF(bytes);
5245
5246 err = ERR_get_error();
5247 errstr = ERR_reason_error_string(err);
5248 v = Py_BuildValue("(ks)", err, errstr);
5249 if (v != NULL) {
5250 PyErr_SetObject(PySSLErrorObject, v);
5251 Py_DECREF(v);
5252 }
5253 return NULL;
5254}
5255
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005256/*[clinic input]
5257_ssl.RAND_bytes
5258 n: int
5259 /
5260
5261Generate n cryptographically strong pseudo-random bytes.
5262[clinic start generated code]*/
5263
Victor Stinner99c8b162011-05-24 12:05:19 +02005264static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005265_ssl_RAND_bytes_impl(PyObject *module, int n)
5266/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005267{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005268 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005269}
5270
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005271/*[clinic input]
5272_ssl.RAND_pseudo_bytes
5273 n: int
5274 /
5275
5276Generate n pseudo-random bytes.
5277
5278Return a pair (bytes, is_cryptographic). is_cryptographic is True
5279if the bytes generated are cryptographically strong.
5280[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005281
5282static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005283_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5284/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005285{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005286 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005287}
5288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005289/*[clinic input]
5290_ssl.RAND_status
5291
5292Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5293
5294It is necessary to seed the PRNG with RAND_add() on some platforms before
5295using the ssl() function.
5296[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005297
5298static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005299_ssl_RAND_status_impl(PyObject *module)
5300/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005301{
Christian Heimes217cfd12007-12-02 14:31:20 +00005302 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005303}
5304
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005305#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005306/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005307/*[clinic input]
5308_ssl.RAND_egd
5309 path: object(converter="PyUnicode_FSConverter")
5310 /
5311
5312Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5313
5314Returns number of bytes read. Raises SSLError if connection to EGD
5315fails or if it does not provide enough data to seed PRNG.
5316[clinic start generated code]*/
5317
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005318static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005319_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5320/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005321{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005322 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005323 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005324 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005325 PyErr_SetString(PySSLErrorObject,
5326 "EGD connection failed or EGD did not return "
5327 "enough data to seed the PRNG");
5328 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005329 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005330 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005331}
Christian Heimesa5d07652016-09-24 10:48:05 +02005332/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005333#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005334
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005335
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005336
5337/*[clinic input]
5338_ssl.get_default_verify_paths
5339
5340Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5341
5342The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5343[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005344
5345static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005346_ssl_get_default_verify_paths_impl(PyObject *module)
5347/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005348{
5349 PyObject *ofile_env = NULL;
5350 PyObject *ofile = NULL;
5351 PyObject *odir_env = NULL;
5352 PyObject *odir = NULL;
5353
Benjamin Petersond113c962015-07-18 10:59:13 -07005354#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005355 const char *tmp = (info); \
5356 target = NULL; \
5357 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5358 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5359 target = PyBytes_FromString(tmp); } \
5360 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005361 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005362
Benjamin Petersond113c962015-07-18 10:59:13 -07005363 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5364 CONVERT(X509_get_default_cert_file(), ofile);
5365 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5366 CONVERT(X509_get_default_cert_dir(), odir);
5367#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005368
Christian Heimes200bb1b2013-06-14 15:14:29 +02005369 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005370
5371 error:
5372 Py_XDECREF(ofile_env);
5373 Py_XDECREF(ofile);
5374 Py_XDECREF(odir_env);
5375 Py_XDECREF(odir);
5376 return NULL;
5377}
5378
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005379static PyObject*
5380asn1obj2py(ASN1_OBJECT *obj)
5381{
5382 int nid;
5383 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005384
5385 nid = OBJ_obj2nid(obj);
5386 if (nid == NID_undef) {
5387 PyErr_Format(PyExc_ValueError, "Unknown object");
5388 return NULL;
5389 }
5390 sn = OBJ_nid2sn(nid);
5391 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005392 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005393}
5394
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005395/*[clinic input]
5396_ssl.txt2obj
5397 txt: str
5398 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005399
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005400Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5401
5402By default objects are looked up by OID. With name=True short and
5403long name are also matched.
5404[clinic start generated code]*/
5405
5406static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005407_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5408/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005409{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005410 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005411 ASN1_OBJECT *obj;
5412
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005413 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5414 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005415 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005416 return NULL;
5417 }
5418 result = asn1obj2py(obj);
5419 ASN1_OBJECT_free(obj);
5420 return result;
5421}
5422
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005423/*[clinic input]
5424_ssl.nid2obj
5425 nid: int
5426 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005427
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005428Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5429[clinic start generated code]*/
5430
5431static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005432_ssl_nid2obj_impl(PyObject *module, int nid)
5433/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005434{
5435 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005436 ASN1_OBJECT *obj;
5437
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005438 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005439 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005440 return NULL;
5441 }
5442 obj = OBJ_nid2obj(nid);
5443 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005444 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005445 return NULL;
5446 }
5447 result = asn1obj2py(obj);
5448 ASN1_OBJECT_free(obj);
5449 return result;
5450}
5451
Christian Heimes46bebee2013-06-09 19:03:31 +02005452#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005453
5454static PyObject*
5455certEncodingType(DWORD encodingType)
5456{
5457 static PyObject *x509_asn = NULL;
5458 static PyObject *pkcs_7_asn = NULL;
5459
5460 if (x509_asn == NULL) {
5461 x509_asn = PyUnicode_InternFromString("x509_asn");
5462 if (x509_asn == NULL)
5463 return NULL;
5464 }
5465 if (pkcs_7_asn == NULL) {
5466 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5467 if (pkcs_7_asn == NULL)
5468 return NULL;
5469 }
5470 switch(encodingType) {
5471 case X509_ASN_ENCODING:
5472 Py_INCREF(x509_asn);
5473 return x509_asn;
5474 case PKCS_7_ASN_ENCODING:
5475 Py_INCREF(pkcs_7_asn);
5476 return pkcs_7_asn;
5477 default:
5478 return PyLong_FromLong(encodingType);
5479 }
5480}
5481
5482static PyObject*
5483parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5484{
5485 CERT_ENHKEY_USAGE *usage;
5486 DWORD size, error, i;
5487 PyObject *retval;
5488
5489 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5490 error = GetLastError();
5491 if (error == CRYPT_E_NOT_FOUND) {
5492 Py_RETURN_TRUE;
5493 }
5494 return PyErr_SetFromWindowsErr(error);
5495 }
5496
5497 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5498 if (usage == NULL) {
5499 return PyErr_NoMemory();
5500 }
5501
5502 /* Now get the actual enhanced usage property */
5503 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5504 PyMem_Free(usage);
5505 error = GetLastError();
5506 if (error == CRYPT_E_NOT_FOUND) {
5507 Py_RETURN_TRUE;
5508 }
5509 return PyErr_SetFromWindowsErr(error);
5510 }
5511 retval = PySet_New(NULL);
5512 if (retval == NULL) {
5513 goto error;
5514 }
5515 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5516 if (usage->rgpszUsageIdentifier[i]) {
5517 PyObject *oid;
5518 int err;
5519 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5520 if (oid == NULL) {
5521 Py_CLEAR(retval);
5522 goto error;
5523 }
5524 err = PySet_Add(retval, oid);
5525 Py_DECREF(oid);
5526 if (err == -1) {
5527 Py_CLEAR(retval);
5528 goto error;
5529 }
5530 }
5531 }
5532 error:
5533 PyMem_Free(usage);
5534 return retval;
5535}
5536
kctherookied93fbbf2019-03-29 00:59:06 +07005537static HCERTSTORE
5538ssl_collect_certificates(const char *store_name)
5539{
5540/* this function collects the system certificate stores listed in
5541 * system_stores into a collection certificate store for being
5542 * enumerated. The store must be readable to be added to the
5543 * store collection.
5544 */
5545
5546 HCERTSTORE hCollectionStore = NULL, hSystemStore = NULL;
5547 static DWORD system_stores[] = {
5548 CERT_SYSTEM_STORE_LOCAL_MACHINE,
5549 CERT_SYSTEM_STORE_LOCAL_MACHINE_ENTERPRISE,
5550 CERT_SYSTEM_STORE_LOCAL_MACHINE_GROUP_POLICY,
5551 CERT_SYSTEM_STORE_CURRENT_USER,
5552 CERT_SYSTEM_STORE_CURRENT_USER_GROUP_POLICY,
5553 CERT_SYSTEM_STORE_SERVICES,
5554 CERT_SYSTEM_STORE_USERS};
5555 size_t i, storesAdded;
5556 BOOL result;
5557
5558 hCollectionStore = CertOpenStore(CERT_STORE_PROV_COLLECTION, 0,
5559 (HCRYPTPROV)NULL, 0, NULL);
5560 if (!hCollectionStore) {
5561 return NULL;
5562 }
5563 storesAdded = 0;
5564 for (i = 0; i < sizeof(system_stores) / sizeof(DWORD); i++) {
5565 hSystemStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0,
5566 (HCRYPTPROV)NULL,
5567 CERT_STORE_READONLY_FLAG |
5568 system_stores[i], store_name);
5569 if (hSystemStore) {
5570 result = CertAddStoreToCollection(hCollectionStore, hSystemStore,
5571 CERT_PHYSICAL_STORE_ADD_ENABLE_FLAG, 0);
5572 if (result) {
5573 ++storesAdded;
5574 }
5575 }
5576 }
5577 if (storesAdded == 0) {
5578 CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG);
5579 return NULL;
5580 }
5581
5582 return hCollectionStore;
5583}
5584
5585/* code from Objects/listobject.c */
5586
5587static int
5588list_contains(PyListObject *a, PyObject *el)
5589{
5590 Py_ssize_t i;
5591 int cmp;
5592
5593 for (i = 0, cmp = 0 ; cmp == 0 && i < Py_SIZE(a); ++i)
5594 cmp = PyObject_RichCompareBool(el, PyList_GET_ITEM(a, i),
5595 Py_EQ);
5596 return cmp;
5597}
5598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005599/*[clinic input]
5600_ssl.enum_certificates
5601 store_name: str
5602
5603Retrieve certificates from Windows' cert store.
5604
5605store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5606more cert storages, too. The function returns a list of (bytes,
5607encoding_type, trust) tuples. The encoding_type flag can be interpreted
5608with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5609a set of OIDs or the boolean True.
5610[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005611
Christian Heimes46bebee2013-06-09 19:03:31 +02005612static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005613_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5614/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005615{
kctherookied93fbbf2019-03-29 00:59:06 +07005616 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005617 PCCERT_CONTEXT pCertCtx = NULL;
5618 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005619 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005620
Christian Heimes44109d72013-11-22 01:51:30 +01005621 result = PyList_New(0);
5622 if (result == NULL) {
5623 return NULL;
5624 }
kctherookied93fbbf2019-03-29 00:59:06 +07005625 hCollectionStore = ssl_collect_certificates(store_name);
5626 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005627 Py_DECREF(result);
5628 return PyErr_SetFromWindowsErr(GetLastError());
5629 }
5630
kctherookied93fbbf2019-03-29 00:59:06 +07005631 while (pCertCtx = CertEnumCertificatesInStore(hCollectionStore, pCertCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005632 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5633 pCertCtx->cbCertEncoded);
5634 if (!cert) {
5635 Py_CLEAR(result);
5636 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005637 }
Christian Heimes44109d72013-11-22 01:51:30 +01005638 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5639 Py_CLEAR(result);
5640 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005641 }
Christian Heimes44109d72013-11-22 01:51:30 +01005642 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5643 if (keyusage == Py_True) {
5644 Py_DECREF(keyusage);
5645 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005646 }
Christian Heimes44109d72013-11-22 01:51:30 +01005647 if (keyusage == NULL) {
5648 Py_CLEAR(result);
5649 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005650 }
Christian Heimes44109d72013-11-22 01:51:30 +01005651 if ((tup = PyTuple_New(3)) == NULL) {
5652 Py_CLEAR(result);
5653 break;
5654 }
5655 PyTuple_SET_ITEM(tup, 0, cert);
5656 cert = NULL;
5657 PyTuple_SET_ITEM(tup, 1, enc);
5658 enc = NULL;
5659 PyTuple_SET_ITEM(tup, 2, keyusage);
5660 keyusage = NULL;
kctherookied93fbbf2019-03-29 00:59:06 +07005661 if (!list_contains((PyListObject*)result, tup)) {
5662 if (PyList_Append(result, tup) < 0) {
5663 Py_CLEAR(result);
5664 break;
5665 }
Christian Heimes44109d72013-11-22 01:51:30 +01005666 }
5667 Py_CLEAR(tup);
5668 }
5669 if (pCertCtx) {
5670 /* loop ended with an error, need to clean up context manually */
5671 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005672 }
5673
5674 /* In error cases cert, enc and tup may not be NULL */
5675 Py_XDECREF(cert);
5676 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005677 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005678 Py_XDECREF(tup);
5679
kctherookied93fbbf2019-03-29 00:59:06 +07005680 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5681 associated with the store, in this case our collection store and the
5682 associated system stores. */
5683 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005684 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005685 Py_XDECREF(result);
5686 return PyErr_SetFromWindowsErr(GetLastError());
5687 }
kctherookied93fbbf2019-03-29 00:59:06 +07005688
Christian Heimes44109d72013-11-22 01:51:30 +01005689 return result;
5690}
5691
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005692/*[clinic input]
5693_ssl.enum_crls
5694 store_name: str
5695
5696Retrieve CRLs from Windows' cert store.
5697
5698store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5699more cert storages, too. The function returns a list of (bytes,
5700encoding_type) tuples. The encoding_type flag can be interpreted with
5701X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5702[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005703
5704static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005705_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5706/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005707{
kctherookied93fbbf2019-03-29 00:59:06 +07005708 HCERTSTORE hCollectionStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005709 PCCRL_CONTEXT pCrlCtx = NULL;
5710 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5711 PyObject *result = NULL;
5712
Christian Heimes44109d72013-11-22 01:51:30 +01005713 result = PyList_New(0);
5714 if (result == NULL) {
5715 return NULL;
5716 }
kctherookied93fbbf2019-03-29 00:59:06 +07005717 hCollectionStore = ssl_collect_certificates(store_name);
5718 if (hCollectionStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005719 Py_DECREF(result);
5720 return PyErr_SetFromWindowsErr(GetLastError());
5721 }
Christian Heimes44109d72013-11-22 01:51:30 +01005722
kctherookied93fbbf2019-03-29 00:59:06 +07005723 while (pCrlCtx = CertEnumCRLsInStore(hCollectionStore, pCrlCtx)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005724 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5725 pCrlCtx->cbCrlEncoded);
5726 if (!crl) {
5727 Py_CLEAR(result);
5728 break;
5729 }
5730 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5731 Py_CLEAR(result);
5732 break;
5733 }
5734 if ((tup = PyTuple_New(2)) == NULL) {
5735 Py_CLEAR(result);
5736 break;
5737 }
5738 PyTuple_SET_ITEM(tup, 0, crl);
5739 crl = NULL;
5740 PyTuple_SET_ITEM(tup, 1, enc);
5741 enc = NULL;
5742
kctherookied93fbbf2019-03-29 00:59:06 +07005743 if (!list_contains((PyListObject*)result, tup)) {
5744 if (PyList_Append(result, tup) < 0) {
5745 Py_CLEAR(result);
5746 break;
5747 }
Christian Heimes44109d72013-11-22 01:51:30 +01005748 }
5749 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005750 }
Christian Heimes44109d72013-11-22 01:51:30 +01005751 if (pCrlCtx) {
5752 /* loop ended with an error, need to clean up context manually */
5753 CertFreeCRLContext(pCrlCtx);
5754 }
5755
5756 /* In error cases cert, enc and tup may not be NULL */
5757 Py_XDECREF(crl);
5758 Py_XDECREF(enc);
5759 Py_XDECREF(tup);
5760
kctherookied93fbbf2019-03-29 00:59:06 +07005761 /* CERT_CLOSE_STORE_FORCE_FLAG forces freeing of memory for all contexts
5762 associated with the store, in this case our collection store and the
5763 associated system stores. */
5764 if (!CertCloseStore(hCollectionStore, CERT_CLOSE_STORE_FORCE_FLAG)) {
Christian Heimes44109d72013-11-22 01:51:30 +01005765 /* This error case might shadow another exception.*/
5766 Py_XDECREF(result);
5767 return PyErr_SetFromWindowsErr(GetLastError());
5768 }
5769 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005770}
Christian Heimes44109d72013-11-22 01:51:30 +01005771
5772#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005773
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005774/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005775static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005776 _SSL__TEST_DECODE_CERT_METHODDEF
5777 _SSL_RAND_ADD_METHODDEF
5778 _SSL_RAND_BYTES_METHODDEF
5779 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5780 _SSL_RAND_EGD_METHODDEF
5781 _SSL_RAND_STATUS_METHODDEF
5782 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5783 _SSL_ENUM_CERTIFICATES_METHODDEF
5784 _SSL_ENUM_CRLS_METHODDEF
5785 _SSL_TXT2OBJ_METHODDEF
5786 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005787 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005788};
5789
5790
Christian Heimes598894f2016-09-05 23:19:05 +02005791#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005792
5793/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005794 * of the Python C thread library
5795 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5796 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005797
5798static PyThread_type_lock *_ssl_locks = NULL;
5799
Christian Heimes4d98ca92013-08-19 17:36:29 +02005800#if OPENSSL_VERSION_NUMBER >= 0x10000000
5801/* use new CRYPTO_THREADID API. */
5802static void
5803_ssl_threadid_callback(CRYPTO_THREADID *id)
5804{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005805 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005806}
5807#else
5808/* deprecated CRYPTO_set_id_callback() API. */
5809static unsigned long
5810_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005811 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005812}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005813#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005814
Bill Janssen6e027db2007-11-15 22:23:56 +00005815static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005816 (int mode, int n, const char *file, int line) {
5817 /* this function is needed to perform locking on shared data
5818 structures. (Note that OpenSSL uses a number of global data
5819 structures that will be implicitly shared whenever multiple
5820 threads use OpenSSL.) Multi-threaded applications will
5821 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005823 locking_function() must be able to handle up to
5824 CRYPTO_num_locks() different mutex locks. It sets the n-th
5825 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005826
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005827 file and line are the file number of the function setting the
5828 lock. They can be useful for debugging.
5829 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005830
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005831 if ((_ssl_locks == NULL) ||
5832 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5833 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005834
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005835 if (mode & CRYPTO_LOCK) {
5836 PyThread_acquire_lock(_ssl_locks[n], 1);
5837 } else {
5838 PyThread_release_lock(_ssl_locks[n]);
5839 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005840}
5841
5842static int _setup_ssl_threads(void) {
5843
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005844 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005846 if (_ssl_locks == NULL) {
5847 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005848 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5849 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005850 if (_ssl_locks == NULL) {
5851 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005852 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005853 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005854 for (i = 0; i < _ssl_locks_count; i++) {
5855 _ssl_locks[i] = PyThread_allocate_lock();
5856 if (_ssl_locks[i] == NULL) {
5857 unsigned int j;
5858 for (j = 0; j < i; j++) {
5859 PyThread_free_lock(_ssl_locks[j]);
5860 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005861 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005862 return 0;
5863 }
5864 }
5865 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005866#if OPENSSL_VERSION_NUMBER >= 0x10000000
5867 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5868#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005869 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005870#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005871 }
5872 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005873}
5874
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005875#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005876
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005877PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005878"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005879for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005880
Martin v. Löwis1a214512008-06-11 05:26:20 +00005881
5882static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005883 PyModuleDef_HEAD_INIT,
5884 "_ssl",
5885 module_doc,
5886 -1,
5887 PySSL_methods,
5888 NULL,
5889 NULL,
5890 NULL,
5891 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005892};
5893
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005894
5895static void
5896parse_openssl_version(unsigned long libver,
5897 unsigned int *major, unsigned int *minor,
5898 unsigned int *fix, unsigned int *patch,
5899 unsigned int *status)
5900{
5901 *status = libver & 0xF;
5902 libver >>= 4;
5903 *patch = libver & 0xFF;
5904 libver >>= 8;
5905 *fix = libver & 0xFF;
5906 libver >>= 8;
5907 *minor = libver & 0xFF;
5908 libver >>= 8;
5909 *major = libver & 0xFF;
5910}
5911
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005912PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005913PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005914{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005915 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005916 unsigned long libver;
5917 unsigned int major, minor, fix, patch, status;
5918 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005919 struct py_ssl_error_code *errcode;
5920 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005921
Antoine Pitrou152efa22010-05-16 18:19:27 +00005922 if (PyType_Ready(&PySSLContext_Type) < 0)
5923 return NULL;
5924 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005925 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005926 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5927 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005928 if (PyType_Ready(&PySSLSession_Type) < 0)
5929 return NULL;
5930
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005932 m = PyModule_Create(&_sslmodule);
5933 if (m == NULL)
5934 return NULL;
5935 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005937 /* Load _socket module and its C API */
5938 socket_api = PySocketModule_ImportModuleAndAPI();
5939 if (!socket_api)
5940 return NULL;
5941 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005942
Christian Heimesc941e622017-09-05 15:47:11 +02005943#ifndef OPENSSL_VERSION_1_1
5944 /* Load all algorithms and initialize cpuid */
5945 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005946 /* Init OpenSSL */
5947 SSL_load_error_strings();
5948 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005949#endif
5950
Christian Heimes598894f2016-09-05 23:19:05 +02005951#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005952 /* note that this will start threading if not already started */
5953 if (!_setup_ssl_threads()) {
5954 return NULL;
5955 }
Christian Heimes598894f2016-09-05 23:19:05 +02005956#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5957 /* OpenSSL 1.1.0 builtin thread support is enabled */
5958 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005959#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005960
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005961 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005962 sslerror_type_slots[0].pfunc = PyExc_OSError;
5963 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005964 if (PySSLErrorObject == NULL)
5965 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005966
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005967 /* ssl.CertificateError used to be a subclass of ValueError */
5968 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5969 if (bases == NULL)
5970 return NULL;
5971 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5972 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5973 bases, NULL);
5974 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005975 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5976 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5977 PySSLErrorObject, NULL);
5978 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5979 "ssl.SSLWantReadError", SSLWantReadError_doc,
5980 PySSLErrorObject, NULL);
5981 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5982 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5983 PySSLErrorObject, NULL);
5984 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5985 "ssl.SSLSyscallError", SSLSyscallError_doc,
5986 PySSLErrorObject, NULL);
5987 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5988 "ssl.SSLEOFError", SSLEOFError_doc,
5989 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005990 if (PySSLCertVerificationErrorObject == NULL
5991 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005992 || PySSLWantReadErrorObject == NULL
5993 || PySSLWantWriteErrorObject == NULL
5994 || PySSLSyscallErrorObject == NULL
5995 || PySSLEOFErrorObject == NULL)
5996 return NULL;
5997 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005998 || PyDict_SetItemString(d, "SSLCertVerificationError",
5999 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02006000 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
6001 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
6002 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
6003 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
6004 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006005 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00006006 if (PyDict_SetItemString(d, "_SSLContext",
6007 (PyObject *)&PySSLContext_Type) != 0)
6008 return NULL;
6009 if (PyDict_SetItemString(d, "_SSLSocket",
6010 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006011 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02006012 if (PyDict_SetItemString(d, "MemoryBIO",
6013 (PyObject *)&PySSLMemoryBIO_Type) != 0)
6014 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02006015 if (PyDict_SetItemString(d, "SSLSession",
6016 (PyObject *)&PySSLSession_Type) != 0)
6017 return NULL;
6018
Christian Heimes892d66e2018-01-29 14:10:18 +01006019 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
6020 PY_SSL_DEFAULT_CIPHER_STRING);
6021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006022 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
6023 PY_SSL_ERROR_ZERO_RETURN);
6024 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
6025 PY_SSL_ERROR_WANT_READ);
6026 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
6027 PY_SSL_ERROR_WANT_WRITE);
6028 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
6029 PY_SSL_ERROR_WANT_X509_LOOKUP);
6030 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
6031 PY_SSL_ERROR_SYSCALL);
6032 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
6033 PY_SSL_ERROR_SSL);
6034 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
6035 PY_SSL_ERROR_WANT_CONNECT);
6036 /* non ssl.h errorcodes */
6037 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
6038 PY_SSL_ERROR_EOF);
6039 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
6040 PY_SSL_ERROR_INVALID_ERROR_CODE);
6041 /* cert requirements */
6042 PyModule_AddIntConstant(m, "CERT_NONE",
6043 PY_SSL_CERT_NONE);
6044 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
6045 PY_SSL_CERT_OPTIONAL);
6046 PyModule_AddIntConstant(m, "CERT_REQUIRED",
6047 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01006048 /* CRL verification for verification_flags */
6049 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
6050 0);
6051 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
6052 X509_V_FLAG_CRL_CHECK);
6053 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
6054 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
6055 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
6056 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05006057#ifdef X509_V_FLAG_TRUSTED_FIRST
6058 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
6059 X509_V_FLAG_TRUSTED_FIRST);
6060#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00006061
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006062 /* Alert Descriptions from ssl.h */
6063 /* note RESERVED constants no longer intended for use have been removed */
6064 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
6065
6066#define ADD_AD_CONSTANT(s) \
6067 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
6068 SSL_AD_##s)
6069
6070 ADD_AD_CONSTANT(CLOSE_NOTIFY);
6071 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
6072 ADD_AD_CONSTANT(BAD_RECORD_MAC);
6073 ADD_AD_CONSTANT(RECORD_OVERFLOW);
6074 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
6075 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
6076 ADD_AD_CONSTANT(BAD_CERTIFICATE);
6077 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
6078 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
6079 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
6080 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
6081 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
6082 ADD_AD_CONSTANT(UNKNOWN_CA);
6083 ADD_AD_CONSTANT(ACCESS_DENIED);
6084 ADD_AD_CONSTANT(DECODE_ERROR);
6085 ADD_AD_CONSTANT(DECRYPT_ERROR);
6086 ADD_AD_CONSTANT(PROTOCOL_VERSION);
6087 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
6088 ADD_AD_CONSTANT(INTERNAL_ERROR);
6089 ADD_AD_CONSTANT(USER_CANCELLED);
6090 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006091 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01006092#ifdef SSL_AD_UNSUPPORTED_EXTENSION
6093 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
6094#endif
6095#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
6096 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
6097#endif
6098#ifdef SSL_AD_UNRECOGNIZED_NAME
6099 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
6100#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01006101#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
6102 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
6103#endif
6104#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
6105 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
6106#endif
6107#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
6108 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
6109#endif
6110
6111#undef ADD_AD_CONSTANT
6112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006113 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02006114#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006115 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
6116 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02006117#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05006118#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006119 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
6120 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05006121#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006122 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02006123 PY_SSL_VERSION_TLS);
6124 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
6125 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02006126 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
6127 PY_SSL_VERSION_TLS_CLIENT);
6128 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
6129 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006130 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
6131 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006132#if HAVE_TLSv1_2
6133 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
6134 PY_SSL_VERSION_TLS1_1);
6135 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
6136 PY_SSL_VERSION_TLS1_2);
6137#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006138
Antoine Pitroub5218772010-05-21 09:56:06 +00006139 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01006140 PyModule_AddIntConstant(m, "OP_ALL",
6141 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00006142 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
6143 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
6144 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01006145#if HAVE_TLSv1_2
6146 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
6147 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
6148#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006149#ifdef SSL_OP_NO_TLSv1_3
6150 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
6151#else
6152 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
6153#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01006154 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
6155 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01006156 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02006157 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006158#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01006159 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01006160#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01006161#ifdef SSL_OP_NO_COMPRESSION
6162 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
6163 SSL_OP_NO_COMPRESSION);
6164#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01006165#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
6166 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
6167 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
6168#endif
Christian Heimes67c48012018-05-15 16:25:40 -04006169#ifdef SSL_OP_NO_RENEGOTIATION
6170 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
6171 SSL_OP_NO_RENEGOTIATION);
6172#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00006173
Christian Heimes61d478c2018-01-27 15:51:38 +01006174#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
6175 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
6176 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
6177#endif
6178#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
6179 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
6180 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
6181#endif
6182#ifdef X509_CHECK_FLAG_NO_WILDCARDS
6183 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
6184 X509_CHECK_FLAG_NO_WILDCARDS);
6185#endif
6186#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
6187 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
6188 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
6189#endif
6190#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
6191 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
6192 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
6193#endif
6194#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
6195 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
6196 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
6197#endif
6198
Christian Heimes698dde12018-02-27 11:54:43 +01006199 /* protocol versions */
6200 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
6201 PY_PROTO_MINIMUM_SUPPORTED);
6202 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
6203 PY_PROTO_MAXIMUM_SUPPORTED);
6204 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
6205 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
6206 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
6207 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
6208 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00006209
Victor Stinnerb37672d2018-11-22 03:37:50 +01006210#define addbool(m, key, value) \
6211 do { \
6212 PyObject *bool_obj = (value) ? Py_True : Py_False; \
6213 Py_INCREF(bool_obj); \
6214 PyModule_AddObject((m), (key), bool_obj); \
6215 } while (0)
Christian Heimes698dde12018-02-27 11:54:43 +01006216
6217#if HAVE_SNI
6218 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01006219#else
Christian Heimes698dde12018-02-27 11:54:43 +01006220 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01006221#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006222
6223 addbool(m, "HAS_TLS_UNIQUE", 1);
6224
6225#ifndef OPENSSL_NO_ECDH
6226 addbool(m, "HAS_ECDH", 1);
6227#else
6228 addbool(m, "HAS_ECDH", 0);
6229#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01006230
Christian Heimes29eab552018-02-25 12:31:33 +01006231#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01006232 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006233#else
Christian Heimes698dde12018-02-27 11:54:43 +01006234 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006235#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01006236
Christian Heimes29eab552018-02-25 12:31:33 +01006237#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01006238 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006239#else
Christian Heimes698dde12018-02-27 11:54:43 +01006240 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05006241#endif
Christian Heimes698dde12018-02-27 11:54:43 +01006242
6243#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
6244 addbool(m, "HAS_SSLv2", 1);
6245#else
6246 addbool(m, "HAS_SSLv2", 0);
6247#endif
6248
6249#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
6250 addbool(m, "HAS_SSLv3", 1);
6251#else
6252 addbool(m, "HAS_SSLv3", 0);
6253#endif
6254
6255#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
6256 addbool(m, "HAS_TLSv1", 1);
6257#else
6258 addbool(m, "HAS_TLSv1", 0);
6259#endif
6260
6261#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
6262 addbool(m, "HAS_TLSv1_1", 1);
6263#else
6264 addbool(m, "HAS_TLSv1_1", 0);
6265#endif
6266
6267#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
6268 addbool(m, "HAS_TLSv1_2", 1);
6269#else
6270 addbool(m, "HAS_TLSv1_2", 0);
6271#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05006272
Christian Heimescb5b68a2017-09-07 18:07:00 -07006273#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01006274 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006275#else
Christian Heimes698dde12018-02-27 11:54:43 +01006276 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07006277#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07006278
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02006279 /* Mappings for error codes */
6280 err_codes_to_names = PyDict_New();
6281 err_names_to_codes = PyDict_New();
6282 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
6283 return NULL;
6284 errcode = error_codes;
6285 while (errcode->mnemonic != NULL) {
6286 PyObject *mnemo, *key;
6287 mnemo = PyUnicode_FromString(errcode->mnemonic);
6288 key = Py_BuildValue("ii", errcode->library, errcode->reason);
6289 if (mnemo == NULL || key == NULL)
6290 return NULL;
6291 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
6292 return NULL;
6293 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
6294 return NULL;
6295 Py_DECREF(key);
6296 Py_DECREF(mnemo);
6297 errcode++;
6298 }
6299 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
6300 return NULL;
6301 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
6302 return NULL;
6303
6304 lib_codes_to_names = PyDict_New();
6305 if (lib_codes_to_names == NULL)
6306 return NULL;
6307 libcode = library_codes;
6308 while (libcode->library != NULL) {
6309 PyObject *mnemo, *key;
6310 key = PyLong_FromLong(libcode->code);
6311 mnemo = PyUnicode_FromString(libcode->library);
6312 if (key == NULL || mnemo == NULL)
6313 return NULL;
6314 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6315 return NULL;
6316 Py_DECREF(key);
6317 Py_DECREF(mnemo);
6318 libcode++;
6319 }
6320 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6321 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006323 /* OpenSSL version */
6324 /* SSLeay() gives us the version of the library linked against,
6325 which could be different from the headers version.
6326 */
6327 libver = SSLeay();
6328 r = PyLong_FromUnsignedLong(libver);
6329 if (r == NULL)
6330 return NULL;
6331 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6332 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006333 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006334 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6335 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6336 return NULL;
6337 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6338 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6339 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006340
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006341 libver = OPENSSL_VERSION_NUMBER;
6342 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6343 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6344 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6345 return NULL;
6346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006347 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006348}