blob: 5b5d7dd445d27bb8dd95667876e667c2f87e5596 [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
Victor Stinner524714e2016-07-22 17:43:59 +0200188#ifndef INVALID_SOCKET /* MS defines this */
189#define INVALID_SOCKET (-1)
190#endif
191
Christian Heimes4ca07392018-03-24 15:41:37 +0100192/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
193#ifndef OPENSSL_VERSION_1_1
194#define HAVE_OPENSSL_CRYPTO_LOCK
195#endif
196
197#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200198#define OPENSSL_NO_SSL2
199#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100200
201#ifndef PY_OPENSSL_1_1_API
202/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200203
204#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200205#define TLS_client_method SSLv23_client_method
206#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200207
208static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
209{
210 return ne->set;
211}
212
213#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200214/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200215static int COMP_get_type(const COMP_METHOD *meth)
216{
217 return meth->type;
218}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200219/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200220#endif
221
222static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
223{
224 return ctx->default_passwd_callback;
225}
226
227static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
228{
229 return ctx->default_passwd_callback_userdata;
230}
231
232static int X509_OBJECT_get_type(X509_OBJECT *x)
233{
234 return x->type;
235}
236
237static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
238{
239 return x->data.x509;
240}
241
242static int BIO_up_ref(BIO *b)
243{
244 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
245 return 1;
246}
247
248static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
249 return store->objs;
250}
251
Christian Heimes99a65702016-09-10 23:44:53 +0200252static int
253SSL_SESSION_has_ticket(const SSL_SESSION *s)
254{
255 return (s->tlsext_ticklen > 0) ? 1 : 0;
256}
257
258static unsigned long
259SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
260{
261 return s->tlsext_tick_lifetime_hint;
262}
263
Christian Heimes4ca07392018-03-24 15:41:37 +0100264#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200265
Christian Heimes892d66e2018-01-29 14:10:18 +0100266/* Default cipher suites */
267#ifndef PY_SSL_DEFAULT_CIPHERS
268#define PY_SSL_DEFAULT_CIPHERS 1
269#endif
270
271#if PY_SSL_DEFAULT_CIPHERS == 0
272 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
273 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
274 #endif
275#elif PY_SSL_DEFAULT_CIPHERS == 1
276/* Python custom selection of sensible ciper suites
277 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
278 * !aNULL:!eNULL: really no NULL ciphers
279 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
280 * !aDSS: no authentication with discrete logarithm DSA algorithm
281 * !SRP:!PSK: no secure remote password or pre-shared key authentication
282 */
283 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
284#elif PY_SSL_DEFAULT_CIPHERS == 2
285/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
286 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
287#else
288 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
289#endif
290
Christian Heimes598894f2016-09-05 23:19:05 +0200291
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000292enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000293 /* these mirror ssl.h */
294 PY_SSL_ERROR_NONE,
295 PY_SSL_ERROR_SSL,
296 PY_SSL_ERROR_WANT_READ,
297 PY_SSL_ERROR_WANT_WRITE,
298 PY_SSL_ERROR_WANT_X509_LOOKUP,
299 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
300 PY_SSL_ERROR_ZERO_RETURN,
301 PY_SSL_ERROR_WANT_CONNECT,
302 /* start of non ssl.h errorcodes */
303 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
304 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
305 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000306};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000307
Thomas Woutersed03b412007-08-28 21:37:11 +0000308enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 PY_SSL_CLIENT,
310 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000311};
312
313enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000314 PY_SSL_CERT_NONE,
315 PY_SSL_CERT_OPTIONAL,
316 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000317};
318
319enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000320 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200321 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200322 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100323#if HAVE_TLSv1_2
324 PY_SSL_VERSION_TLS1,
325 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200326 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100327#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200328 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000329#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200330 PY_SSL_VERSION_TLS_CLIENT=0x10,
331 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100332};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200333
Christian Heimes698dde12018-02-27 11:54:43 +0100334enum py_proto_version {
335 PY_PROTO_MINIMUM_SUPPORTED = -2,
336 PY_PROTO_SSLv3 = SSL3_VERSION,
337 PY_PROTO_TLSv1 = TLS1_VERSION,
338 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
339 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
340#ifdef TLS1_3_VERSION
341 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
342#else
343 PY_PROTO_TLSv1_3 = 0x304,
344#endif
345 PY_PROTO_MAXIMUM_SUPPORTED = -1,
346
347/* OpenSSL has no dedicated API to set the minimum version to the maximum
348 * available version, and the other way around. We have to figure out the
349 * minimum and maximum available version on our own and hope for the best.
350 */
351#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
352 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
353#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
354 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
355#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
356 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
357#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
358 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
359#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
360 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
361#else
362 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
363#endif
364
365#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
366 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
367#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
368 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
369#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
370 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
371#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
372 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
373#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
374 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
375#else
376 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
377#endif
378};
379
380
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000381/* serves as a flag to see whether we've initialized the SSL thread support. */
382/* 0 means no, greater than 0 means yes */
383
384static unsigned int _ssl_locks_count = 0;
385
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000386/* SSL socket object */
387
388#define X509_NAME_MAXLEN 256
389
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000390/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
391 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
392 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
393#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000394# define HAVE_SSL_CTX_CLEAR_OPTIONS
395#else
396# undef HAVE_SSL_CTX_CLEAR_OPTIONS
397#endif
398
Antoine Pitroud6494802011-07-21 01:11:30 +0200399/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
400 * older SSL, but let's be safe */
401#define PySSL_CB_MAXLEN 128
402
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100403
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000404typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000405 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000406 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100407#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500408 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100409 int npn_protocols_len;
410#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100411#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500412 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300413 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500414#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100415#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100416 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100417#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100418 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100419 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
420 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
421 */
422 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100423 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000424} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000425
Antoine Pitrou152efa22010-05-16 18:19:27 +0000426typedef struct {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700427 int ssl; /* last seen error from SSL */
428 int c; /* last seen error from libc */
429#ifdef MS_WINDOWS
430 int ws; /* last seen error from winsock */
431#endif
432} _PySSLError;
433
434typedef struct {
Antoine Pitrou152efa22010-05-16 18:19:27 +0000435 PyObject_HEAD
436 PyObject *Socket; /* weakref to socket on which we're layered */
437 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100438 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200439 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200440 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200441 PyObject *owner; /* Python level "owner" passed to servername callback */
442 PyObject *server_hostname;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700443 _PySSLError err; /* last seen error from various sources */
Antoine Pitrou152efa22010-05-16 18:19:27 +0000444} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000445
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200446typedef struct {
447 PyObject_HEAD
448 BIO *bio;
449 int eof_written;
450} PySSLMemoryBIO;
451
Christian Heimes99a65702016-09-10 23:44:53 +0200452typedef struct {
453 PyObject_HEAD
454 SSL_SESSION *session;
455 PySSLContext *ctx;
456} PySSLSession;
457
Antoine Pitrou152efa22010-05-16 18:19:27 +0000458static PyTypeObject PySSLContext_Type;
459static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200460static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200461static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000462
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700463static inline _PySSLError _PySSL_errno(int failed, const SSL *ssl, int retcode)
464{
465 _PySSLError err = { 0 };
466 if (failed) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700467#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700468 err.ws = WSAGetLastError();
469 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700470#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700471 err.c = errno;
472 err.ssl = SSL_get_error(ssl, retcode);
473 }
474 return err;
475}
Steve Dowere6eb48c2017-09-08 15:16:15 -0700476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300477/*[clinic input]
478module _ssl
479class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
480class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
481class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200482class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300483[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200484/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300485
486#include "clinic/_ssl.c.h"
487
Victor Stinner14690702015-04-06 22:46:13 +0200488static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000489
Christian Heimes141c5e82018-02-24 21:10:57 +0100490static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
491static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000492#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200493#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200494#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000495
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000496typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000497 SOCKET_IS_NONBLOCKING,
498 SOCKET_IS_BLOCKING,
499 SOCKET_HAS_TIMED_OUT,
500 SOCKET_HAS_BEEN_CLOSED,
501 SOCKET_TOO_LARGE_FOR_SELECT,
502 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000503} timeout_state;
504
Thomas Woutersed03b412007-08-28 21:37:11 +0000505/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000506#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200507#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000508
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200509/* Get the socket from a PySSLSocket, if it has one */
510#define GET_SOCKET(obj) ((obj)->Socket ? \
511 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200512
Victor Stinner14690702015-04-06 22:46:13 +0200513/* If sock is NULL, use a timeout of 0 second */
514#define GET_SOCKET_TIMEOUT(sock) \
515 ((sock != NULL) ? (sock)->sock_timeout : 0)
516
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200517/*
518 * SSL errors.
519 */
520
521PyDoc_STRVAR(SSLError_doc,
522"An error occurred in the SSL implementation.");
523
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700524PyDoc_STRVAR(SSLCertVerificationError_doc,
525"A certificate could not be verified.");
526
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527PyDoc_STRVAR(SSLZeroReturnError_doc,
528"SSL/TLS session closed cleanly.");
529
530PyDoc_STRVAR(SSLWantReadError_doc,
531"Non-blocking SSL socket needs to read more data\n"
532"before the requested operation can be completed.");
533
534PyDoc_STRVAR(SSLWantWriteError_doc,
535"Non-blocking SSL socket needs to write more data\n"
536"before the requested operation can be completed.");
537
538PyDoc_STRVAR(SSLSyscallError_doc,
539"System error when attempting SSL operation.");
540
541PyDoc_STRVAR(SSLEOFError_doc,
542"SSL/TLS connection terminated abruptly.");
543
544static PyObject *
545SSLError_str(PyOSErrorObject *self)
546{
547 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
548 Py_INCREF(self->strerror);
549 return self->strerror;
550 }
551 else
552 return PyObject_Str(self->args);
553}
554
555static PyType_Slot sslerror_type_slots[] = {
556 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
557 {Py_tp_doc, SSLError_doc},
558 {Py_tp_str, SSLError_str},
559 {0, 0},
560};
561
562static PyType_Spec sslerror_type_spec = {
563 "ssl.SSLError",
564 sizeof(PyOSErrorObject),
565 0,
566 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
567 sslerror_type_slots
568};
569
570static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
572 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200573{
574 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700575 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200576 PyObject *init_value, *msg, *key;
577 _Py_IDENTIFIER(reason);
578 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700579 _Py_IDENTIFIER(verify_message);
580 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200581
582 if (errcode != 0) {
583 int lib, reason;
584
585 lib = ERR_GET_LIB(errcode);
586 reason = ERR_GET_REASON(errcode);
587 key = Py_BuildValue("ii", lib, reason);
588 if (key == NULL)
589 goto fail;
590 reason_obj = PyDict_GetItem(err_codes_to_names, key);
591 Py_DECREF(key);
592 if (reason_obj == NULL) {
593 /* XXX if reason < 100, it might reflect a library number (!!) */
594 PyErr_Clear();
595 }
596 key = PyLong_FromLong(lib);
597 if (key == NULL)
598 goto fail;
599 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
600 Py_DECREF(key);
601 if (lib_obj == NULL) {
602 PyErr_Clear();
603 }
604 if (errstr == NULL)
605 errstr = ERR_reason_error_string(errcode);
606 }
607 if (errstr == NULL)
608 errstr = "unknown error";
609
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700610 /* verify code for cert validation error */
611 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
612 const char *verify_str = NULL;
613 long verify_code;
614
615 verify_code = SSL_get_verify_result(sslsock->ssl);
616 verify_code_obj = PyLong_FromLong(verify_code);
617 if (verify_code_obj == NULL) {
618 goto fail;
619 }
620
621 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700622#ifdef X509_V_ERR_HOSTNAME_MISMATCH
623 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700624 case X509_V_ERR_HOSTNAME_MISMATCH:
625 verify_obj = PyUnicode_FromFormat(
626 "Hostname mismatch, certificate is not valid for '%S'.",
627 sslsock->server_hostname
628 );
629 break;
Christian Heimes09153602017-09-08 14:47:58 -0700630#endif
631#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700632 case X509_V_ERR_IP_ADDRESS_MISMATCH:
633 verify_obj = PyUnicode_FromFormat(
634 "IP address mismatch, certificate is not valid for '%S'.",
635 sslsock->server_hostname
636 );
637 break;
Christian Heimes09153602017-09-08 14:47:58 -0700638#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700639 default:
640 verify_str = X509_verify_cert_error_string(verify_code);
641 if (verify_str != NULL) {
642 verify_obj = PyUnicode_FromString(verify_str);
643 } else {
644 verify_obj = Py_None;
645 Py_INCREF(verify_obj);
646 }
647 break;
648 }
649 if (verify_obj == NULL) {
650 goto fail;
651 }
652 }
653
654 if (verify_obj && reason_obj && lib_obj)
655 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
656 lib_obj, reason_obj, errstr, verify_obj,
657 lineno);
658 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200659 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
660 lib_obj, reason_obj, errstr, lineno);
661 else if (lib_obj)
662 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
663 lib_obj, errstr, lineno);
664 else
665 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200666 if (msg == NULL)
667 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100668
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200669 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100670 if (init_value == NULL)
671 goto fail;
672
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200673 err_value = PyObject_CallObject(type, init_value);
674 Py_DECREF(init_value);
675 if (err_value == NULL)
676 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100677
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200678 if (reason_obj == NULL)
679 reason_obj = Py_None;
680 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
681 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700682
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200683 if (lib_obj == NULL)
684 lib_obj = Py_None;
685 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
686 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700687
688 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
689 /* Only set verify code / message for SSLCertVerificationError */
690 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
691 verify_code_obj))
692 goto fail;
693 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
694 goto fail;
695 }
696
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200697 PyErr_SetObject(type, err_value);
698fail:
699 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700700 Py_XDECREF(verify_code_obj);
701 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200702}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000703
704static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700705PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000706{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200707 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200708 char *errstr = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700709 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000710 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200711 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000712
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200714 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000715
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700716 if (sslsock->ssl != NULL) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700717 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000718
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700719 switch (err.ssl) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000720 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200721 errstr = "TLS/SSL connection has been closed (EOF)";
722 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 p = PY_SSL_ERROR_ZERO_RETURN;
724 break;
725 case SSL_ERROR_WANT_READ:
726 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200727 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728 p = PY_SSL_ERROR_WANT_READ;
729 break;
730 case SSL_ERROR_WANT_WRITE:
731 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200732 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 errstr = "The operation did not complete (write)";
734 break;
735 case SSL_ERROR_WANT_X509_LOOKUP:
736 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000737 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 break;
739 case SSL_ERROR_WANT_CONNECT:
740 p = PY_SSL_ERROR_WANT_CONNECT;
741 errstr = "The operation did not complete (connect)";
742 break;
743 case SSL_ERROR_SYSCALL:
744 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000745 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700746 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000747 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000748 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200749 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000750 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200751 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000752 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000753 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700754#ifdef MS_WINDOWS
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700755 if (err.ws) {
756 return PyErr_SetFromWindowsErr(err.ws);
757 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700758#endif
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700759 if (err.c) {
760 errno = err.c;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700761 return PyErr_SetFromErrno(PyExc_OSError);
762 }
763 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200764 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000765 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200766 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000767 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000768 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200769 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000770 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000771 }
772 } else {
773 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 }
775 break;
776 }
777 case SSL_ERROR_SSL:
778 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700780 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200781 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000782 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700783 }
784 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
785 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
786 type = PySSLCertVerificationErrorObject;
787 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000788 break;
789 }
790 default:
791 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
792 errstr = "Invalid error code";
793 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700795 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000796 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000798}
799
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000800static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200801_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000802
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200803 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200805 else
806 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700807 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000808 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000810}
811
Christian Heimes61d478c2018-01-27 15:51:38 +0100812/*
813 * SSL objects
814 */
815
816static int
817_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
818{
819 int retval = -1;
820 ASN1_OCTET_STRING *ip;
821 PyObject *hostname;
822 size_t len;
823
824 assert(server_hostname);
825
826 /* Disable OpenSSL's special mode with leading dot in hostname:
827 * When name starts with a dot (e.g ".example.com"), it will be
828 * matched by a certificate valid for any sub-domain of name.
829 */
830 len = strlen(server_hostname);
831 if (len == 0 || *server_hostname == '.') {
832 PyErr_SetString(
833 PyExc_ValueError,
834 "server_hostname cannot be an empty string or start with a "
835 "leading dot.");
836 return retval;
837 }
838
839 /* inet_pton is not available on all platforms. */
840 ip = a2i_IPADDRESS(server_hostname);
841 if (ip == NULL) {
842 ERR_clear_error();
843 }
844
Christian Heimes11a14932018-02-24 02:35:08 +0100845 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100846 if (hostname == NULL) {
847 goto error;
848 }
849 self->server_hostname = hostname;
850
851 /* Only send SNI extension for non-IP hostnames */
852 if (ip == NULL) {
853 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
854 _setSSLError(NULL, 0, __FILE__, __LINE__);
855 }
856 }
857 if (self->ctx->check_hostname) {
858 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
859 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200860 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
861 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100862 _setSSLError(NULL, 0, __FILE__, __LINE__);
863 goto error;
864 }
865 } else {
866 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
867 ASN1_STRING_length(ip))) {
868 _setSSLError(NULL, 0, __FILE__, __LINE__);
869 goto error;
870 }
871 }
872 }
873 retval = 0;
874 error:
875 if (ip != NULL) {
876 ASN1_OCTET_STRING_free(ip);
877 }
878 return retval;
879}
880
Antoine Pitrou152efa22010-05-16 18:19:27 +0000881static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100882newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000883 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200884 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100885 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200886 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000887{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000888 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100889 SSL_CTX *ctx = sslctx->ctx;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700890 _PySSLError err = { 0 };
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000891
Antoine Pitrou152efa22010-05-16 18:19:27 +0000892 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 if (self == NULL)
894 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000895
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000897 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100898 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700899 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200900 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200901 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700902 self->server_hostname = NULL;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700903 self->err = err;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200904
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000905 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000909 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200911 SSL_set_app_data(self->ssl, self);
912 if (sock) {
913 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
914 } else {
915 /* BIOs are reference counted and SSL_set_bio borrows our reference.
916 * To prevent a double free in memory_bio_dealloc() we need to take an
917 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200918 BIO_up_ref(inbio->bio);
919 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200920 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
921 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400922 SSL_set_mode(self->ssl,
923 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000924
Christian Heimes61d478c2018-01-27 15:51:38 +0100925 if (server_hostname != NULL) {
926 if (_ssl_configure_hostname(self, server_hostname) < 0) {
927 Py_DECREF(self);
928 return NULL;
929 }
930 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 /* If the socket is in non-blocking mode or timeout mode, set the BIO
932 * to non-blocking mode (blocking is the default)
933 */
Victor Stinnere2452312015-03-28 03:00:46 +0100934 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
936 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
937 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 PySSL_BEGIN_ALLOW_THREADS
940 if (socket_type == PY_SSL_CLIENT)
941 SSL_set_connect_state(self->ssl);
942 else
943 SSL_set_accept_state(self->ssl);
944 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000945
Antoine Pitroud6494802011-07-21 01:11:30 +0200946 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200947 if (sock != NULL) {
948 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
949 if (self->Socket == NULL) {
950 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200951 return NULL;
952 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100953 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100954 if (owner && owner != Py_None) {
955 if (PySSL_set_owner(self, owner, NULL) == -1) {
956 Py_DECREF(self);
957 return NULL;
958 }
959 }
960 if (session && session != Py_None) {
961 if (PySSL_set_session(self, session, NULL) == -1) {
962 Py_DECREF(self);
963 return NULL;
964 }
965 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000967}
968
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000969/* SSL object methods */
970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300971/*[clinic input]
972_ssl._SSLSocket.do_handshake
973[clinic start generated code]*/
974
975static PyObject *
976_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
977/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000978{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 int ret;
Steve Dowerc6fd1c12018-09-17 11:34:47 -0700980 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200982 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200983 _PyTime_t timeout, deadline = 0;
984 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000985
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200986 if (sock) {
987 if (((PyObject*)sock) == Py_None) {
988 _setSSLError("Underlying socket connection gone",
989 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
990 return NULL;
991 }
992 Py_INCREF(sock);
993
994 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100995 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200996 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
997 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000999
Victor Stinner14690702015-04-06 22:46:13 +02001000 timeout = GET_SOCKET_TIMEOUT(sock);
1001 has_timeout = (timeout > 0);
1002 if (has_timeout)
1003 deadline = _PyTime_GetMonotonicClock() + timeout;
1004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 /* Actually negotiate SSL connection */
1006 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001008 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 ret = SSL_do_handshake(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001010 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001012 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001013
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001014 if (PyErr_CheckSignals())
1015 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001016
Victor Stinner14690702015-04-06 22:46:13 +02001017 if (has_timeout)
1018 timeout = deadline - _PyTime_GetMonotonicClock();
1019
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001020 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001021 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001022 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001023 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 } else {
1025 sockstate = SOCKET_OPERATION_OK;
1026 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001029 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001030 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001031 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1033 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001034 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001035 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1037 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001038 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001039 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1041 break;
1042 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07001043 } while (err.ssl == SSL_ERROR_WANT_READ ||
1044 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001045 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 if (ret < 1)
1047 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001048
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001049 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001050
1051error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001052 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001053 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001054}
1055
Thomas Woutersed03b412007-08-28 21:37:11 +00001056static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001057_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1058{
1059 char buf[X509_NAME_MAXLEN];
1060 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001062 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001063
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001064 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 if (buflen < 0) {
1066 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001067 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001069 /* initial buffer is too small for oid + terminating null byte */
1070 if (buflen > X509_NAME_MAXLEN - 1) {
1071 /* make OBJ_obj2txt() calculate the required buflen */
1072 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1073 /* allocate len + 1 for terminating NULL byte */
1074 namebuf = PyMem_Malloc(buflen + 1);
1075 if (namebuf == NULL) {
1076 PyErr_NoMemory();
1077 return NULL;
1078 }
1079 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1080 if (buflen < 0) {
1081 _setSSLError(NULL, 0, __FILE__, __LINE__);
1082 goto done;
1083 }
1084 }
1085 if (!buflen && no_name) {
1086 Py_INCREF(Py_None);
1087 name_obj = Py_None;
1088 }
1089 else {
1090 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1091 }
1092
1093 done:
1094 if (buf != namebuf) {
1095 PyMem_Free(namebuf);
1096 }
1097 return name_obj;
1098}
1099
1100static PyObject *
1101_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1102{
1103 Py_ssize_t buflen;
1104 unsigned char *valuebuf = NULL;
1105 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001106
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001107 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1108 if (buflen < 0) {
1109 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001110 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001112 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001115}
1116
1117static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001119{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1121 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1122 PyObject *rdnt;
1123 PyObject *attr = NULL; /* tuple to hold an attribute */
1124 int entry_count = X509_NAME_entry_count(xname);
1125 X509_NAME_ENTRY *entry;
1126 ASN1_OBJECT *name;
1127 ASN1_STRING *value;
1128 int index_counter;
1129 int rdn_level = -1;
1130 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001131
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001132 dn = PyList_New(0);
1133 if (dn == NULL)
1134 return NULL;
1135 /* now create another tuple to hold the top-level RDN */
1136 rdn = PyList_New(0);
1137 if (rdn == NULL)
1138 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 for (index_counter = 0;
1141 index_counter < entry_count;
1142 index_counter++)
1143 {
1144 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 /* check to see if we've gotten to a new RDN */
1147 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001148 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 /* yes, new RDN */
1150 /* add old RDN to DN */
1151 rdnt = PyList_AsTuple(rdn);
1152 Py_DECREF(rdn);
1153 if (rdnt == NULL)
1154 goto fail0;
1155 retcode = PyList_Append(dn, rdnt);
1156 Py_DECREF(rdnt);
1157 if (retcode < 0)
1158 goto fail0;
1159 /* create new RDN */
1160 rdn = PyList_New(0);
1161 if (rdn == NULL)
1162 goto fail0;
1163 }
1164 }
Christian Heimes598894f2016-09-05 23:19:05 +02001165 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 /* now add this attribute to the current RDN */
1168 name = X509_NAME_ENTRY_get_object(entry);
1169 value = X509_NAME_ENTRY_get_data(entry);
1170 attr = _create_tuple_for_attribute(name, value);
1171 /*
1172 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1173 entry->set,
1174 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1175 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1176 */
1177 if (attr == NULL)
1178 goto fail1;
1179 retcode = PyList_Append(rdn, attr);
1180 Py_DECREF(attr);
1181 if (retcode < 0)
1182 goto fail1;
1183 }
1184 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001185 if (rdn != NULL) {
1186 if (PyList_GET_SIZE(rdn) > 0) {
1187 rdnt = PyList_AsTuple(rdn);
1188 Py_DECREF(rdn);
1189 if (rdnt == NULL)
1190 goto fail0;
1191 retcode = PyList_Append(dn, rdnt);
1192 Py_DECREF(rdnt);
1193 if (retcode < 0)
1194 goto fail0;
1195 }
1196 else {
1197 Py_DECREF(rdn);
1198 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 /* convert list to tuple */
1202 rdnt = PyList_AsTuple(dn);
1203 Py_DECREF(dn);
1204 if (rdnt == NULL)
1205 return NULL;
1206 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
1208 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001210
1211 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001212 Py_XDECREF(dn);
1213 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001214}
1215
1216static PyObject *
1217_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 /* this code follows the procedure outlined in
1220 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1221 function to extract the STACK_OF(GENERAL_NAME),
1222 then iterates through the stack to add the
1223 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001224
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001225 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001227 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 GENERAL_NAMES *names = NULL;
1229 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 BIO *biobuf = NULL;
1231 char buf[2048];
1232 char *vptr;
1233 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 if (certificate == NULL)
1236 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001238 /* get a memory buffer */
1239 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001240
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001241 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1242 certificate, NID_subject_alt_name, NULL, NULL);
1243 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001244 if (peer_alt_names == Py_None) {
1245 peer_alt_names = PyList_New(0);
1246 if (peer_alt_names == NULL)
1247 goto fail;
1248 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001252 int gntype;
1253 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001254
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001255 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001256 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001257 switch (gntype) {
1258 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 /* we special-case DirName as a tuple of
1260 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001262 t = PyTuple_New(2);
1263 if (t == NULL) {
1264 goto fail;
1265 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001267 v = PyUnicode_FromString("DirName");
1268 if (v == NULL) {
1269 Py_DECREF(t);
1270 goto fail;
1271 }
1272 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 v = _create_tuple_for_X509_NAME (name->d.dirn);
1275 if (v == NULL) {
1276 Py_DECREF(t);
1277 goto fail;
1278 }
1279 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001280 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001281
Christian Heimes824f7f32013-08-17 00:54:47 +02001282 case GEN_EMAIL:
1283 case GEN_DNS:
1284 case GEN_URI:
1285 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1286 correctly, CVE-2013-4238 */
1287 t = PyTuple_New(2);
1288 if (t == NULL)
1289 goto fail;
1290 switch (gntype) {
1291 case GEN_EMAIL:
1292 v = PyUnicode_FromString("email");
1293 as = name->d.rfc822Name;
1294 break;
1295 case GEN_DNS:
1296 v = PyUnicode_FromString("DNS");
1297 as = name->d.dNSName;
1298 break;
1299 case GEN_URI:
1300 v = PyUnicode_FromString("URI");
1301 as = name->d.uniformResourceIdentifier;
1302 break;
1303 }
1304 if (v == NULL) {
1305 Py_DECREF(t);
1306 goto fail;
1307 }
1308 PyTuple_SET_ITEM(t, 0, v);
1309 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1310 ASN1_STRING_length(as));
1311 if (v == NULL) {
1312 Py_DECREF(t);
1313 goto fail;
1314 }
1315 PyTuple_SET_ITEM(t, 1, v);
1316 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001317
Christian Heimes1c03abd2016-09-06 23:25:35 +02001318 case GEN_RID:
1319 t = PyTuple_New(2);
1320 if (t == NULL)
1321 goto fail;
1322
1323 v = PyUnicode_FromString("Registered ID");
1324 if (v == NULL) {
1325 Py_DECREF(t);
1326 goto fail;
1327 }
1328 PyTuple_SET_ITEM(t, 0, v);
1329
1330 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1331 if (len < 0) {
1332 Py_DECREF(t);
1333 _setSSLError(NULL, 0, __FILE__, __LINE__);
1334 goto fail;
1335 } else if (len >= (int)sizeof(buf)) {
1336 v = PyUnicode_FromString("<INVALID>");
1337 } else {
1338 v = PyUnicode_FromStringAndSize(buf, len);
1339 }
1340 if (v == NULL) {
1341 Py_DECREF(t);
1342 goto fail;
1343 }
1344 PyTuple_SET_ITEM(t, 1, v);
1345 break;
1346
Christian Heimes824f7f32013-08-17 00:54:47 +02001347 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001349 switch (gntype) {
1350 /* check for new general name type */
1351 case GEN_OTHERNAME:
1352 case GEN_X400:
1353 case GEN_EDIPARTY:
1354 case GEN_IPADD:
1355 case GEN_RID:
1356 break;
1357 default:
1358 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1359 "Unknown general name type %d",
1360 gntype) == -1) {
1361 goto fail;
1362 }
1363 break;
1364 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 (void) BIO_reset(biobuf);
1366 GENERAL_NAME_print(biobuf, name);
1367 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1368 if (len < 0) {
1369 _setSSLError(NULL, 0, __FILE__, __LINE__);
1370 goto fail;
1371 }
1372 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001373 if (vptr == NULL) {
1374 PyErr_Format(PyExc_ValueError,
1375 "Invalid value %.200s",
1376 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001378 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 t = PyTuple_New(2);
1380 if (t == NULL)
1381 goto fail;
1382 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1383 if (v == NULL) {
1384 Py_DECREF(t);
1385 goto fail;
1386 }
1387 PyTuple_SET_ITEM(t, 0, v);
1388 v = PyUnicode_FromStringAndSize((vptr + 1),
1389 (len - (vptr - buf + 1)));
1390 if (v == NULL) {
1391 Py_DECREF(t);
1392 goto fail;
1393 }
1394 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001395 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001397
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 if (PyList_Append(peer_alt_names, t) < 0) {
1401 Py_DECREF(t);
1402 goto fail;
1403 }
1404 Py_DECREF(t);
1405 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001406 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 }
1408 BIO_free(biobuf);
1409 if (peer_alt_names != Py_None) {
1410 v = PyList_AsTuple(peer_alt_names);
1411 Py_DECREF(peer_alt_names);
1412 return v;
1413 } else {
1414 return peer_alt_names;
1415 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001416
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001417
1418 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 if (biobuf != NULL)
1420 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001421
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001422 if (peer_alt_names != Py_None) {
1423 Py_XDECREF(peer_alt_names);
1424 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001426 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427}
1428
1429static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001430_get_aia_uri(X509 *certificate, int nid) {
1431 PyObject *lst = NULL, *ostr = NULL;
1432 int i, result;
1433 AUTHORITY_INFO_ACCESS *info;
1434
1435 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001436 if (info == NULL)
1437 return Py_None;
1438 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1439 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001440 return Py_None;
1441 }
1442
1443 if ((lst = PyList_New(0)) == NULL) {
1444 goto fail;
1445 }
1446
1447 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1448 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1449 ASN1_IA5STRING *uri;
1450
1451 if ((OBJ_obj2nid(ad->method) != nid) ||
1452 (ad->location->type != GEN_URI)) {
1453 continue;
1454 }
1455 uri = ad->location->d.uniformResourceIdentifier;
1456 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1457 uri->length);
1458 if (ostr == NULL) {
1459 goto fail;
1460 }
1461 result = PyList_Append(lst, ostr);
1462 Py_DECREF(ostr);
1463 if (result < 0) {
1464 goto fail;
1465 }
1466 }
1467 AUTHORITY_INFO_ACCESS_free(info);
1468
1469 /* convert to tuple or None */
1470 if (PyList_Size(lst) == 0) {
1471 Py_DECREF(lst);
1472 return Py_None;
1473 } else {
1474 PyObject *tup;
1475 tup = PyList_AsTuple(lst);
1476 Py_DECREF(lst);
1477 return tup;
1478 }
1479
1480 fail:
1481 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001482 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001483 return NULL;
1484}
1485
1486static PyObject *
1487_get_crl_dp(X509 *certificate) {
1488 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001489 int i, j;
1490 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001491
Christian Heimes598894f2016-09-05 23:19:05 +02001492 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001493
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001494 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001495 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001496
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001497 lst = PyList_New(0);
1498 if (lst == NULL)
1499 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001500
1501 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1502 DIST_POINT *dp;
1503 STACK_OF(GENERAL_NAME) *gns;
1504
1505 dp = sk_DIST_POINT_value(dps, i);
1506 gns = dp->distpoint->name.fullname;
1507
1508 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1509 GENERAL_NAME *gn;
1510 ASN1_IA5STRING *uri;
1511 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001512 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001513
1514 gn = sk_GENERAL_NAME_value(gns, j);
1515 if (gn->type != GEN_URI) {
1516 continue;
1517 }
1518 uri = gn->d.uniformResourceIdentifier;
1519 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1520 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001521 if (ouri == NULL)
1522 goto done;
1523
1524 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001525 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001526 if (err < 0)
1527 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001528 }
1529 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001530
1531 /* Convert to tuple. */
1532 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1533
1534 done:
1535 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001536 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001537 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001538}
1539
1540static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001541_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 PyObject *retval = NULL;
1544 BIO *biobuf = NULL;
1545 PyObject *peer;
1546 PyObject *peer_alt_names = NULL;
1547 PyObject *issuer;
1548 PyObject *version;
1549 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001550 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 ASN1_INTEGER *serialNumber;
1552 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001553 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 ASN1_TIME *notBefore, *notAfter;
1555 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 retval = PyDict_New();
1558 if (retval == NULL)
1559 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 peer = _create_tuple_for_X509_NAME(
1562 X509_get_subject_name(certificate));
1563 if (peer == NULL)
1564 goto fail0;
1565 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1566 Py_DECREF(peer);
1567 goto fail0;
1568 }
1569 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001570
Antoine Pitroufb046912010-11-09 20:21:19 +00001571 issuer = _create_tuple_for_X509_NAME(
1572 X509_get_issuer_name(certificate));
1573 if (issuer == NULL)
1574 goto fail0;
1575 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001577 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001579 Py_DECREF(issuer);
1580
1581 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001582 if (version == NULL)
1583 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001584 if (PyDict_SetItemString(retval, "version", version) < 0) {
1585 Py_DECREF(version);
1586 goto fail0;
1587 }
1588 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001589
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001590 /* get a memory buffer */
1591 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001592
Antoine Pitroufb046912010-11-09 20:21:19 +00001593 (void) BIO_reset(biobuf);
1594 serialNumber = X509_get_serialNumber(certificate);
1595 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1596 i2a_ASN1_INTEGER(biobuf, serialNumber);
1597 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1598 if (len < 0) {
1599 _setSSLError(NULL, 0, __FILE__, __LINE__);
1600 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001601 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001602 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1603 if (sn_obj == NULL)
1604 goto fail1;
1605 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1606 Py_DECREF(sn_obj);
1607 goto fail1;
1608 }
1609 Py_DECREF(sn_obj);
1610
1611 (void) BIO_reset(biobuf);
1612 notBefore = X509_get_notBefore(certificate);
1613 ASN1_TIME_print(biobuf, notBefore);
1614 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1615 if (len < 0) {
1616 _setSSLError(NULL, 0, __FILE__, __LINE__);
1617 goto fail1;
1618 }
1619 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1620 if (pnotBefore == NULL)
1621 goto fail1;
1622 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1623 Py_DECREF(pnotBefore);
1624 goto fail1;
1625 }
1626 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 (void) BIO_reset(biobuf);
1629 notAfter = X509_get_notAfter(certificate);
1630 ASN1_TIME_print(biobuf, notAfter);
1631 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1632 if (len < 0) {
1633 _setSSLError(NULL, 0, __FILE__, __LINE__);
1634 goto fail1;
1635 }
1636 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1637 if (pnotAfter == NULL)
1638 goto fail1;
1639 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1640 Py_DECREF(pnotAfter);
1641 goto fail1;
1642 }
1643 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 peer_alt_names = _get_peer_alt_names(certificate);
1648 if (peer_alt_names == NULL)
1649 goto fail1;
1650 else if (peer_alt_names != Py_None) {
1651 if (PyDict_SetItemString(retval, "subjectAltName",
1652 peer_alt_names) < 0) {
1653 Py_DECREF(peer_alt_names);
1654 goto fail1;
1655 }
1656 Py_DECREF(peer_alt_names);
1657 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001658
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001659 /* Authority Information Access: OCSP URIs */
1660 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1661 if (obj == NULL) {
1662 goto fail1;
1663 } else if (obj != Py_None) {
1664 result = PyDict_SetItemString(retval, "OCSP", obj);
1665 Py_DECREF(obj);
1666 if (result < 0) {
1667 goto fail1;
1668 }
1669 }
1670
1671 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1672 if (obj == NULL) {
1673 goto fail1;
1674 } else if (obj != Py_None) {
1675 result = PyDict_SetItemString(retval, "caIssuers", obj);
1676 Py_DECREF(obj);
1677 if (result < 0) {
1678 goto fail1;
1679 }
1680 }
1681
1682 /* CDP (CRL distribution points) */
1683 obj = _get_crl_dp(certificate);
1684 if (obj == NULL) {
1685 goto fail1;
1686 } else if (obj != Py_None) {
1687 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1688 Py_DECREF(obj);
1689 if (result < 0) {
1690 goto fail1;
1691 }
1692 }
1693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001694 BIO_free(biobuf);
1695 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001696
1697 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 if (biobuf != NULL)
1699 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001700 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001701 Py_XDECREF(retval);
1702 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001703}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001704
Christian Heimes9a5395a2013-06-17 15:44:12 +02001705static PyObject *
1706_certificate_to_der(X509 *certificate)
1707{
1708 unsigned char *bytes_buf = NULL;
1709 int len;
1710 PyObject *retval;
1711
1712 bytes_buf = NULL;
1713 len = i2d_X509(certificate, &bytes_buf);
1714 if (len < 0) {
1715 _setSSLError(NULL, 0, __FILE__, __LINE__);
1716 return NULL;
1717 }
1718 /* this is actually an immutable bytes sequence */
1719 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1720 OPENSSL_free(bytes_buf);
1721 return retval;
1722}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001724/*[clinic input]
1725_ssl._test_decode_cert
1726 path: object(converter="PyUnicode_FSConverter")
1727 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001728
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001729[clinic start generated code]*/
1730
1731static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001732_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1733/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 X509 *x=NULL;
1737 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001738
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001739 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1740 PyErr_SetString(PySSLErrorObject,
1741 "Can't malloc memory to read file");
1742 goto fail0;
1743 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001745 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001746 PyErr_SetString(PySSLErrorObject,
1747 "Can't open file");
1748 goto fail0;
1749 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001750
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001751 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1752 if (x == NULL) {
1753 PyErr_SetString(PySSLErrorObject,
1754 "Error decoding PEM-encoded file");
1755 goto fail0;
1756 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001757
Antoine Pitroufb046912010-11-09 20:21:19 +00001758 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001759 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001760
1761 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001762 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 if (cert != NULL) BIO_free(cert);
1764 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001765}
1766
1767
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001768/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001769_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001770 der as binary_mode: bool = False
1771 /
1772
1773Returns the certificate for the peer.
1774
1775If no certificate was provided, returns None. If a certificate was
1776provided, but not validated, returns an empty dictionary. Otherwise
1777returns a dict containing information about the peer certificate.
1778
1779If the optional argument is True, returns a DER-encoded copy of the
1780peer certificate, or None if no certificate was provided. This will
1781return the certificate even if it wasn't validated.
1782[clinic start generated code]*/
1783
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001784static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001785_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1786/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001787{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001788 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001789 X509 *peer_cert;
1790 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791
Christian Heimes66dc33b2017-05-23 16:02:02 -07001792 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001793 PyErr_SetString(PyExc_ValueError,
1794 "handshake not done yet");
1795 return NULL;
1796 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001797 peer_cert = SSL_get_peer_certificate(self->ssl);
1798 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001800
Antoine Pitrou721738f2012-08-15 23:20:39 +02001801 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001802 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001803 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001805 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001807 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001809 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001811 X509_free(peer_cert);
1812 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001813}
1814
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001815static PyObject *
1816cipher_to_tuple(const SSL_CIPHER *cipher)
1817{
1818 const char *cipher_name, *cipher_protocol;
1819 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001820 if (retval == NULL)
1821 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001822
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001823 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001825 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 PyTuple_SET_ITEM(retval, 0, Py_None);
1827 } else {
1828 v = PyUnicode_FromString(cipher_name);
1829 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001830 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001831 PyTuple_SET_ITEM(retval, 0, v);
1832 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001833
1834 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001836 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 PyTuple_SET_ITEM(retval, 1, Py_None);
1838 } else {
1839 v = PyUnicode_FromString(cipher_protocol);
1840 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001841 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001842 PyTuple_SET_ITEM(retval, 1, v);
1843 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001844
1845 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001846 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001847 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001851
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001852 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 Py_DECREF(retval);
1854 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001855}
1856
Christian Heimes25bfcd52016-09-06 00:04:45 +02001857#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1858static PyObject *
1859cipher_to_dict(const SSL_CIPHER *cipher)
1860{
1861 const char *cipher_name, *cipher_protocol;
1862
1863 unsigned long cipher_id;
1864 int alg_bits, strength_bits, len;
1865 char buf[512] = {0};
1866#if OPENSSL_VERSION_1_1
1867 int aead, nid;
1868 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1869#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001870
1871 /* can be NULL */
1872 cipher_name = SSL_CIPHER_get_name(cipher);
1873 cipher_protocol = SSL_CIPHER_get_version(cipher);
1874 cipher_id = SSL_CIPHER_get_id(cipher);
1875 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001876 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1877 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001878 if (len > 1 && buf[len-1] == '\n')
1879 buf[len-1] = '\0';
1880 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1881
1882#if OPENSSL_VERSION_1_1
1883 aead = SSL_CIPHER_is_aead(cipher);
1884 nid = SSL_CIPHER_get_cipher_nid(cipher);
1885 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1886 nid = SSL_CIPHER_get_digest_nid(cipher);
1887 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1888 nid = SSL_CIPHER_get_kx_nid(cipher);
1889 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1890 nid = SSL_CIPHER_get_auth_nid(cipher);
1891 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1892#endif
1893
Victor Stinner410b9882016-09-12 12:00:23 +02001894 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001895 "{sksssssssisi"
1896#if OPENSSL_VERSION_1_1
1897 "sOssssssss"
1898#endif
1899 "}",
1900 "id", cipher_id,
1901 "name", cipher_name,
1902 "protocol", cipher_protocol,
1903 "description", buf,
1904 "strength_bits", strength_bits,
1905 "alg_bits", alg_bits
1906#if OPENSSL_VERSION_1_1
1907 ,"aead", aead ? Py_True : Py_False,
1908 "symmetric", skcipher,
1909 "digest", digest,
1910 "kea", kx,
1911 "auth", auth
1912#endif
1913 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001914}
1915#endif
1916
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001917/*[clinic input]
1918_ssl._SSLSocket.shared_ciphers
1919[clinic start generated code]*/
1920
1921static PyObject *
1922_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1923/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001924{
1925 STACK_OF(SSL_CIPHER) *ciphers;
1926 int i;
1927 PyObject *res;
1928
Christian Heimes598894f2016-09-05 23:19:05 +02001929 ciphers = SSL_get_ciphers(self->ssl);
1930 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001931 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001932 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1933 if (!res)
1934 return NULL;
1935 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1936 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1937 if (!tup) {
1938 Py_DECREF(res);
1939 return NULL;
1940 }
1941 PyList_SET_ITEM(res, i, tup);
1942 }
1943 return res;
1944}
1945
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001946/*[clinic input]
1947_ssl._SSLSocket.cipher
1948[clinic start generated code]*/
1949
1950static PyObject *
1951_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1952/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001953{
1954 const SSL_CIPHER *current;
1955
1956 if (self->ssl == NULL)
1957 Py_RETURN_NONE;
1958 current = SSL_get_current_cipher(self->ssl);
1959 if (current == NULL)
1960 Py_RETURN_NONE;
1961 return cipher_to_tuple(current);
1962}
1963
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001964/*[clinic input]
1965_ssl._SSLSocket.version
1966[clinic start generated code]*/
1967
1968static PyObject *
1969_ssl__SSLSocket_version_impl(PySSLSocket *self)
1970/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001971{
1972 const char *version;
1973
1974 if (self->ssl == NULL)
1975 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001976 if (!SSL_is_init_finished(self->ssl)) {
1977 /* handshake not finished */
1978 Py_RETURN_NONE;
1979 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001980 version = SSL_get_version(self->ssl);
1981 if (!strcmp(version, "unknown"))
1982 Py_RETURN_NONE;
1983 return PyUnicode_FromString(version);
1984}
1985
Christian Heimes29eab552018-02-25 12:31:33 +01001986#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001987/*[clinic input]
1988_ssl._SSLSocket.selected_npn_protocol
1989[clinic start generated code]*/
1990
1991static PyObject *
1992_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1993/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1994{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001995 const unsigned char *out;
1996 unsigned int outlen;
1997
Victor Stinner4569cd52013-06-23 14:58:43 +02001998 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001999 &out, &outlen);
2000
2001 if (out == NULL)
2002 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002003 return PyUnicode_FromStringAndSize((char *)out, outlen);
2004}
2005#endif
2006
Christian Heimes29eab552018-02-25 12:31:33 +01002007#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002008/*[clinic input]
2009_ssl._SSLSocket.selected_alpn_protocol
2010[clinic start generated code]*/
2011
2012static PyObject *
2013_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2014/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2015{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002016 const unsigned char *out;
2017 unsigned int outlen;
2018
2019 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2020
2021 if (out == NULL)
2022 Py_RETURN_NONE;
2023 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002024}
2025#endif
2026
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002027/*[clinic input]
2028_ssl._SSLSocket.compression
2029[clinic start generated code]*/
2030
2031static PyObject *
2032_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2033/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2034{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002035#ifdef OPENSSL_NO_COMP
2036 Py_RETURN_NONE;
2037#else
2038 const COMP_METHOD *comp_method;
2039 const char *short_name;
2040
2041 if (self->ssl == NULL)
2042 Py_RETURN_NONE;
2043 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002044 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002045 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002046 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002047 if (short_name == NULL)
2048 Py_RETURN_NONE;
2049 return PyUnicode_DecodeFSDefault(short_name);
2050#endif
2051}
2052
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002053static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2054 Py_INCREF(self->ctx);
2055 return self->ctx;
2056}
2057
2058static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2059 void *closure) {
2060
2061 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002062#if !HAVE_SNI
2063 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2064 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002065 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002066#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002067 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002068 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002069 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002070#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002071 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002072 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002073 return -1;
2074 }
2075
2076 return 0;
2077}
2078
2079PyDoc_STRVAR(PySSL_set_context_doc,
2080"_setter_context(ctx)\n\
2081\
2082This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002083used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002084on the SSLContext to change the certificate information associated with the\n\
2085SSLSocket before the cryptographic exchange handshake messages\n");
2086
2087
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002088static PyObject *
2089PySSL_get_server_side(PySSLSocket *self, void *c)
2090{
2091 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2092}
2093
2094PyDoc_STRVAR(PySSL_get_server_side_doc,
2095"Whether this is a server-side socket.");
2096
2097static PyObject *
2098PySSL_get_server_hostname(PySSLSocket *self, void *c)
2099{
2100 if (self->server_hostname == NULL)
2101 Py_RETURN_NONE;
2102 Py_INCREF(self->server_hostname);
2103 return self->server_hostname;
2104}
2105
2106PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2107"The currently set server hostname (for SNI).");
2108
2109static PyObject *
2110PySSL_get_owner(PySSLSocket *self, void *c)
2111{
2112 PyObject *owner;
2113
2114 if (self->owner == NULL)
2115 Py_RETURN_NONE;
2116
2117 owner = PyWeakref_GetObject(self->owner);
2118 Py_INCREF(owner);
2119 return owner;
2120}
2121
2122static int
2123PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2124{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002125 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002126 if (self->owner == NULL)
2127 return -1;
2128 return 0;
2129}
2130
2131PyDoc_STRVAR(PySSL_get_owner_doc,
2132"The Python-level owner of this object.\
2133Passed as \"self\" in servername callback.");
2134
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002135
Antoine Pitrou152efa22010-05-16 18:19:27 +00002136static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002137{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 if (self->ssl)
2139 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002141 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002142 Py_XDECREF(self->server_hostname);
2143 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002145}
2146
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002147/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002148 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002149 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002150 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002151
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002152static int
Victor Stinner14690702015-04-06 22:46:13 +02002153PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002154{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002155 int rc;
2156#ifdef HAVE_POLL
2157 struct pollfd pollfd;
2158 _PyTime_t ms;
2159#else
2160 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002161 fd_set fds;
2162 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002163#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002166 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002168 else if (timeout < 0) {
2169 if (s->sock_timeout > 0)
2170 return SOCKET_HAS_TIMED_OUT;
2171 else
2172 return SOCKET_IS_BLOCKING;
2173 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002176 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 /* Prefer poll, if available, since you can poll() any fd
2180 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002181#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002182 pollfd.fd = s->sock_fd;
2183 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002184
Victor Stinner14690702015-04-06 22:46:13 +02002185 /* timeout is in seconds, poll() uses milliseconds */
2186 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002187 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002188
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002189 PySSL_BEGIN_ALLOW_THREADS
2190 rc = poll(&pollfd, 1, (int)ms);
2191 PySSL_END_ALLOW_THREADS
2192#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002194 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002196
Victor Stinner14690702015-04-06 22:46:13 +02002197 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002199 FD_ZERO(&fds);
2200 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002201
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002202 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002204 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002208 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002210#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002211
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002212 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2213 (when we are able to write or when there's something to read) */
2214 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002215}
2216
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002217/*[clinic input]
2218_ssl._SSLSocket.write
2219 b: Py_buffer
2220 /
2221
2222Writes the bytes-like object b into the SSL object.
2223
2224Returns the number of bytes written.
2225[clinic start generated code]*/
2226
2227static PyObject *
2228_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2229/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002230{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002231 int len;
2232 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002233 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002235 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002236 _PyTime_t timeout, deadline = 0;
2237 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002238
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002239 if (sock != NULL) {
2240 if (((PyObject*)sock) == Py_None) {
2241 _setSSLError("Underlying socket connection gone",
2242 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2243 return NULL;
2244 }
2245 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002246 }
2247
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002248 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002249 PyErr_Format(PyExc_OverflowError,
2250 "string longer than %d bytes", INT_MAX);
2251 goto error;
2252 }
2253
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002254 if (sock != NULL) {
2255 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002256 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002257 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2258 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2259 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260
Victor Stinner14690702015-04-06 22:46:13 +02002261 timeout = GET_SOCKET_TIMEOUT(sock);
2262 has_timeout = (timeout > 0);
2263 if (has_timeout)
2264 deadline = _PyTime_GetMonotonicClock() + timeout;
2265
2266 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002268 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 "The write operation timed out");
2270 goto error;
2271 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2272 PyErr_SetString(PySSLErrorObject,
2273 "Underlying socket has been closed.");
2274 goto error;
2275 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2276 PyErr_SetString(PySSLErrorObject,
2277 "Underlying socket too large for select().");
2278 goto error;
2279 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002280
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002283 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002284 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002286 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002287
2288 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002290
Victor Stinner14690702015-04-06 22:46:13 +02002291 if (has_timeout)
2292 timeout = deadline - _PyTime_GetMonotonicClock();
2293
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002294 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002295 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002296 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002297 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 } else {
2299 sockstate = SOCKET_OPERATION_OK;
2300 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002303 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 "The write operation timed out");
2305 goto error;
2306 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2307 PyErr_SetString(PySSLErrorObject,
2308 "Underlying socket has been closed.");
2309 goto error;
2310 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2311 break;
2312 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002313 } while (err.ssl == SSL_ERROR_WANT_READ ||
2314 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002315
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002316 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002317 if (len > 0)
2318 return PyLong_FromLong(len);
2319 else
2320 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002321
2322error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002323 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002325}
2326
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002327/*[clinic input]
2328_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002329
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002330Returns the number of already decrypted bytes available for read, pending on the connection.
2331[clinic start generated code]*/
2332
2333static PyObject *
2334_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2335/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002336{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 int count = 0;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002338 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 PySSL_BEGIN_ALLOW_THREADS
2341 count = SSL_pending(self->ssl);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002342 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002344 self->err = err;
2345
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346 if (count < 0)
2347 return PySSL_SetError(self, count, __FILE__, __LINE__);
2348 else
2349 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002350}
2351
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002352/*[clinic input]
2353_ssl._SSLSocket.read
2354 size as len: int
2355 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002356 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002357 ]
2358 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002360Read up to size bytes from the SSL socket.
2361[clinic start generated code]*/
2362
2363static PyObject *
2364_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2365 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002366/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002367{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002368 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002369 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002370 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 int sockstate;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002372 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002374 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002375 _PyTime_t timeout, deadline = 0;
2376 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002377
Martin Panter5503d472016-03-27 05:35:19 +00002378 if (!group_right_1 && len < 0) {
2379 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2380 return NULL;
2381 }
2382
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002383 if (sock != NULL) {
2384 if (((PyObject*)sock) == Py_None) {
2385 _setSSLError("Underlying socket connection gone",
2386 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2387 return NULL;
2388 }
2389 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 }
2391
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002392 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002393 dest = PyBytes_FromStringAndSize(NULL, len);
2394 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002395 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002396 if (len == 0) {
2397 Py_XDECREF(sock);
2398 return dest;
2399 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002400 mem = PyBytes_AS_STRING(dest);
2401 }
2402 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002403 mem = buffer->buf;
2404 if (len <= 0 || len > buffer->len) {
2405 len = (int) buffer->len;
2406 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002407 PyErr_SetString(PyExc_OverflowError,
2408 "maximum length can't fit in a C 'int'");
2409 goto error;
2410 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002411 if (len == 0) {
2412 count = 0;
2413 goto done;
2414 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002415 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002416 }
2417
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002418 if (sock != NULL) {
2419 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002420 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002421 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2422 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2423 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424
Victor Stinner14690702015-04-06 22:46:13 +02002425 timeout = GET_SOCKET_TIMEOUT(sock);
2426 has_timeout = (timeout > 0);
2427 if (has_timeout)
2428 deadline = _PyTime_GetMonotonicClock() + timeout;
2429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002431 PySSL_BEGIN_ALLOW_THREADS
2432 count = SSL_read(self->ssl, mem, len);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002433 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002435 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002436
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 if (PyErr_CheckSignals())
2438 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002439
Victor Stinner14690702015-04-06 22:46:13 +02002440 if (has_timeout)
2441 timeout = deadline - _PyTime_GetMonotonicClock();
2442
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002443 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002444 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002445 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002446 sockstate = PySSL_select(sock, 1, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002447 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002448 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 {
2450 count = 0;
2451 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002453 else
2454 sockstate = SOCKET_OPERATION_OK;
2455
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002457 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002458 "The read operation timed out");
2459 goto error;
2460 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2461 break;
2462 }
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002463 } while (err.ssl == SSL_ERROR_WANT_READ ||
2464 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 if (count <= 0) {
2467 PySSL_SetError(self, count, __FILE__, __LINE__);
2468 goto error;
2469 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002470
2471done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002472 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002473 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002474 _PyBytes_Resize(&dest, count);
2475 return dest;
2476 }
2477 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002478 return PyLong_FromLong(count);
2479 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002480
2481error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002482 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002483 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002484 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002486}
2487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002488/*[clinic input]
2489_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002490
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002491Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492[clinic start generated code]*/
2493
2494static PyObject *
2495_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002496/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002497{
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002498 _PySSLError err;
2499 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002501 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002502 _PyTime_t timeout, deadline = 0;
2503 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002504
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002505 if (sock != NULL) {
2506 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002507 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002508 _setSSLError("Underlying socket connection gone",
2509 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2510 return NULL;
2511 }
2512 Py_INCREF(sock);
2513
2514 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002515 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002516 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2517 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519
Victor Stinner14690702015-04-06 22:46:13 +02002520 timeout = GET_SOCKET_TIMEOUT(sock);
2521 has_timeout = (timeout > 0);
2522 if (has_timeout)
2523 deadline = _PyTime_GetMonotonicClock() + timeout;
2524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 while (1) {
2526 PySSL_BEGIN_ALLOW_THREADS
2527 /* Disable read-ahead so that unwrap can work correctly.
2528 * Otherwise OpenSSL might read in too much data,
2529 * eating clear text data that happens to be
2530 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002531 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 * function is used and the shutdown_seen_zero != 0
2533 * condition is met.
2534 */
2535 if (self->shutdown_seen_zero)
2536 SSL_set_read_ahead(self->ssl, 0);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002537 ret = SSL_shutdown(self->ssl);
2538 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 PySSL_END_ALLOW_THREADS
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002540 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002542 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002543 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002544 break;
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002545 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002546 /* Don't loop endlessly; instead preserve legacy
2547 behaviour of trying SSL_shutdown() only twice.
2548 This looks necessary for OpenSSL < 0.9.8m */
2549 if (++zeros > 1)
2550 break;
2551 /* Shutdown was sent, now try receiving */
2552 self->shutdown_seen_zero = 1;
2553 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002554 }
2555
Victor Stinner14690702015-04-06 22:46:13 +02002556 if (has_timeout)
2557 timeout = deadline - _PyTime_GetMonotonicClock();
2558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 /* Possibly retry shutdown until timeout or failure */
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002560 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002561 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002562 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002563 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002564 else
2565 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002566
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002567 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowerc6fd1c12018-09-17 11:34:47 -07002568 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002569 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002570 "The read operation timed out");
2571 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002572 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002575 }
2576 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2577 PyErr_SetString(PySSLErrorObject,
2578 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002579 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 }
2581 else if (sockstate != SOCKET_OPERATION_OK)
2582 /* Retain the SSL error code */
2583 break;
2584 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002585
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002586 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002587 Py_XDECREF(sock);
Nathaniel J. Smithc0da5822018-09-21 21:44:12 -07002588 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002589 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002590 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002591 /* It's already INCREF'ed */
2592 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002593 else
2594 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002595
2596error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002597 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002598 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002599}
2600
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002601/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002602_ssl._SSLSocket.get_channel_binding
2603 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002604
Christian Heimes141c5e82018-02-24 21:10:57 +01002605Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002606
Christian Heimes141c5e82018-02-24 21:10:57 +01002607Raise ValueError if the requested `cb_type` is not supported. Return bytes
2608of the data or None if the data is not available (e.g. before the handshake).
2609Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002610[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002611
Antoine Pitroud6494802011-07-21 01:11:30 +02002612static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002613_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2614 const char *cb_type)
2615/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002616{
Antoine Pitroud6494802011-07-21 01:11:30 +02002617 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002618 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002619
Christian Heimes141c5e82018-02-24 21:10:57 +01002620 if (strcmp(cb_type, "tls-unique") == 0) {
2621 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2622 /* if session is resumed XOR we are the client */
2623 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2624 }
2625 else {
2626 /* if a new session XOR we are the server */
2627 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2628 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002629 }
2630 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002631 PyErr_Format(
2632 PyExc_ValueError,
2633 "'%s' channel binding type not implemented",
2634 cb_type
2635 );
2636 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002637 }
2638
2639 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002640 if (len == 0)
2641 Py_RETURN_NONE;
2642
Christian Heimes141c5e82018-02-24 21:10:57 +01002643 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002644}
2645
Christian Heimes99a65702016-09-10 23:44:53 +02002646#ifdef OPENSSL_VERSION_1_1
2647
2648static SSL_SESSION*
2649_ssl_session_dup(SSL_SESSION *session) {
2650 SSL_SESSION *newsession = NULL;
2651 int slen;
2652 unsigned char *senc = NULL, *p;
2653 const unsigned char *const_p;
2654
2655 if (session == NULL) {
2656 PyErr_SetString(PyExc_ValueError, "Invalid session");
2657 goto error;
2658 }
2659
2660 /* get length */
2661 slen = i2d_SSL_SESSION(session, NULL);
2662 if (slen == 0 || slen > 0xFF00) {
2663 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2664 goto error;
2665 }
2666 if ((senc = PyMem_Malloc(slen)) == NULL) {
2667 PyErr_NoMemory();
2668 goto error;
2669 }
2670 p = senc;
2671 if (!i2d_SSL_SESSION(session, &p)) {
2672 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2673 goto error;
2674 }
2675 const_p = senc;
2676 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2677 if (session == NULL) {
2678 goto error;
2679 }
2680 PyMem_Free(senc);
2681 return newsession;
2682 error:
2683 if (senc != NULL) {
2684 PyMem_Free(senc);
2685 }
2686 return NULL;
2687}
2688#endif
2689
2690static PyObject *
2691PySSL_get_session(PySSLSocket *self, void *closure) {
2692 /* get_session can return sessions from a server-side connection,
2693 * it does not check for handshake done or client socket. */
2694 PySSLSession *pysess;
2695 SSL_SESSION *session;
2696
2697#ifdef OPENSSL_VERSION_1_1
2698 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2699 * https://github.com/openssl/openssl/issues/1550 */
2700 session = SSL_get0_session(self->ssl); /* borrowed reference */
2701 if (session == NULL) {
2702 Py_RETURN_NONE;
2703 }
2704 if ((session = _ssl_session_dup(session)) == NULL) {
2705 return NULL;
2706 }
2707#else
2708 session = SSL_get1_session(self->ssl);
2709 if (session == NULL) {
2710 Py_RETURN_NONE;
2711 }
2712#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002713 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002714 if (pysess == NULL) {
2715 SSL_SESSION_free(session);
2716 return NULL;
2717 }
2718
2719 assert(self->ctx);
2720 pysess->ctx = self->ctx;
2721 Py_INCREF(pysess->ctx);
2722 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002723 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002724 return (PyObject *)pysess;
2725}
2726
2727static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2728 void *closure)
2729 {
2730 PySSLSession *pysess;
2731#ifdef OPENSSL_VERSION_1_1
2732 SSL_SESSION *session;
2733#endif
2734 int result;
2735
2736 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002737 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002738 return -1;
2739 }
2740 pysess = (PySSLSession *)value;
2741
2742 if (self->ctx->ctx != pysess->ctx->ctx) {
2743 PyErr_SetString(PyExc_ValueError,
2744 "Session refers to a different SSLContext.");
2745 return -1;
2746 }
2747 if (self->socket_type != PY_SSL_CLIENT) {
2748 PyErr_SetString(PyExc_ValueError,
2749 "Cannot set session for server-side SSLSocket.");
2750 return -1;
2751 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002752 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002753 PyErr_SetString(PyExc_ValueError,
2754 "Cannot set session after handshake.");
2755 return -1;
2756 }
2757#ifdef OPENSSL_VERSION_1_1
2758 /* duplicate session */
2759 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2760 return -1;
2761 }
2762 result = SSL_set_session(self->ssl, session);
2763 /* free duplicate, SSL_set_session() bumps ref count */
2764 SSL_SESSION_free(session);
2765#else
2766 result = SSL_set_session(self->ssl, pysess->session);
2767#endif
2768 if (result == 0) {
2769 _setSSLError(NULL, 0, __FILE__, __LINE__);
2770 return -1;
2771 }
2772 return 0;
2773}
2774
2775PyDoc_STRVAR(PySSL_set_session_doc,
2776"_setter_session(session)\n\
2777\
2778Get / set SSLSession.");
2779
2780static PyObject *
2781PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2782 if (SSL_session_reused(self->ssl)) {
2783 Py_RETURN_TRUE;
2784 } else {
2785 Py_RETURN_FALSE;
2786 }
2787}
2788
2789PyDoc_STRVAR(PySSL_get_session_reused_doc,
2790"Was the client session reused during handshake?");
2791
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002792static PyGetSetDef ssl_getsetlist[] = {
2793 {"context", (getter) PySSL_get_context,
2794 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002795 {"server_side", (getter) PySSL_get_server_side, NULL,
2796 PySSL_get_server_side_doc},
2797 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2798 PySSL_get_server_hostname_doc},
2799 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2800 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002801 {"session", (getter) PySSL_get_session,
2802 (setter) PySSL_set_session, PySSL_set_session_doc},
2803 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2804 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002805 {NULL}, /* sentinel */
2806};
2807
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002808static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002809 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2810 _SSL__SSLSOCKET_WRITE_METHODDEF
2811 _SSL__SSLSOCKET_READ_METHODDEF
2812 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002813 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2814 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002815 _SSL__SSLSOCKET_CIPHER_METHODDEF
2816 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2817 _SSL__SSLSOCKET_VERSION_METHODDEF
2818 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2819 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2820 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2821 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002822 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002823};
2824
Antoine Pitrou152efa22010-05-16 18:19:27 +00002825static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002826 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002827 "_ssl._SSLSocket", /*tp_name*/
2828 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002829 0, /*tp_itemsize*/
2830 /* methods */
2831 (destructor)PySSL_dealloc, /*tp_dealloc*/
2832 0, /*tp_print*/
2833 0, /*tp_getattr*/
2834 0, /*tp_setattr*/
2835 0, /*tp_reserved*/
2836 0, /*tp_repr*/
2837 0, /*tp_as_number*/
2838 0, /*tp_as_sequence*/
2839 0, /*tp_as_mapping*/
2840 0, /*tp_hash*/
2841 0, /*tp_call*/
2842 0, /*tp_str*/
2843 0, /*tp_getattro*/
2844 0, /*tp_setattro*/
2845 0, /*tp_as_buffer*/
2846 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2847 0, /*tp_doc*/
2848 0, /*tp_traverse*/
2849 0, /*tp_clear*/
2850 0, /*tp_richcompare*/
2851 0, /*tp_weaklistoffset*/
2852 0, /*tp_iter*/
2853 0, /*tp_iternext*/
2854 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002855 0, /*tp_members*/
2856 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002857};
2858
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859
2860/*
2861 * _SSLContext objects
2862 */
2863
Christian Heimes5fe668c2016-09-12 00:01:11 +02002864static int
2865_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2866{
2867 int mode;
2868 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2869
2870 switch(n) {
2871 case PY_SSL_CERT_NONE:
2872 mode = SSL_VERIFY_NONE;
2873 break;
2874 case PY_SSL_CERT_OPTIONAL:
2875 mode = SSL_VERIFY_PEER;
2876 break;
2877 case PY_SSL_CERT_REQUIRED:
2878 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2879 break;
2880 default:
2881 PyErr_SetString(PyExc_ValueError,
2882 "invalid value for verify_mode");
2883 return -1;
2884 }
2885 /* keep current verify cb */
2886 verify_cb = SSL_CTX_get_verify_callback(ctx);
2887 SSL_CTX_set_verify(ctx, mode, verify_cb);
2888 return 0;
2889}
2890
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002891/*[clinic input]
2892@classmethod
2893_ssl._SSLContext.__new__
2894 protocol as proto_version: int
2895 /
2896[clinic start generated code]*/
2897
Antoine Pitrou152efa22010-05-16 18:19:27 +00002898static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002899_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2900/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002901{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002902 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002903 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002904 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002905 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002906 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002907#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002908 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002909#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002910
Antoine Pitrou152efa22010-05-16 18:19:27 +00002911 PySSL_BEGIN_ALLOW_THREADS
2912 if (proto_version == PY_SSL_VERSION_TLS1)
2913 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002914#if HAVE_TLSv1_2
2915 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2916 ctx = SSL_CTX_new(TLSv1_1_method());
2917 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2918 ctx = SSL_CTX_new(TLSv1_2_method());
2919#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002920#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002921 else if (proto_version == PY_SSL_VERSION_SSL3)
2922 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002923#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002924#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002925 else if (proto_version == PY_SSL_VERSION_SSL2)
2926 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002927#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002928 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002929 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002930 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2931 ctx = SSL_CTX_new(TLS_client_method());
2932 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2933 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002934 else
2935 proto_version = -1;
2936 PySSL_END_ALLOW_THREADS
2937
2938 if (proto_version == -1) {
2939 PyErr_SetString(PyExc_ValueError,
2940 "invalid protocol version");
2941 return NULL;
2942 }
2943 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002944 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002945 return NULL;
2946 }
2947
2948 assert(type != NULL && type->tp_alloc != NULL);
2949 self = (PySSLContext *) type->tp_alloc(type, 0);
2950 if (self == NULL) {
2951 SSL_CTX_free(ctx);
2952 return NULL;
2953 }
2954 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002955 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002956 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002957#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002958 self->npn_protocols = NULL;
2959#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002960#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002961 self->alpn_protocols = NULL;
2962#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002963#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002964 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002965#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002966 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002967 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2968 self->check_hostname = 1;
2969 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2970 Py_DECREF(self);
2971 return NULL;
2972 }
2973 } else {
2974 self->check_hostname = 0;
2975 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2976 Py_DECREF(self);
2977 return NULL;
2978 }
2979 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002980 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002981 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2982 if (proto_version != PY_SSL_VERSION_SSL2)
2983 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002984 if (proto_version != PY_SSL_VERSION_SSL3)
2985 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002986 /* Minimal security flags for server and client side context.
2987 * Client sockets ignore server-side parameters. */
2988#ifdef SSL_OP_NO_COMPRESSION
2989 options |= SSL_OP_NO_COMPRESSION;
2990#endif
2991#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2992 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2993#endif
2994#ifdef SSL_OP_SINGLE_DH_USE
2995 options |= SSL_OP_SINGLE_DH_USE;
2996#endif
2997#ifdef SSL_OP_SINGLE_ECDH_USE
2998 options |= SSL_OP_SINGLE_ECDH_USE;
2999#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003000 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003001
Semen Zhydenko1295e112017-10-15 21:28:31 +02003002 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003003 * It's far from perfect but gives users a better head start. */
3004 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003005#if PY_SSL_DEFAULT_CIPHERS == 2
3006 /* stick to OpenSSL's default settings */
3007 result = 1;
3008#else
3009 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3010#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003011 } else {
3012 /* SSLv2 needs MD5 */
3013 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3014 }
3015 if (result == 0) {
3016 Py_DECREF(self);
3017 ERR_clear_error();
3018 PyErr_SetString(PySSLErrorObject,
3019 "No cipher can be selected.");
3020 return NULL;
3021 }
3022
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003023#if defined(SSL_MODE_RELEASE_BUFFERS)
3024 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3025 usage for no cost at all. However, don't do this for OpenSSL versions
3026 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3027 2014-0198. I can't find exactly which beta fixed this CVE, so be
3028 conservative and assume it wasn't fixed until release. We do this check
3029 at runtime to avoid problems from the dynamic linker.
3030 See #25672 for more on this. */
3031 libver = SSLeay();
3032 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3033 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3034 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3035 }
3036#endif
3037
3038
Donald Stufft8ae264c2017-03-02 11:45:29 -05003039#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003040 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3041 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003042 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3043 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003044#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003045 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3046#else
3047 {
3048 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3049 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3050 EC_KEY_free(key);
3051 }
3052#endif
3053#endif
3054
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003055#define SID_CTX "Python"
3056 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3057 sizeof(SID_CTX));
3058#undef SID_CTX
3059
Christian Heimes61d478c2018-01-27 15:51:38 +01003060 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003061#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003062 /* Improve trust chain building when cross-signed intermediate
3063 certificates are present. See https://bugs.python.org/issue23476. */
3064 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003065#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003066 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003067
Antoine Pitrou152efa22010-05-16 18:19:27 +00003068 return (PyObject *)self;
3069}
3070
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003071static int
3072context_traverse(PySSLContext *self, visitproc visit, void *arg)
3073{
3074#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003075 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003076#endif
3077 return 0;
3078}
3079
3080static int
3081context_clear(PySSLContext *self)
3082{
3083#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003084 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003085#endif
3086 return 0;
3087}
3088
Antoine Pitrou152efa22010-05-16 18:19:27 +00003089static void
3090context_dealloc(PySSLContext *self)
3091{
INADA Naokia6296d32017-08-24 14:55:17 +09003092 /* bpo-31095: UnTrack is needed before calling any callbacks */
3093 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003094 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003096#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003097 PyMem_FREE(self->npn_protocols);
3098#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003099#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003100 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003101#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003102 Py_TYPE(self)->tp_free(self);
3103}
3104
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003105/*[clinic input]
3106_ssl._SSLContext.set_ciphers
3107 cipherlist: str
3108 /
3109[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003110
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003111static PyObject *
3112_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3113/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3114{
3115 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003116 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003117 /* Clearing the error queue is necessary on some OpenSSL versions,
3118 otherwise the error will be reported again when another SSL call
3119 is done. */
3120 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003121 PyErr_SetString(PySSLErrorObject,
3122 "No cipher can be selected.");
3123 return NULL;
3124 }
3125 Py_RETURN_NONE;
3126}
3127
Christian Heimes25bfcd52016-09-06 00:04:45 +02003128#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3129/*[clinic input]
3130_ssl._SSLContext.get_ciphers
3131[clinic start generated code]*/
3132
3133static PyObject *
3134_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3135/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3136{
3137 SSL *ssl = NULL;
3138 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003139 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003140 int i=0;
3141 PyObject *result = NULL, *dct;
3142
3143 ssl = SSL_new(self->ctx);
3144 if (ssl == NULL) {
3145 _setSSLError(NULL, 0, __FILE__, __LINE__);
3146 goto exit;
3147 }
3148 sk = SSL_get_ciphers(ssl);
3149
3150 result = PyList_New(sk_SSL_CIPHER_num(sk));
3151 if (result == NULL) {
3152 goto exit;
3153 }
3154
3155 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3156 cipher = sk_SSL_CIPHER_value(sk, i);
3157 dct = cipher_to_dict(cipher);
3158 if (dct == NULL) {
3159 Py_CLEAR(result);
3160 goto exit;
3161 }
3162 PyList_SET_ITEM(result, i, dct);
3163 }
3164
3165 exit:
3166 if (ssl != NULL)
3167 SSL_free(ssl);
3168 return result;
3169
3170}
3171#endif
3172
3173
Christian Heimes29eab552018-02-25 12:31:33 +01003174#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003175static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003176do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3177 const unsigned char *server_protocols, unsigned int server_protocols_len,
3178 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003179{
Benjamin Peterson88615022015-01-23 17:30:26 -05003180 int ret;
3181 if (client_protocols == NULL) {
3182 client_protocols = (unsigned char *)"";
3183 client_protocols_len = 0;
3184 }
3185 if (server_protocols == NULL) {
3186 server_protocols = (unsigned char *)"";
3187 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003188 }
3189
Benjamin Peterson88615022015-01-23 17:30:26 -05003190 ret = SSL_select_next_proto(out, outlen,
3191 server_protocols, server_protocols_len,
3192 client_protocols, client_protocols_len);
3193 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3194 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003195
3196 return SSL_TLSEXT_ERR_OK;
3197}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003198#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003199
Christian Heimes29eab552018-02-25 12:31:33 +01003200#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003201/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3202static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003203_advertiseNPN_cb(SSL *s,
3204 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003205 void *args)
3206{
3207 PySSLContext *ssl_ctx = (PySSLContext *) args;
3208
3209 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003210 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003211 *len = 0;
3212 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003213 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003214 *len = ssl_ctx->npn_protocols_len;
3215 }
3216
3217 return SSL_TLSEXT_ERR_OK;
3218}
3219/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3220static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003221_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003222 unsigned char **out, unsigned char *outlen,
3223 const unsigned char *server, unsigned int server_len,
3224 void *args)
3225{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003227 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003228 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003229}
3230#endif
3231
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003232/*[clinic input]
3233_ssl._SSLContext._set_npn_protocols
3234 protos: Py_buffer
3235 /
3236[clinic start generated code]*/
3237
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003238static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003239_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3240 Py_buffer *protos)
3241/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003242{
Christian Heimes29eab552018-02-25 12:31:33 +01003243#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003244 PyMem_Free(self->npn_protocols);
3245 self->npn_protocols = PyMem_Malloc(protos->len);
3246 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003247 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003248 memcpy(self->npn_protocols, protos->buf, protos->len);
3249 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003250
3251 /* set both server and client callbacks, because the context can
3252 * be used to create both types of sockets */
3253 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3254 _advertiseNPN_cb,
3255 self);
3256 SSL_CTX_set_next_proto_select_cb(self->ctx,
3257 _selectNPN_cb,
3258 self);
3259
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003260 Py_RETURN_NONE;
3261#else
3262 PyErr_SetString(PyExc_NotImplementedError,
3263 "The NPN extension requires OpenSSL 1.0.1 or later.");
3264 return NULL;
3265#endif
3266}
3267
Christian Heimes29eab552018-02-25 12:31:33 +01003268#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003269static int
3270_selectALPN_cb(SSL *s,
3271 const unsigned char **out, unsigned char *outlen,
3272 const unsigned char *client_protocols, unsigned int client_protocols_len,
3273 void *args)
3274{
3275 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003276 return do_protocol_selection(1, (unsigned char **)out, outlen,
3277 ctx->alpn_protocols, ctx->alpn_protocols_len,
3278 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003279}
3280#endif
3281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003282/*[clinic input]
3283_ssl._SSLContext._set_alpn_protocols
3284 protos: Py_buffer
3285 /
3286[clinic start generated code]*/
3287
Benjamin Petersoncca27322015-01-23 16:35:37 -05003288static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003289_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3290 Py_buffer *protos)
3291/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003292{
Christian Heimes29eab552018-02-25 12:31:33 +01003293#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003294 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003295 PyErr_Format(PyExc_OverflowError,
3296 "protocols longer than %d bytes", UINT_MAX);
3297 return NULL;
3298 }
3299
Benjamin Petersoncca27322015-01-23 16:35:37 -05003300 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003301 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003302 if (!self->alpn_protocols)
3303 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003304 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003305 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003306
3307 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3308 return PyErr_NoMemory();
3309 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3310
Benjamin Petersoncca27322015-01-23 16:35:37 -05003311 Py_RETURN_NONE;
3312#else
3313 PyErr_SetString(PyExc_NotImplementedError,
3314 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3315 return NULL;
3316#endif
3317}
3318
Antoine Pitrou152efa22010-05-16 18:19:27 +00003319static PyObject *
3320get_verify_mode(PySSLContext *self, void *c)
3321{
3322 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3323 case SSL_VERIFY_NONE:
3324 return PyLong_FromLong(PY_SSL_CERT_NONE);
3325 case SSL_VERIFY_PEER:
3326 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3327 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3328 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3329 }
3330 PyErr_SetString(PySSLErrorObject,
3331 "invalid return value from SSL_CTX_get_verify_mode");
3332 return NULL;
3333}
3334
3335static int
3336set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3337{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003338 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003339 if (!PyArg_Parse(arg, "i", &n))
3340 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003341 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003342 PyErr_SetString(PyExc_ValueError,
3343 "Cannot set verify_mode to CERT_NONE when "
3344 "check_hostname is enabled.");
3345 return -1;
3346 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003347 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003348}
3349
3350static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003351get_verify_flags(PySSLContext *self, void *c)
3352{
Christian Heimes598894f2016-09-05 23:19:05 +02003353 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003354 unsigned long flags;
3355
Christian Heimes61d478c2018-01-27 15:51:38 +01003356 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003357 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003358 return PyLong_FromUnsignedLong(flags);
3359}
3360
3361static int
3362set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3363{
Christian Heimes598894f2016-09-05 23:19:05 +02003364 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003365 unsigned long new_flags, flags, set, clear;
3366
3367 if (!PyArg_Parse(arg, "k", &new_flags))
3368 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003369 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003370 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003371 clear = flags & ~new_flags;
3372 set = ~flags & new_flags;
3373 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003374 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003375 _setSSLError(NULL, 0, __FILE__, __LINE__);
3376 return -1;
3377 }
3378 }
3379 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003380 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003381 _setSSLError(NULL, 0, __FILE__, __LINE__);
3382 return -1;
3383 }
3384 }
3385 return 0;
3386}
3387
Christian Heimes698dde12018-02-27 11:54:43 +01003388/* Getter and setter for protocol version */
3389#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3390
3391
3392static int
3393set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3394{
3395 long v;
3396 int result;
3397
3398 if (!PyArg_Parse(arg, "l", &v))
3399 return -1;
3400 if (v > INT_MAX) {
3401 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3402 return -1;
3403 }
3404
3405 switch(self->protocol) {
3406 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3407 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3408 case PY_SSL_VERSION_TLS:
3409 break;
3410 default:
3411 PyErr_SetString(
3412 PyExc_ValueError,
3413 "The context's protocol doesn't support modification of "
3414 "highest and lowest version."
3415 );
3416 return -1;
3417 }
3418
3419 if (what == 0) {
3420 switch(v) {
3421 case PY_PROTO_MINIMUM_SUPPORTED:
3422 v = 0;
3423 break;
3424 case PY_PROTO_MAXIMUM_SUPPORTED:
3425 /* Emulate max for set_min_proto_version */
3426 v = PY_PROTO_MAXIMUM_AVAILABLE;
3427 break;
3428 default:
3429 break;
3430 }
3431 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3432 }
3433 else {
3434 switch(v) {
3435 case PY_PROTO_MAXIMUM_SUPPORTED:
3436 v = 0;
3437 break;
3438 case PY_PROTO_MINIMUM_SUPPORTED:
3439 /* Emulate max for set_min_proto_version */
3440 v = PY_PROTO_MINIMUM_AVAILABLE;
3441 break;
3442 default:
3443 break;
3444 }
3445 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3446 }
3447 if (result == 0) {
3448 PyErr_Format(PyExc_ValueError,
3449 "Unsupported protocol version 0x%x", v);
3450 return -1;
3451 }
3452 return 0;
3453}
3454
3455static PyObject *
3456get_minimum_version(PySSLContext *self, void *c)
3457{
3458 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3459 if (v == 0) {
3460 v = PY_PROTO_MINIMUM_SUPPORTED;
3461 }
3462 return PyLong_FromLong(v);
3463}
3464
3465static int
3466set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3467{
3468 return set_min_max_proto_version(self, arg, 0);
3469}
3470
3471static PyObject *
3472get_maximum_version(PySSLContext *self, void *c)
3473{
3474 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3475 if (v == 0) {
3476 v = PY_PROTO_MAXIMUM_SUPPORTED;
3477 }
3478 return PyLong_FromLong(v);
3479}
3480
3481static int
3482set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3483{
3484 return set_min_max_proto_version(self, arg, 1);
3485}
3486#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3487
Christian Heimes22587792013-11-21 23:56:13 +01003488static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003489get_options(PySSLContext *self, void *c)
3490{
3491 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3492}
3493
3494static int
3495set_options(PySSLContext *self, PyObject *arg, void *c)
3496{
3497 long new_opts, opts, set, clear;
3498 if (!PyArg_Parse(arg, "l", &new_opts))
3499 return -1;
3500 opts = SSL_CTX_get_options(self->ctx);
3501 clear = opts & ~new_opts;
3502 set = ~opts & new_opts;
3503 if (clear) {
3504#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3505 SSL_CTX_clear_options(self->ctx, clear);
3506#else
3507 PyErr_SetString(PyExc_ValueError,
3508 "can't clear options before OpenSSL 0.9.8m");
3509 return -1;
3510#endif
3511 }
3512 if (set)
3513 SSL_CTX_set_options(self->ctx, set);
3514 return 0;
3515}
3516
Christian Heimes1aa9a752013-12-02 02:41:19 +01003517static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003518get_host_flags(PySSLContext *self, void *c)
3519{
3520 return PyLong_FromUnsignedLong(self->hostflags);
3521}
3522
3523static int
3524set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3525{
3526 X509_VERIFY_PARAM *param;
3527 unsigned int new_flags = 0;
3528
3529 if (!PyArg_Parse(arg, "I", &new_flags))
3530 return -1;
3531
3532 param = SSL_CTX_get0_param(self->ctx);
3533 self->hostflags = new_flags;
3534 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3535 return 0;
3536}
3537
3538static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003539get_check_hostname(PySSLContext *self, void *c)
3540{
3541 return PyBool_FromLong(self->check_hostname);
3542}
3543
3544static int
3545set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3546{
3547 int check_hostname;
3548 if (!PyArg_Parse(arg, "p", &check_hostname))
3549 return -1;
3550 if (check_hostname &&
3551 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003552 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3553 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3554 return -1;
3555 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003556 }
3557 self->check_hostname = check_hostname;
3558 return 0;
3559}
3560
Christian Heimes11a14932018-02-24 02:35:08 +01003561static PyObject *
3562get_protocol(PySSLContext *self, void *c) {
3563 return PyLong_FromLong(self->protocol);
3564}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003565
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003566typedef struct {
3567 PyThreadState *thread_state;
3568 PyObject *callable;
3569 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003570 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003571 int error;
3572} _PySSLPasswordInfo;
3573
3574static int
3575_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3576 const char *bad_type_error)
3577{
3578 /* Set the password and size fields of a _PySSLPasswordInfo struct
3579 from a unicode, bytes, or byte array object.
3580 The password field will be dynamically allocated and must be freed
3581 by the caller */
3582 PyObject *password_bytes = NULL;
3583 const char *data = NULL;
3584 Py_ssize_t size;
3585
3586 if (PyUnicode_Check(password)) {
3587 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3588 if (!password_bytes) {
3589 goto error;
3590 }
3591 data = PyBytes_AS_STRING(password_bytes);
3592 size = PyBytes_GET_SIZE(password_bytes);
3593 } else if (PyBytes_Check(password)) {
3594 data = PyBytes_AS_STRING(password);
3595 size = PyBytes_GET_SIZE(password);
3596 } else if (PyByteArray_Check(password)) {
3597 data = PyByteArray_AS_STRING(password);
3598 size = PyByteArray_GET_SIZE(password);
3599 } else {
3600 PyErr_SetString(PyExc_TypeError, bad_type_error);
3601 goto error;
3602 }
3603
Victor Stinner9ee02032013-06-23 15:08:23 +02003604 if (size > (Py_ssize_t)INT_MAX) {
3605 PyErr_Format(PyExc_ValueError,
3606 "password cannot be longer than %d bytes", INT_MAX);
3607 goto error;
3608 }
3609
Victor Stinner11ebff22013-07-07 17:07:52 +02003610 PyMem_Free(pw_info->password);
3611 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003612 if (!pw_info->password) {
3613 PyErr_SetString(PyExc_MemoryError,
3614 "unable to allocate password buffer");
3615 goto error;
3616 }
3617 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003618 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003619
3620 Py_XDECREF(password_bytes);
3621 return 1;
3622
3623error:
3624 Py_XDECREF(password_bytes);
3625 return 0;
3626}
3627
3628static int
3629_password_callback(char *buf, int size, int rwflag, void *userdata)
3630{
3631 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3632 PyObject *fn_ret = NULL;
3633
3634 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3635
3636 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003637 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003638 if (!fn_ret) {
3639 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3640 core python API, so we could use it to add a frame here */
3641 goto error;
3642 }
3643
3644 if (!_pwinfo_set(pw_info, fn_ret,
3645 "password callback must return a string")) {
3646 goto error;
3647 }
3648 Py_CLEAR(fn_ret);
3649 }
3650
3651 if (pw_info->size > size) {
3652 PyErr_Format(PyExc_ValueError,
3653 "password cannot be longer than %d bytes", size);
3654 goto error;
3655 }
3656
3657 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3658 memcpy(buf, pw_info->password, pw_info->size);
3659 return pw_info->size;
3660
3661error:
3662 Py_XDECREF(fn_ret);
3663 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3664 pw_info->error = 1;
3665 return -1;
3666}
3667
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003668/*[clinic input]
3669_ssl._SSLContext.load_cert_chain
3670 certfile: object
3671 keyfile: object = NULL
3672 password: object = NULL
3673
3674[clinic start generated code]*/
3675
Antoine Pitroub5218772010-05-21 09:56:06 +00003676static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003677_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3678 PyObject *keyfile, PyObject *password)
3679/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003680{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003681 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003682 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3683 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003684 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003685 int r;
3686
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003687 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003688 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003689 if (keyfile == Py_None)
3690 keyfile = NULL;
3691 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3692 PyErr_SetString(PyExc_TypeError,
3693 "certfile should be a valid filesystem path");
3694 return NULL;
3695 }
3696 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3697 PyErr_SetString(PyExc_TypeError,
3698 "keyfile should be a valid filesystem path");
3699 goto error;
3700 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003701 if (password && password != Py_None) {
3702 if (PyCallable_Check(password)) {
3703 pw_info.callable = password;
3704 } else if (!_pwinfo_set(&pw_info, password,
3705 "password should be a string or callable")) {
3706 goto error;
3707 }
3708 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3709 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3710 }
3711 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003712 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3713 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003714 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003715 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003716 if (pw_info.error) {
3717 ERR_clear_error();
3718 /* the password callback has already set the error information */
3719 }
3720 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003721 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003722 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003723 }
3724 else {
3725 _setSSLError(NULL, 0, __FILE__, __LINE__);
3726 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003727 goto error;
3728 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003729 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003730 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003731 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3732 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003733 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3734 Py_CLEAR(keyfile_bytes);
3735 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003736 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003737 if (pw_info.error) {
3738 ERR_clear_error();
3739 /* the password callback has already set the error information */
3740 }
3741 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003742 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003743 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003744 }
3745 else {
3746 _setSSLError(NULL, 0, __FILE__, __LINE__);
3747 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003748 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003749 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003750 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003751 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003752 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003753 if (r != 1) {
3754 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003755 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003756 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003757 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3758 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003759 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003760 Py_RETURN_NONE;
3761
3762error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003763 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3764 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003765 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003766 Py_XDECREF(keyfile_bytes);
3767 Py_XDECREF(certfile_bytes);
3768 return NULL;
3769}
3770
Christian Heimesefff7062013-11-21 03:35:02 +01003771/* internal helper function, returns -1 on error
3772 */
3773static int
3774_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3775 int filetype)
3776{
3777 BIO *biobuf = NULL;
3778 X509_STORE *store;
3779 int retval = 0, err, loaded = 0;
3780
3781 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3782
3783 if (len <= 0) {
3784 PyErr_SetString(PyExc_ValueError,
3785 "Empty certificate data");
3786 return -1;
3787 } else if (len > INT_MAX) {
3788 PyErr_SetString(PyExc_OverflowError,
3789 "Certificate data is too long.");
3790 return -1;
3791 }
3792
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003793 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003794 if (biobuf == NULL) {
3795 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3796 return -1;
3797 }
3798
3799 store = SSL_CTX_get_cert_store(self->ctx);
3800 assert(store != NULL);
3801
3802 while (1) {
3803 X509 *cert = NULL;
3804 int r;
3805
3806 if (filetype == SSL_FILETYPE_ASN1) {
3807 cert = d2i_X509_bio(biobuf, NULL);
3808 } else {
3809 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003810 SSL_CTX_get_default_passwd_cb(self->ctx),
3811 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3812 );
Christian Heimesefff7062013-11-21 03:35:02 +01003813 }
3814 if (cert == NULL) {
3815 break;
3816 }
3817 r = X509_STORE_add_cert(store, cert);
3818 X509_free(cert);
3819 if (!r) {
3820 err = ERR_peek_last_error();
3821 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3822 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3823 /* cert already in hash table, not an error */
3824 ERR_clear_error();
3825 } else {
3826 break;
3827 }
3828 }
3829 loaded++;
3830 }
3831
3832 err = ERR_peek_last_error();
3833 if ((filetype == SSL_FILETYPE_ASN1) &&
3834 (loaded > 0) &&
3835 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3836 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3837 /* EOF ASN1 file, not an error */
3838 ERR_clear_error();
3839 retval = 0;
3840 } else if ((filetype == SSL_FILETYPE_PEM) &&
3841 (loaded > 0) &&
3842 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3843 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3844 /* EOF PEM file, not an error */
3845 ERR_clear_error();
3846 retval = 0;
3847 } else {
3848 _setSSLError(NULL, 0, __FILE__, __LINE__);
3849 retval = -1;
3850 }
3851
3852 BIO_free(biobuf);
3853 return retval;
3854}
3855
3856
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003857/*[clinic input]
3858_ssl._SSLContext.load_verify_locations
3859 cafile: object = NULL
3860 capath: object = NULL
3861 cadata: object = NULL
3862
3863[clinic start generated code]*/
3864
Antoine Pitrou152efa22010-05-16 18:19:27 +00003865static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003866_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3867 PyObject *cafile,
3868 PyObject *capath,
3869 PyObject *cadata)
3870/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003871{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003872 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3873 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003874 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003875
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003876 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003877 if (cafile == Py_None)
3878 cafile = NULL;
3879 if (capath == Py_None)
3880 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003881 if (cadata == Py_None)
3882 cadata = NULL;
3883
3884 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003885 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003886 "cafile, capath and cadata cannot be all omitted");
3887 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003888 }
3889 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3890 PyErr_SetString(PyExc_TypeError,
3891 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003892 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003893 }
3894 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003895 PyErr_SetString(PyExc_TypeError,
3896 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003897 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003898 }
Christian Heimesefff7062013-11-21 03:35:02 +01003899
3900 /* validata cadata type and load cadata */
3901 if (cadata) {
3902 Py_buffer buf;
3903 PyObject *cadata_ascii = NULL;
3904
3905 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3906 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3907 PyBuffer_Release(&buf);
3908 PyErr_SetString(PyExc_TypeError,
3909 "cadata should be a contiguous buffer with "
3910 "a single dimension");
3911 goto error;
3912 }
3913 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3914 PyBuffer_Release(&buf);
3915 if (r == -1) {
3916 goto error;
3917 }
3918 } else {
3919 PyErr_Clear();
3920 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3921 if (cadata_ascii == NULL) {
3922 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003923 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003924 "bytes-like object");
3925 goto error;
3926 }
3927 r = _add_ca_certs(self,
3928 PyBytes_AS_STRING(cadata_ascii),
3929 PyBytes_GET_SIZE(cadata_ascii),
3930 SSL_FILETYPE_PEM);
3931 Py_DECREF(cadata_ascii);
3932 if (r == -1) {
3933 goto error;
3934 }
3935 }
3936 }
3937
3938 /* load cafile or capath */
3939 if (cafile || capath) {
3940 if (cafile)
3941 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3942 if (capath)
3943 capath_buf = PyBytes_AS_STRING(capath_bytes);
3944 PySSL_BEGIN_ALLOW_THREADS
3945 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3946 PySSL_END_ALLOW_THREADS
3947 if (r != 1) {
3948 ok = 0;
3949 if (errno != 0) {
3950 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003951 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003952 }
3953 else {
3954 _setSSLError(NULL, 0, __FILE__, __LINE__);
3955 }
3956 goto error;
3957 }
3958 }
3959 goto end;
3960
3961 error:
3962 ok = 0;
3963 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003964 Py_XDECREF(cafile_bytes);
3965 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003966 if (ok) {
3967 Py_RETURN_NONE;
3968 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003969 return NULL;
3970 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003971}
3972
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003973/*[clinic input]
3974_ssl._SSLContext.load_dh_params
3975 path as filepath: object
3976 /
3977
3978[clinic start generated code]*/
3979
Antoine Pitrou152efa22010-05-16 18:19:27 +00003980static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003981_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3982/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003983{
3984 FILE *f;
3985 DH *dh;
3986
Victor Stinnerdaf45552013-08-28 00:53:59 +02003987 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003988 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003989 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003990
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003991 errno = 0;
3992 PySSL_BEGIN_ALLOW_THREADS
3993 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003994 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003995 PySSL_END_ALLOW_THREADS
3996 if (dh == NULL) {
3997 if (errno != 0) {
3998 ERR_clear_error();
3999 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4000 }
4001 else {
4002 _setSSLError(NULL, 0, __FILE__, __LINE__);
4003 }
4004 return NULL;
4005 }
4006 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4007 _setSSLError(NULL, 0, __FILE__, __LINE__);
4008 DH_free(dh);
4009 Py_RETURN_NONE;
4010}
4011
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004012/*[clinic input]
4013_ssl._SSLContext._wrap_socket
4014 sock: object(subclass_of="PySocketModule.Sock_Type")
4015 server_side: int
4016 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004017 *
4018 owner: object = None
4019 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004020
4021[clinic start generated code]*/
4022
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004023static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004024_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004025 int server_side, PyObject *hostname_obj,
4026 PyObject *owner, PyObject *session)
4027/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004028{
Antoine Pitroud5323212010-10-22 18:19:07 +00004029 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004030 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031
Antoine Pitroud5323212010-10-22 18:19:07 +00004032 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004033 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004034 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004035 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004036 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004037 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004038
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004039 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4040 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004041 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004042 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004043 if (hostname != NULL)
4044 PyMem_Free(hostname);
4045 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004046}
4047
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004048/*[clinic input]
4049_ssl._SSLContext._wrap_bio
4050 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4051 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4052 server_side: int
4053 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004054 *
4055 owner: object = None
4056 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004057
4058[clinic start generated code]*/
4059
Antoine Pitroub0182c82010-10-12 20:09:02 +00004060static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004061_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4062 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004063 PyObject *hostname_obj, PyObject *owner,
4064 PyObject *session)
4065/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004066{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004068 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004069
4070 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004071 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004072 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004073 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004074 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004075 }
4076
4077 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004078 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004079 incoming, outgoing);
4080
4081 PyMem_Free(hostname);
4082 return res;
4083}
4084
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085/*[clinic input]
4086_ssl._SSLContext.session_stats
4087[clinic start generated code]*/
4088
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004089static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004090_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4091/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004092{
4093 int r;
4094 PyObject *value, *stats = PyDict_New();
4095 if (!stats)
4096 return NULL;
4097
4098#define ADD_STATS(SSL_NAME, KEY_NAME) \
4099 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4100 if (value == NULL) \
4101 goto error; \
4102 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4103 Py_DECREF(value); \
4104 if (r < 0) \
4105 goto error;
4106
4107 ADD_STATS(number, "number");
4108 ADD_STATS(connect, "connect");
4109 ADD_STATS(connect_good, "connect_good");
4110 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4111 ADD_STATS(accept, "accept");
4112 ADD_STATS(accept_good, "accept_good");
4113 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4114 ADD_STATS(accept, "accept");
4115 ADD_STATS(hits, "hits");
4116 ADD_STATS(misses, "misses");
4117 ADD_STATS(timeouts, "timeouts");
4118 ADD_STATS(cache_full, "cache_full");
4119
4120#undef ADD_STATS
4121
4122 return stats;
4123
4124error:
4125 Py_DECREF(stats);
4126 return NULL;
4127}
4128
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129/*[clinic input]
4130_ssl._SSLContext.set_default_verify_paths
4131[clinic start generated code]*/
4132
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004133static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004134_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4135/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004136{
4137 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4138 _setSSLError(NULL, 0, __FILE__, __LINE__);
4139 return NULL;
4140 }
4141 Py_RETURN_NONE;
4142}
4143
Antoine Pitrou501da612011-12-21 09:27:41 +01004144#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004145/*[clinic input]
4146_ssl._SSLContext.set_ecdh_curve
4147 name: object
4148 /
4149
4150[clinic start generated code]*/
4151
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004152static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004153_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4154/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004155{
4156 PyObject *name_bytes;
4157 int nid;
4158 EC_KEY *key;
4159
4160 if (!PyUnicode_FSConverter(name, &name_bytes))
4161 return NULL;
4162 assert(PyBytes_Check(name_bytes));
4163 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4164 Py_DECREF(name_bytes);
4165 if (nid == 0) {
4166 PyErr_Format(PyExc_ValueError,
4167 "unknown elliptic curve name %R", name);
4168 return NULL;
4169 }
4170 key = EC_KEY_new_by_curve_name(nid);
4171 if (key == NULL) {
4172 _setSSLError(NULL, 0, __FILE__, __LINE__);
4173 return NULL;
4174 }
4175 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4176 EC_KEY_free(key);
4177 Py_RETURN_NONE;
4178}
Antoine Pitrou501da612011-12-21 09:27:41 +01004179#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004180
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004181#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004182static int
4183_servername_callback(SSL *s, int *al, void *args)
4184{
4185 int ret;
4186 PySSLContext *ssl_ctx = (PySSLContext *) args;
4187 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004188 PyObject *result;
4189 /* The high-level ssl.SSLSocket object */
4190 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004191 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004192 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004193
Christian Heimes11a14932018-02-24 02:35:08 +01004194 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004195 /* remove race condition in this the call back while if removing the
4196 * callback is in progress */
4197 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004198 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004199 }
4200
4201 ssl = SSL_get_app_data(s);
4202 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004203
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004204 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205 * SSL connection and that has a .context attribute that can be changed to
4206 * identify the requested hostname. Since the official API is the Python
4207 * level API we want to pass the callback a Python level object rather than
4208 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4209 * SSLObject) that will be passed. Otherwise if there's a socket then that
4210 * will be passed. If both do not exist only then the C-level object is
4211 * passed. */
4212 if (ssl->owner)
4213 ssl_socket = PyWeakref_GetObject(ssl->owner);
4214 else if (ssl->Socket)
4215 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4216 else
4217 ssl_socket = (PyObject *) ssl;
4218
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004219 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004220 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004221 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004222
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004223 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004224 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004225 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004226 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004227 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004228 PyObject *servername_bytes;
4229 PyObject *servername_str;
4230
4231 servername_bytes = PyBytes_FromString(servername);
4232 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004233 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4234 goto error;
4235 }
Christian Heimes11a14932018-02-24 02:35:08 +01004236 /* server_hostname was encoded to an A-label by our caller; put it
4237 * back into a str object, but still as an A-label (bpo-28414)
4238 */
4239 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4240 Py_DECREF(servername_bytes);
4241 if (servername_str == NULL) {
4242 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004243 goto error;
4244 }
Christian Heimes11a14932018-02-24 02:35:08 +01004245 result = PyObject_CallFunctionObjArgs(
4246 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4247 ssl_ctx, NULL);
4248 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004249 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004250 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004251
4252 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004253 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004254 *al = SSL_AD_HANDSHAKE_FAILURE;
4255 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4256 }
4257 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004258 /* Result may be None, a SSLContext or an integer
4259 * None and SSLContext are OK, integer or other values are an error.
4260 */
4261 if (result == Py_None) {
4262 ret = SSL_TLSEXT_ERR_OK;
4263 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004264 *al = (int) PyLong_AsLong(result);
4265 if (PyErr_Occurred()) {
4266 PyErr_WriteUnraisable(result);
4267 *al = SSL_AD_INTERNAL_ERROR;
4268 }
4269 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4270 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004271 Py_DECREF(result);
4272 }
4273
4274 PyGILState_Release(gstate);
4275 return ret;
4276
4277error:
4278 Py_DECREF(ssl_socket);
4279 *al = SSL_AD_INTERNAL_ERROR;
4280 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4281 PyGILState_Release(gstate);
4282 return ret;
4283}
Antoine Pitroua5963382013-03-30 16:39:00 +01004284#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004285
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004286static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004287get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004288{
Christian Heimes11a14932018-02-24 02:35:08 +01004289 PyObject *cb = self->set_sni_cb;
4290 if (cb == NULL) {
4291 Py_RETURN_NONE;
4292 }
4293 Py_INCREF(cb);
4294 return cb;
4295}
4296
4297static int
4298set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4299{
4300 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4301 PyErr_SetString(PyExc_ValueError,
4302 "sni_callback cannot be set on TLS_CLIENT context");
4303 return -1;
4304 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004305#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004306 Py_CLEAR(self->set_sni_cb);
4307 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004308 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4309 }
4310 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004311 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004312 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4313 PyErr_SetString(PyExc_TypeError,
4314 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004315 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004316 }
Christian Heimes11a14932018-02-24 02:35:08 +01004317 Py_INCREF(arg);
4318 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004319 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4320 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4321 }
Christian Heimes11a14932018-02-24 02:35:08 +01004322 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004323#else
4324 PyErr_SetString(PyExc_NotImplementedError,
4325 "The TLS extension servername callback, "
4326 "SSL_CTX_set_tlsext_servername_callback, "
4327 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004328 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004329#endif
4330}
4331
Christian Heimes11a14932018-02-24 02:35:08 +01004332PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4333"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4334\n\
4335If the argument is None then the callback is disabled. The method is called\n\
4336with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4337See RFC 6066 for details of the SNI extension.");
4338
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004339/*[clinic input]
4340_ssl._SSLContext.cert_store_stats
4341
4342Returns quantities of loaded X.509 certificates.
4343
4344X.509 certificates with a CA extension and certificate revocation lists
4345inside the context's cert store.
4346
4347NOTE: Certificates in a capath directory aren't loaded unless they have
4348been used at least once.
4349[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004350
4351static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004352_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4353/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004354{
4355 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004356 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004357 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004358 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004359
4360 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004361 objs = X509_STORE_get0_objects(store);
4362 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4363 obj = sk_X509_OBJECT_value(objs, i);
4364 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004365 case X509_LU_X509:
4366 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004367 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004368 ca++;
4369 }
4370 break;
4371 case X509_LU_CRL:
4372 crl++;
4373 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004374 default:
4375 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4376 * As far as I can tell they are internal states and never
4377 * stored in a cert store */
4378 break;
4379 }
4380 }
4381 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4382 "x509_ca", ca);
4383}
4384
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004385/*[clinic input]
4386_ssl._SSLContext.get_ca_certs
4387 binary_form: bool = False
4388
4389Returns a list of dicts with information of loaded CA certs.
4390
4391If the optional argument is True, returns a DER-encoded copy of the CA
4392certificate.
4393
4394NOTE: Certificates in a capath directory aren't loaded unless they have
4395been used at least once.
4396[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004397
4398static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004399_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4400/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004401{
4402 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004403 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004404 PyObject *ci = NULL, *rlist = NULL;
4405 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004406
4407 if ((rlist = PyList_New(0)) == NULL) {
4408 return NULL;
4409 }
4410
4411 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004412 objs = X509_STORE_get0_objects(store);
4413 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004414 X509_OBJECT *obj;
4415 X509 *cert;
4416
Christian Heimes598894f2016-09-05 23:19:05 +02004417 obj = sk_X509_OBJECT_value(objs, i);
4418 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004419 /* not a x509 cert */
4420 continue;
4421 }
4422 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004423 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004424 if (!X509_check_ca(cert)) {
4425 continue;
4426 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004427 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004428 ci = _certificate_to_der(cert);
4429 } else {
4430 ci = _decode_certificate(cert);
4431 }
4432 if (ci == NULL) {
4433 goto error;
4434 }
4435 if (PyList_Append(rlist, ci) == -1) {
4436 goto error;
4437 }
4438 Py_CLEAR(ci);
4439 }
4440 return rlist;
4441
4442 error:
4443 Py_XDECREF(ci);
4444 Py_XDECREF(rlist);
4445 return NULL;
4446}
4447
4448
Antoine Pitrou152efa22010-05-16 18:19:27 +00004449static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004450 {"check_hostname", (getter) get_check_hostname,
4451 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004452 {"_host_flags", (getter) get_host_flags,
4453 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004454#if SSL_CTRL_GET_MAX_PROTO_VERSION
4455 {"minimum_version", (getter) get_minimum_version,
4456 (setter) set_minimum_version, NULL},
4457 {"maximum_version", (getter) get_maximum_version,
4458 (setter) set_maximum_version, NULL},
4459#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004460 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004461 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004462 {"options", (getter) get_options,
4463 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004464 {"protocol", (getter) get_protocol,
4465 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004466 {"verify_flags", (getter) get_verify_flags,
4467 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004468 {"verify_mode", (getter) get_verify_mode,
4469 (setter) set_verify_mode, NULL},
4470 {NULL}, /* sentinel */
4471};
4472
4473static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004474 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4475 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4476 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4477 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4478 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4479 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4480 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4481 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4482 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4483 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4484 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004485 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4486 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004487 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004488 {NULL, NULL} /* sentinel */
4489};
4490
4491static PyTypeObject PySSLContext_Type = {
4492 PyVarObject_HEAD_INIT(NULL, 0)
4493 "_ssl._SSLContext", /*tp_name*/
4494 sizeof(PySSLContext), /*tp_basicsize*/
4495 0, /*tp_itemsize*/
4496 (destructor)context_dealloc, /*tp_dealloc*/
4497 0, /*tp_print*/
4498 0, /*tp_getattr*/
4499 0, /*tp_setattr*/
4500 0, /*tp_reserved*/
4501 0, /*tp_repr*/
4502 0, /*tp_as_number*/
4503 0, /*tp_as_sequence*/
4504 0, /*tp_as_mapping*/
4505 0, /*tp_hash*/
4506 0, /*tp_call*/
4507 0, /*tp_str*/
4508 0, /*tp_getattro*/
4509 0, /*tp_setattro*/
4510 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004511 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004512 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004513 (traverseproc) context_traverse, /*tp_traverse*/
4514 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004515 0, /*tp_richcompare*/
4516 0, /*tp_weaklistoffset*/
4517 0, /*tp_iter*/
4518 0, /*tp_iternext*/
4519 context_methods, /*tp_methods*/
4520 0, /*tp_members*/
4521 context_getsetlist, /*tp_getset*/
4522 0, /*tp_base*/
4523 0, /*tp_dict*/
4524 0, /*tp_descr_get*/
4525 0, /*tp_descr_set*/
4526 0, /*tp_dictoffset*/
4527 0, /*tp_init*/
4528 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004529 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004530};
4531
4532
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004533/*
4534 * MemoryBIO objects
4535 */
4536
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004537/*[clinic input]
4538@classmethod
4539_ssl.MemoryBIO.__new__
4540
4541[clinic start generated code]*/
4542
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004543static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004544_ssl_MemoryBIO_impl(PyTypeObject *type)
4545/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004546{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004547 BIO *bio;
4548 PySSLMemoryBIO *self;
4549
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004550 bio = BIO_new(BIO_s_mem());
4551 if (bio == NULL) {
4552 PyErr_SetString(PySSLErrorObject,
4553 "failed to allocate BIO");
4554 return NULL;
4555 }
4556 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4557 * just that no data is currently available. The SSL routines should retry
4558 * the read, which we can achieve by calling BIO_set_retry_read(). */
4559 BIO_set_retry_read(bio);
4560 BIO_set_mem_eof_return(bio, -1);
4561
4562 assert(type != NULL && type->tp_alloc != NULL);
4563 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4564 if (self == NULL) {
4565 BIO_free(bio);
4566 return NULL;
4567 }
4568 self->bio = bio;
4569 self->eof_written = 0;
4570
4571 return (PyObject *) self;
4572}
4573
4574static void
4575memory_bio_dealloc(PySSLMemoryBIO *self)
4576{
4577 BIO_free(self->bio);
4578 Py_TYPE(self)->tp_free(self);
4579}
4580
4581static PyObject *
4582memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4583{
Segev Finer5cff6372017-07-27 01:19:17 +03004584 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004585}
4586
4587PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4588"The number of bytes pending in the memory BIO.");
4589
4590static PyObject *
4591memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4592{
4593 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4594 && self->eof_written);
4595}
4596
4597PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4598"Whether the memory BIO is at EOF.");
4599
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004600/*[clinic input]
4601_ssl.MemoryBIO.read
4602 size as len: int = -1
4603 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004604
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004605Read up to size bytes from the memory BIO.
4606
4607If size is not specified, read the entire buffer.
4608If the return value is an empty bytes instance, this means either
4609EOF or that no data is available. Use the "eof" property to
4610distinguish between the two.
4611[clinic start generated code]*/
4612
4613static PyObject *
4614_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4615/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4616{
4617 int avail, nbytes;
4618 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004619
Segev Finer5cff6372017-07-27 01:19:17 +03004620 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004621 if ((len < 0) || (len > avail))
4622 len = avail;
4623
4624 result = PyBytes_FromStringAndSize(NULL, len);
4625 if ((result == NULL) || (len == 0))
4626 return result;
4627
4628 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4629 /* There should never be any short reads but check anyway. */
4630 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4631 Py_DECREF(result);
4632 return NULL;
4633 }
4634
4635 return result;
4636}
4637
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004638/*[clinic input]
4639_ssl.MemoryBIO.write
4640 b: Py_buffer
4641 /
4642
4643Writes the bytes b into the memory BIO.
4644
4645Returns the number of bytes written.
4646[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647
4648static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4650/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004651{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004652 int nbytes;
4653
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004654 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004655 PyErr_Format(PyExc_OverflowError,
4656 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004657 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004658 }
4659
4660 if (self->eof_written) {
4661 PyErr_SetString(PySSLErrorObject,
4662 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004663 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004664 }
4665
Segev Finer5cff6372017-07-27 01:19:17 +03004666 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004667 if (nbytes < 0) {
4668 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004669 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004670 }
4671
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004672 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004673}
4674
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004675/*[clinic input]
4676_ssl.MemoryBIO.write_eof
4677
4678Write an EOF marker to the memory BIO.
4679
4680When all data has been read, the "eof" property will be True.
4681[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682
4683static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004684_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4685/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004686{
4687 self->eof_written = 1;
4688 /* After an EOF is written, a zero return from read() should be a real EOF
4689 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4690 BIO_clear_retry_flags(self->bio);
4691 BIO_set_mem_eof_return(self->bio, 0);
4692
4693 Py_RETURN_NONE;
4694}
4695
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004696static PyGetSetDef memory_bio_getsetlist[] = {
4697 {"pending", (getter) memory_bio_get_pending, NULL,
4698 PySSL_memory_bio_pending_doc},
4699 {"eof", (getter) memory_bio_get_eof, NULL,
4700 PySSL_memory_bio_eof_doc},
4701 {NULL}, /* sentinel */
4702};
4703
4704static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004705 _SSL_MEMORYBIO_READ_METHODDEF
4706 _SSL_MEMORYBIO_WRITE_METHODDEF
4707 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004708 {NULL, NULL} /* sentinel */
4709};
4710
4711static PyTypeObject PySSLMemoryBIO_Type = {
4712 PyVarObject_HEAD_INIT(NULL, 0)
4713 "_ssl.MemoryBIO", /*tp_name*/
4714 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4715 0, /*tp_itemsize*/
4716 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4717 0, /*tp_print*/
4718 0, /*tp_getattr*/
4719 0, /*tp_setattr*/
4720 0, /*tp_reserved*/
4721 0, /*tp_repr*/
4722 0, /*tp_as_number*/
4723 0, /*tp_as_sequence*/
4724 0, /*tp_as_mapping*/
4725 0, /*tp_hash*/
4726 0, /*tp_call*/
4727 0, /*tp_str*/
4728 0, /*tp_getattro*/
4729 0, /*tp_setattro*/
4730 0, /*tp_as_buffer*/
4731 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4732 0, /*tp_doc*/
4733 0, /*tp_traverse*/
4734 0, /*tp_clear*/
4735 0, /*tp_richcompare*/
4736 0, /*tp_weaklistoffset*/
4737 0, /*tp_iter*/
4738 0, /*tp_iternext*/
4739 memory_bio_methods, /*tp_methods*/
4740 0, /*tp_members*/
4741 memory_bio_getsetlist, /*tp_getset*/
4742 0, /*tp_base*/
4743 0, /*tp_dict*/
4744 0, /*tp_descr_get*/
4745 0, /*tp_descr_set*/
4746 0, /*tp_dictoffset*/
4747 0, /*tp_init*/
4748 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004749 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004750};
4751
Antoine Pitrou152efa22010-05-16 18:19:27 +00004752
Christian Heimes99a65702016-09-10 23:44:53 +02004753/*
4754 * SSL Session object
4755 */
4756
4757static void
4758PySSLSession_dealloc(PySSLSession *self)
4759{
INADA Naokia6296d32017-08-24 14:55:17 +09004760 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004761 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004762 Py_XDECREF(self->ctx);
4763 if (self->session != NULL) {
4764 SSL_SESSION_free(self->session);
4765 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004766 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004767}
4768
4769static PyObject *
4770PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4771{
4772 int result;
4773
4774 if (left == NULL || right == NULL) {
4775 PyErr_BadInternalCall();
4776 return NULL;
4777 }
4778
4779 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4780 Py_RETURN_NOTIMPLEMENTED;
4781 }
4782
4783 if (left == right) {
4784 result = 0;
4785 } else {
4786 const unsigned char *left_id, *right_id;
4787 unsigned int left_len, right_len;
4788 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4789 &left_len);
4790 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4791 &right_len);
4792 if (left_len == right_len) {
4793 result = memcmp(left_id, right_id, left_len);
4794 } else {
4795 result = 1;
4796 }
4797 }
4798
4799 switch (op) {
4800 case Py_EQ:
4801 if (result == 0) {
4802 Py_RETURN_TRUE;
4803 } else {
4804 Py_RETURN_FALSE;
4805 }
4806 break;
4807 case Py_NE:
4808 if (result != 0) {
4809 Py_RETURN_TRUE;
4810 } else {
4811 Py_RETURN_FALSE;
4812 }
4813 break;
4814 case Py_LT:
4815 case Py_LE:
4816 case Py_GT:
4817 case Py_GE:
4818 Py_RETURN_NOTIMPLEMENTED;
4819 break;
4820 default:
4821 PyErr_BadArgument();
4822 return NULL;
4823 }
4824}
4825
4826static int
4827PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4828{
4829 Py_VISIT(self->ctx);
4830 return 0;
4831}
4832
4833static int
4834PySSLSession_clear(PySSLSession *self)
4835{
4836 Py_CLEAR(self->ctx);
4837 return 0;
4838}
4839
4840
4841static PyObject *
4842PySSLSession_get_time(PySSLSession *self, void *closure) {
4843 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4844}
4845
4846PyDoc_STRVAR(PySSLSession_get_time_doc,
4847"Session creation time (seconds since epoch).");
4848
4849
4850static PyObject *
4851PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4852 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4853}
4854
4855PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4856"Session timeout (delta in seconds).");
4857
4858
4859static PyObject *
4860PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4861 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4862 return PyLong_FromUnsignedLong(hint);
4863}
4864
4865PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4866"Ticket life time hint.");
4867
4868
4869static PyObject *
4870PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4871 const unsigned char *id;
4872 unsigned int len;
4873 id = SSL_SESSION_get_id(self->session, &len);
4874 return PyBytes_FromStringAndSize((const char *)id, len);
4875}
4876
4877PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4878"Session id");
4879
4880
4881static PyObject *
4882PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4883 if (SSL_SESSION_has_ticket(self->session)) {
4884 Py_RETURN_TRUE;
4885 } else {
4886 Py_RETURN_FALSE;
4887 }
4888}
4889
4890PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4891"Does the session contain a ticket?");
4892
4893
4894static PyGetSetDef PySSLSession_getsetlist[] = {
4895 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4896 PySSLSession_get_has_ticket_doc},
4897 {"id", (getter) PySSLSession_get_session_id, NULL,
4898 PySSLSession_get_session_id_doc},
4899 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4900 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4901 {"time", (getter) PySSLSession_get_time, NULL,
4902 PySSLSession_get_time_doc},
4903 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4904 PySSLSession_get_timeout_doc},
4905 {NULL}, /* sentinel */
4906};
4907
4908static PyTypeObject PySSLSession_Type = {
4909 PyVarObject_HEAD_INIT(NULL, 0)
4910 "_ssl.Session", /*tp_name*/
4911 sizeof(PySSLSession), /*tp_basicsize*/
4912 0, /*tp_itemsize*/
4913 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4914 0, /*tp_print*/
4915 0, /*tp_getattr*/
4916 0, /*tp_setattr*/
4917 0, /*tp_reserved*/
4918 0, /*tp_repr*/
4919 0, /*tp_as_number*/
4920 0, /*tp_as_sequence*/
4921 0, /*tp_as_mapping*/
4922 0, /*tp_hash*/
4923 0, /*tp_call*/
4924 0, /*tp_str*/
4925 0, /*tp_getattro*/
4926 0, /*tp_setattro*/
4927 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004928 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004929 0, /*tp_doc*/
4930 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4931 (inquiry)PySSLSession_clear, /*tp_clear*/
4932 PySSLSession_richcompare, /*tp_richcompare*/
4933 0, /*tp_weaklistoffset*/
4934 0, /*tp_iter*/
4935 0, /*tp_iternext*/
4936 0, /*tp_methods*/
4937 0, /*tp_members*/
4938 PySSLSession_getsetlist, /*tp_getset*/
4939};
4940
4941
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004942/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004943/*[clinic input]
4944_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004945 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004946 entropy: double
4947 /
4948
4949Mix string into the OpenSSL PRNG state.
4950
4951entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304952string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004953[clinic start generated code]*/
4954
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004955static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004956_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004957/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004958{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004959 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004960 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004961
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004962 buf = (const char *)view->buf;
4963 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004964 do {
4965 written = Py_MIN(len, INT_MAX);
4966 RAND_add(buf, (int)written, entropy);
4967 buf += written;
4968 len -= written;
4969 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004970 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004971}
4972
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004973static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004974PySSL_RAND(int len, int pseudo)
4975{
4976 int ok;
4977 PyObject *bytes;
4978 unsigned long err;
4979 const char *errstr;
4980 PyObject *v;
4981
Victor Stinner1e81a392013-12-19 16:47:04 +01004982 if (len < 0) {
4983 PyErr_SetString(PyExc_ValueError, "num must be positive");
4984 return NULL;
4985 }
4986
Victor Stinner99c8b162011-05-24 12:05:19 +02004987 bytes = PyBytes_FromStringAndSize(NULL, len);
4988 if (bytes == NULL)
4989 return NULL;
4990 if (pseudo) {
4991 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4992 if (ok == 0 || ok == 1)
4993 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4994 }
4995 else {
4996 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4997 if (ok == 1)
4998 return bytes;
4999 }
5000 Py_DECREF(bytes);
5001
5002 err = ERR_get_error();
5003 errstr = ERR_reason_error_string(err);
5004 v = Py_BuildValue("(ks)", err, errstr);
5005 if (v != NULL) {
5006 PyErr_SetObject(PySSLErrorObject, v);
5007 Py_DECREF(v);
5008 }
5009 return NULL;
5010}
5011
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005012/*[clinic input]
5013_ssl.RAND_bytes
5014 n: int
5015 /
5016
5017Generate n cryptographically strong pseudo-random bytes.
5018[clinic start generated code]*/
5019
Victor Stinner99c8b162011-05-24 12:05:19 +02005020static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005021_ssl_RAND_bytes_impl(PyObject *module, int n)
5022/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005023{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005024 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005025}
5026
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005027/*[clinic input]
5028_ssl.RAND_pseudo_bytes
5029 n: int
5030 /
5031
5032Generate n pseudo-random bytes.
5033
5034Return a pair (bytes, is_cryptographic). is_cryptographic is True
5035if the bytes generated are cryptographically strong.
5036[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005037
5038static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005039_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5040/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005041{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005042 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005043}
5044
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005045/*[clinic input]
5046_ssl.RAND_status
5047
5048Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5049
5050It is necessary to seed the PRNG with RAND_add() on some platforms before
5051using the ssl() function.
5052[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005053
5054static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005055_ssl_RAND_status_impl(PyObject *module)
5056/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005057{
Christian Heimes217cfd12007-12-02 14:31:20 +00005058 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005059}
5060
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005061#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005062/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005063/*[clinic input]
5064_ssl.RAND_egd
5065 path: object(converter="PyUnicode_FSConverter")
5066 /
5067
5068Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5069
5070Returns number of bytes read. Raises SSLError if connection to EGD
5071fails or if it does not provide enough data to seed PRNG.
5072[clinic start generated code]*/
5073
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005074static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005075_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5076/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005077{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005078 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005079 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005080 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005081 PyErr_SetString(PySSLErrorObject,
5082 "EGD connection failed or EGD did not return "
5083 "enough data to seed the PRNG");
5084 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005085 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005086 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005087}
Christian Heimesa5d07652016-09-24 10:48:05 +02005088/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005089#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005090
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005091
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005092
5093/*[clinic input]
5094_ssl.get_default_verify_paths
5095
5096Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5097
5098The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5099[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005100
5101static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005102_ssl_get_default_verify_paths_impl(PyObject *module)
5103/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005104{
5105 PyObject *ofile_env = NULL;
5106 PyObject *ofile = NULL;
5107 PyObject *odir_env = NULL;
5108 PyObject *odir = NULL;
5109
Benjamin Petersond113c962015-07-18 10:59:13 -07005110#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005111 const char *tmp = (info); \
5112 target = NULL; \
5113 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5114 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5115 target = PyBytes_FromString(tmp); } \
5116 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005117 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005118
Benjamin Petersond113c962015-07-18 10:59:13 -07005119 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5120 CONVERT(X509_get_default_cert_file(), ofile);
5121 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5122 CONVERT(X509_get_default_cert_dir(), odir);
5123#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005124
Christian Heimes200bb1b2013-06-14 15:14:29 +02005125 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005126
5127 error:
5128 Py_XDECREF(ofile_env);
5129 Py_XDECREF(ofile);
5130 Py_XDECREF(odir_env);
5131 Py_XDECREF(odir);
5132 return NULL;
5133}
5134
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005135static PyObject*
5136asn1obj2py(ASN1_OBJECT *obj)
5137{
5138 int nid;
5139 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005140
5141 nid = OBJ_obj2nid(obj);
5142 if (nid == NID_undef) {
5143 PyErr_Format(PyExc_ValueError, "Unknown object");
5144 return NULL;
5145 }
5146 sn = OBJ_nid2sn(nid);
5147 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005148 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005149}
5150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005151/*[clinic input]
5152_ssl.txt2obj
5153 txt: str
5154 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005155
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005156Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5157
5158By default objects are looked up by OID. With name=True short and
5159long name are also matched.
5160[clinic start generated code]*/
5161
5162static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005163_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5164/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005165{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005166 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005167 ASN1_OBJECT *obj;
5168
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005169 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5170 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005171 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005172 return NULL;
5173 }
5174 result = asn1obj2py(obj);
5175 ASN1_OBJECT_free(obj);
5176 return result;
5177}
5178
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005179/*[clinic input]
5180_ssl.nid2obj
5181 nid: int
5182 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005183
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005184Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5185[clinic start generated code]*/
5186
5187static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005188_ssl_nid2obj_impl(PyObject *module, int nid)
5189/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005190{
5191 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005192 ASN1_OBJECT *obj;
5193
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005194 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005195 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005196 return NULL;
5197 }
5198 obj = OBJ_nid2obj(nid);
5199 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005200 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005201 return NULL;
5202 }
5203 result = asn1obj2py(obj);
5204 ASN1_OBJECT_free(obj);
5205 return result;
5206}
5207
Christian Heimes46bebee2013-06-09 19:03:31 +02005208#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005209
5210static PyObject*
5211certEncodingType(DWORD encodingType)
5212{
5213 static PyObject *x509_asn = NULL;
5214 static PyObject *pkcs_7_asn = NULL;
5215
5216 if (x509_asn == NULL) {
5217 x509_asn = PyUnicode_InternFromString("x509_asn");
5218 if (x509_asn == NULL)
5219 return NULL;
5220 }
5221 if (pkcs_7_asn == NULL) {
5222 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5223 if (pkcs_7_asn == NULL)
5224 return NULL;
5225 }
5226 switch(encodingType) {
5227 case X509_ASN_ENCODING:
5228 Py_INCREF(x509_asn);
5229 return x509_asn;
5230 case PKCS_7_ASN_ENCODING:
5231 Py_INCREF(pkcs_7_asn);
5232 return pkcs_7_asn;
5233 default:
5234 return PyLong_FromLong(encodingType);
5235 }
5236}
5237
5238static PyObject*
5239parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5240{
5241 CERT_ENHKEY_USAGE *usage;
5242 DWORD size, error, i;
5243 PyObject *retval;
5244
5245 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5246 error = GetLastError();
5247 if (error == CRYPT_E_NOT_FOUND) {
5248 Py_RETURN_TRUE;
5249 }
5250 return PyErr_SetFromWindowsErr(error);
5251 }
5252
5253 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5254 if (usage == NULL) {
5255 return PyErr_NoMemory();
5256 }
5257
5258 /* Now get the actual enhanced usage property */
5259 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5260 PyMem_Free(usage);
5261 error = GetLastError();
5262 if (error == CRYPT_E_NOT_FOUND) {
5263 Py_RETURN_TRUE;
5264 }
5265 return PyErr_SetFromWindowsErr(error);
5266 }
5267 retval = PySet_New(NULL);
5268 if (retval == NULL) {
5269 goto error;
5270 }
5271 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5272 if (usage->rgpszUsageIdentifier[i]) {
5273 PyObject *oid;
5274 int err;
5275 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5276 if (oid == NULL) {
5277 Py_CLEAR(retval);
5278 goto error;
5279 }
5280 err = PySet_Add(retval, oid);
5281 Py_DECREF(oid);
5282 if (err == -1) {
5283 Py_CLEAR(retval);
5284 goto error;
5285 }
5286 }
5287 }
5288 error:
5289 PyMem_Free(usage);
5290 return retval;
5291}
5292
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005293/*[clinic input]
5294_ssl.enum_certificates
5295 store_name: str
5296
5297Retrieve certificates from Windows' cert store.
5298
5299store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5300more cert storages, too. The function returns a list of (bytes,
5301encoding_type, trust) tuples. The encoding_type flag can be interpreted
5302with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5303a set of OIDs or the boolean True.
5304[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005305
Christian Heimes46bebee2013-06-09 19:03:31 +02005306static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005307_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5308/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005309{
Christian Heimes46bebee2013-06-09 19:03:31 +02005310 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005311 PCCERT_CONTEXT pCertCtx = NULL;
5312 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005313 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005314
Christian Heimes44109d72013-11-22 01:51:30 +01005315 result = PyList_New(0);
5316 if (result == NULL) {
5317 return NULL;
5318 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005319 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5320 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5321 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005322 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005323 Py_DECREF(result);
5324 return PyErr_SetFromWindowsErr(GetLastError());
5325 }
5326
Christian Heimes44109d72013-11-22 01:51:30 +01005327 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5328 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5329 pCertCtx->cbCertEncoded);
5330 if (!cert) {
5331 Py_CLEAR(result);
5332 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005333 }
Christian Heimes44109d72013-11-22 01:51:30 +01005334 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5335 Py_CLEAR(result);
5336 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005337 }
Christian Heimes44109d72013-11-22 01:51:30 +01005338 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5339 if (keyusage == Py_True) {
5340 Py_DECREF(keyusage);
5341 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005342 }
Christian Heimes44109d72013-11-22 01:51:30 +01005343 if (keyusage == NULL) {
5344 Py_CLEAR(result);
5345 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005346 }
Christian Heimes44109d72013-11-22 01:51:30 +01005347 if ((tup = PyTuple_New(3)) == NULL) {
5348 Py_CLEAR(result);
5349 break;
5350 }
5351 PyTuple_SET_ITEM(tup, 0, cert);
5352 cert = NULL;
5353 PyTuple_SET_ITEM(tup, 1, enc);
5354 enc = NULL;
5355 PyTuple_SET_ITEM(tup, 2, keyusage);
5356 keyusage = NULL;
5357 if (PyList_Append(result, tup) < 0) {
5358 Py_CLEAR(result);
5359 break;
5360 }
5361 Py_CLEAR(tup);
5362 }
5363 if (pCertCtx) {
5364 /* loop ended with an error, need to clean up context manually */
5365 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005366 }
5367
5368 /* In error cases cert, enc and tup may not be NULL */
5369 Py_XDECREF(cert);
5370 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005371 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005372 Py_XDECREF(tup);
5373
5374 if (!CertCloseStore(hStore, 0)) {
5375 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005376 Py_XDECREF(result);
5377 return PyErr_SetFromWindowsErr(GetLastError());
5378 }
5379 return result;
5380}
5381
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005382/*[clinic input]
5383_ssl.enum_crls
5384 store_name: str
5385
5386Retrieve CRLs from Windows' cert store.
5387
5388store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5389more cert storages, too. The function returns a list of (bytes,
5390encoding_type) tuples. The encoding_type flag can be interpreted with
5391X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5392[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005393
5394static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005395_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5396/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005397{
Christian Heimes44109d72013-11-22 01:51:30 +01005398 HCERTSTORE hStore = NULL;
5399 PCCRL_CONTEXT pCrlCtx = NULL;
5400 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5401 PyObject *result = NULL;
5402
Christian Heimes44109d72013-11-22 01:51:30 +01005403 result = PyList_New(0);
5404 if (result == NULL) {
5405 return NULL;
5406 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005407 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5408 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5409 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005410 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005411 Py_DECREF(result);
5412 return PyErr_SetFromWindowsErr(GetLastError());
5413 }
Christian Heimes44109d72013-11-22 01:51:30 +01005414
5415 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5416 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5417 pCrlCtx->cbCrlEncoded);
5418 if (!crl) {
5419 Py_CLEAR(result);
5420 break;
5421 }
5422 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5423 Py_CLEAR(result);
5424 break;
5425 }
5426 if ((tup = PyTuple_New(2)) == NULL) {
5427 Py_CLEAR(result);
5428 break;
5429 }
5430 PyTuple_SET_ITEM(tup, 0, crl);
5431 crl = NULL;
5432 PyTuple_SET_ITEM(tup, 1, enc);
5433 enc = NULL;
5434
5435 if (PyList_Append(result, tup) < 0) {
5436 Py_CLEAR(result);
5437 break;
5438 }
5439 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005440 }
Christian Heimes44109d72013-11-22 01:51:30 +01005441 if (pCrlCtx) {
5442 /* loop ended with an error, need to clean up context manually */
5443 CertFreeCRLContext(pCrlCtx);
5444 }
5445
5446 /* In error cases cert, enc and tup may not be NULL */
5447 Py_XDECREF(crl);
5448 Py_XDECREF(enc);
5449 Py_XDECREF(tup);
5450
5451 if (!CertCloseStore(hStore, 0)) {
5452 /* This error case might shadow another exception.*/
5453 Py_XDECREF(result);
5454 return PyErr_SetFromWindowsErr(GetLastError());
5455 }
5456 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005457}
Christian Heimes44109d72013-11-22 01:51:30 +01005458
5459#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005460
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005461/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005462static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005463 _SSL__TEST_DECODE_CERT_METHODDEF
5464 _SSL_RAND_ADD_METHODDEF
5465 _SSL_RAND_BYTES_METHODDEF
5466 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5467 _SSL_RAND_EGD_METHODDEF
5468 _SSL_RAND_STATUS_METHODDEF
5469 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5470 _SSL_ENUM_CERTIFICATES_METHODDEF
5471 _SSL_ENUM_CRLS_METHODDEF
5472 _SSL_TXT2OBJ_METHODDEF
5473 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005474 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005475};
5476
5477
Christian Heimes598894f2016-09-05 23:19:05 +02005478#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005479
5480/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005481 * of the Python C thread library
5482 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5483 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005484
5485static PyThread_type_lock *_ssl_locks = NULL;
5486
Christian Heimes4d98ca92013-08-19 17:36:29 +02005487#if OPENSSL_VERSION_NUMBER >= 0x10000000
5488/* use new CRYPTO_THREADID API. */
5489static void
5490_ssl_threadid_callback(CRYPTO_THREADID *id)
5491{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005492 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005493}
5494#else
5495/* deprecated CRYPTO_set_id_callback() API. */
5496static unsigned long
5497_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005498 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005499}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005500#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005501
Bill Janssen6e027db2007-11-15 22:23:56 +00005502static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005503 (int mode, int n, const char *file, int line) {
5504 /* this function is needed to perform locking on shared data
5505 structures. (Note that OpenSSL uses a number of global data
5506 structures that will be implicitly shared whenever multiple
5507 threads use OpenSSL.) Multi-threaded applications will
5508 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005510 locking_function() must be able to handle up to
5511 CRYPTO_num_locks() different mutex locks. It sets the n-th
5512 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005514 file and line are the file number of the function setting the
5515 lock. They can be useful for debugging.
5516 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005518 if ((_ssl_locks == NULL) ||
5519 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5520 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005522 if (mode & CRYPTO_LOCK) {
5523 PyThread_acquire_lock(_ssl_locks[n], 1);
5524 } else {
5525 PyThread_release_lock(_ssl_locks[n]);
5526 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005527}
5528
5529static int _setup_ssl_threads(void) {
5530
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005531 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005533 if (_ssl_locks == NULL) {
5534 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005535 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5536 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005537 if (_ssl_locks == NULL) {
5538 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005539 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005540 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005541 for (i = 0; i < _ssl_locks_count; i++) {
5542 _ssl_locks[i] = PyThread_allocate_lock();
5543 if (_ssl_locks[i] == NULL) {
5544 unsigned int j;
5545 for (j = 0; j < i; j++) {
5546 PyThread_free_lock(_ssl_locks[j]);
5547 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005548 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005549 return 0;
5550 }
5551 }
5552 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005553#if OPENSSL_VERSION_NUMBER >= 0x10000000
5554 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5555#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005556 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005557#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005558 }
5559 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005560}
5561
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005562#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005563
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005564PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005565"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005566for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005567
Martin v. Löwis1a214512008-06-11 05:26:20 +00005568
5569static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005570 PyModuleDef_HEAD_INIT,
5571 "_ssl",
5572 module_doc,
5573 -1,
5574 PySSL_methods,
5575 NULL,
5576 NULL,
5577 NULL,
5578 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005579};
5580
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005581
5582static void
5583parse_openssl_version(unsigned long libver,
5584 unsigned int *major, unsigned int *minor,
5585 unsigned int *fix, unsigned int *patch,
5586 unsigned int *status)
5587{
5588 *status = libver & 0xF;
5589 libver >>= 4;
5590 *patch = libver & 0xFF;
5591 libver >>= 8;
5592 *fix = libver & 0xFF;
5593 libver >>= 8;
5594 *minor = libver & 0xFF;
5595 libver >>= 8;
5596 *major = libver & 0xFF;
5597}
5598
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005599PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005600PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005601{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005602 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005603 unsigned long libver;
5604 unsigned int major, minor, fix, patch, status;
5605 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005606 struct py_ssl_error_code *errcode;
5607 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005608
Antoine Pitrou152efa22010-05-16 18:19:27 +00005609 if (PyType_Ready(&PySSLContext_Type) < 0)
5610 return NULL;
5611 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005612 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005613 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5614 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005615 if (PyType_Ready(&PySSLSession_Type) < 0)
5616 return NULL;
5617
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005619 m = PyModule_Create(&_sslmodule);
5620 if (m == NULL)
5621 return NULL;
5622 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005623
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005624 /* Load _socket module and its C API */
5625 socket_api = PySocketModule_ImportModuleAndAPI();
5626 if (!socket_api)
5627 return NULL;
5628 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005629
Christian Heimesc941e622017-09-05 15:47:11 +02005630#ifndef OPENSSL_VERSION_1_1
5631 /* Load all algorithms and initialize cpuid */
5632 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005633 /* Init OpenSSL */
5634 SSL_load_error_strings();
5635 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005636#endif
5637
Christian Heimes598894f2016-09-05 23:19:05 +02005638#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005639 /* note that this will start threading if not already started */
5640 if (!_setup_ssl_threads()) {
5641 return NULL;
5642 }
Christian Heimes598894f2016-09-05 23:19:05 +02005643#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5644 /* OpenSSL 1.1.0 builtin thread support is enabled */
5645 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005646#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005648 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005649 sslerror_type_slots[0].pfunc = PyExc_OSError;
5650 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005651 if (PySSLErrorObject == NULL)
5652 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005653
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005654 /* ssl.CertificateError used to be a subclass of ValueError */
5655 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5656 if (bases == NULL)
5657 return NULL;
5658 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5659 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5660 bases, NULL);
5661 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005662 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5663 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5664 PySSLErrorObject, NULL);
5665 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5666 "ssl.SSLWantReadError", SSLWantReadError_doc,
5667 PySSLErrorObject, NULL);
5668 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5669 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5670 PySSLErrorObject, NULL);
5671 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5672 "ssl.SSLSyscallError", SSLSyscallError_doc,
5673 PySSLErrorObject, NULL);
5674 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5675 "ssl.SSLEOFError", SSLEOFError_doc,
5676 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005677 if (PySSLCertVerificationErrorObject == NULL
5678 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005679 || PySSLWantReadErrorObject == NULL
5680 || PySSLWantWriteErrorObject == NULL
5681 || PySSLSyscallErrorObject == NULL
5682 || PySSLEOFErrorObject == NULL)
5683 return NULL;
5684 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005685 || PyDict_SetItemString(d, "SSLCertVerificationError",
5686 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005687 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5688 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5689 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5690 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5691 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005692 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005693 if (PyDict_SetItemString(d, "_SSLContext",
5694 (PyObject *)&PySSLContext_Type) != 0)
5695 return NULL;
5696 if (PyDict_SetItemString(d, "_SSLSocket",
5697 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005698 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005699 if (PyDict_SetItemString(d, "MemoryBIO",
5700 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5701 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005702 if (PyDict_SetItemString(d, "SSLSession",
5703 (PyObject *)&PySSLSession_Type) != 0)
5704 return NULL;
5705
Christian Heimes892d66e2018-01-29 14:10:18 +01005706 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5707 PY_SSL_DEFAULT_CIPHER_STRING);
5708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005709 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5710 PY_SSL_ERROR_ZERO_RETURN);
5711 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5712 PY_SSL_ERROR_WANT_READ);
5713 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5714 PY_SSL_ERROR_WANT_WRITE);
5715 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5716 PY_SSL_ERROR_WANT_X509_LOOKUP);
5717 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5718 PY_SSL_ERROR_SYSCALL);
5719 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5720 PY_SSL_ERROR_SSL);
5721 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5722 PY_SSL_ERROR_WANT_CONNECT);
5723 /* non ssl.h errorcodes */
5724 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5725 PY_SSL_ERROR_EOF);
5726 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5727 PY_SSL_ERROR_INVALID_ERROR_CODE);
5728 /* cert requirements */
5729 PyModule_AddIntConstant(m, "CERT_NONE",
5730 PY_SSL_CERT_NONE);
5731 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5732 PY_SSL_CERT_OPTIONAL);
5733 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5734 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005735 /* CRL verification for verification_flags */
5736 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5737 0);
5738 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5739 X509_V_FLAG_CRL_CHECK);
5740 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5741 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5742 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5743 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005744#ifdef X509_V_FLAG_TRUSTED_FIRST
5745 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5746 X509_V_FLAG_TRUSTED_FIRST);
5747#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005748
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005749 /* Alert Descriptions from ssl.h */
5750 /* note RESERVED constants no longer intended for use have been removed */
5751 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5752
5753#define ADD_AD_CONSTANT(s) \
5754 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5755 SSL_AD_##s)
5756
5757 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5758 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5759 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5760 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5761 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5762 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5763 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5764 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5765 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5766 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5767 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5768 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5769 ADD_AD_CONSTANT(UNKNOWN_CA);
5770 ADD_AD_CONSTANT(ACCESS_DENIED);
5771 ADD_AD_CONSTANT(DECODE_ERROR);
5772 ADD_AD_CONSTANT(DECRYPT_ERROR);
5773 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5774 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5775 ADD_AD_CONSTANT(INTERNAL_ERROR);
5776 ADD_AD_CONSTANT(USER_CANCELLED);
5777 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005778 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005779#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5780 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5781#endif
5782#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5783 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5784#endif
5785#ifdef SSL_AD_UNRECOGNIZED_NAME
5786 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5787#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005788#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5789 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5790#endif
5791#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5792 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5793#endif
5794#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5795 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5796#endif
5797
5798#undef ADD_AD_CONSTANT
5799
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005800 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005801#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005802 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5803 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005804#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005805#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005806 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5807 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005808#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005809 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005810 PY_SSL_VERSION_TLS);
5811 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5812 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005813 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5814 PY_SSL_VERSION_TLS_CLIENT);
5815 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5816 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005817 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5818 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005819#if HAVE_TLSv1_2
5820 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5821 PY_SSL_VERSION_TLS1_1);
5822 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5823 PY_SSL_VERSION_TLS1_2);
5824#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005825
Antoine Pitroub5218772010-05-21 09:56:06 +00005826 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005827 PyModule_AddIntConstant(m, "OP_ALL",
5828 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005829 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5830 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5831 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005832#if HAVE_TLSv1_2
5833 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5834 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5835#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005836#ifdef SSL_OP_NO_TLSv1_3
5837 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5838#else
5839 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5840#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005841 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5842 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005843 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005844 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005845#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005846 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005847#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005848#ifdef SSL_OP_NO_COMPRESSION
5849 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5850 SSL_OP_NO_COMPRESSION);
5851#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005852#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5853 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5854 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5855#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005856#ifdef SSL_OP_NO_RENEGOTIATION
5857 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5858 SSL_OP_NO_RENEGOTIATION);
5859#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005860
Christian Heimes61d478c2018-01-27 15:51:38 +01005861#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5862 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5863 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5864#endif
5865#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5866 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5867 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5868#endif
5869#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5870 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5871 X509_CHECK_FLAG_NO_WILDCARDS);
5872#endif
5873#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5874 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5875 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5876#endif
5877#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5878 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5879 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5880#endif
5881#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5882 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5883 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5884#endif
5885
Christian Heimes698dde12018-02-27 11:54:43 +01005886 /* protocol versions */
5887 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5888 PY_PROTO_MINIMUM_SUPPORTED);
5889 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5890 PY_PROTO_MAXIMUM_SUPPORTED);
5891 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5892 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5893 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5894 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5895 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005896
Christian Heimes698dde12018-02-27 11:54:43 +01005897#define addbool(m, v, b) \
5898 Py_INCREF((b) ? Py_True : Py_False); \
5899 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5900
5901#if HAVE_SNI
5902 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005903#else
Christian Heimes698dde12018-02-27 11:54:43 +01005904 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005905#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005906
5907 addbool(m, "HAS_TLS_UNIQUE", 1);
5908
5909#ifndef OPENSSL_NO_ECDH
5910 addbool(m, "HAS_ECDH", 1);
5911#else
5912 addbool(m, "HAS_ECDH", 0);
5913#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005914
Christian Heimes29eab552018-02-25 12:31:33 +01005915#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005916 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005917#else
Christian Heimes698dde12018-02-27 11:54:43 +01005918 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005919#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005920
Christian Heimes29eab552018-02-25 12:31:33 +01005921#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005922 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005923#else
Christian Heimes698dde12018-02-27 11:54:43 +01005924 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005925#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005926
5927#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5928 addbool(m, "HAS_SSLv2", 1);
5929#else
5930 addbool(m, "HAS_SSLv2", 0);
5931#endif
5932
5933#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5934 addbool(m, "HAS_SSLv3", 1);
5935#else
5936 addbool(m, "HAS_SSLv3", 0);
5937#endif
5938
5939#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5940 addbool(m, "HAS_TLSv1", 1);
5941#else
5942 addbool(m, "HAS_TLSv1", 0);
5943#endif
5944
5945#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5946 addbool(m, "HAS_TLSv1_1", 1);
5947#else
5948 addbool(m, "HAS_TLSv1_1", 0);
5949#endif
5950
5951#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5952 addbool(m, "HAS_TLSv1_2", 1);
5953#else
5954 addbool(m, "HAS_TLSv1_2", 0);
5955#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005956
Christian Heimescb5b68a2017-09-07 18:07:00 -07005957#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005958 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005959#else
Christian Heimes698dde12018-02-27 11:54:43 +01005960 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005961#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005962
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005963 /* Mappings for error codes */
5964 err_codes_to_names = PyDict_New();
5965 err_names_to_codes = PyDict_New();
5966 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5967 return NULL;
5968 errcode = error_codes;
5969 while (errcode->mnemonic != NULL) {
5970 PyObject *mnemo, *key;
5971 mnemo = PyUnicode_FromString(errcode->mnemonic);
5972 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5973 if (mnemo == NULL || key == NULL)
5974 return NULL;
5975 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5976 return NULL;
5977 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5978 return NULL;
5979 Py_DECREF(key);
5980 Py_DECREF(mnemo);
5981 errcode++;
5982 }
5983 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5984 return NULL;
5985 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5986 return NULL;
5987
5988 lib_codes_to_names = PyDict_New();
5989 if (lib_codes_to_names == NULL)
5990 return NULL;
5991 libcode = library_codes;
5992 while (libcode->library != NULL) {
5993 PyObject *mnemo, *key;
5994 key = PyLong_FromLong(libcode->code);
5995 mnemo = PyUnicode_FromString(libcode->library);
5996 if (key == NULL || mnemo == NULL)
5997 return NULL;
5998 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5999 return NULL;
6000 Py_DECREF(key);
6001 Py_DECREF(mnemo);
6002 libcode++;
6003 }
6004 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6005 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006007 /* OpenSSL version */
6008 /* SSLeay() gives us the version of the library linked against,
6009 which could be different from the headers version.
6010 */
6011 libver = SSLeay();
6012 r = PyLong_FromUnsignedLong(libver);
6013 if (r == NULL)
6014 return NULL;
6015 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6016 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006017 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006018 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6019 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6020 return NULL;
6021 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6022 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6023 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006024
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006025 libver = OPENSSL_VERSION_NUMBER;
6026 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6027 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6028 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6029 return NULL;
6030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006031 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006032}