blob: faca3a27c562d83a5e533d8bdf9488b12935cf1c [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"
Miss Islington (bot)e2c0aea2018-09-17 05:18:23 -070066#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
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700140# 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
Miss Islington (bot)96177412018-02-25 04:18:43 -0800167# define HAVE_ALPN 1
168#else
169# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500170#endif
171
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800172/* 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.
Miss Islington (bot)96177412018-02-25 04:18:43 -0800176 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800177 */
178#ifdef OPENSSL_NO_NEXTPROTONEG
Miss Islington (bot)96177412018-02-25 04:18:43 -0800179# define HAVE_NPN 0
180#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
181# define HAVE_NPN 0
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800182#elif defined(TLSEXT_TYPE_next_proto_neg)
Miss Islington (bot)96177412018-02-25 04:18:43 -0800183# define HAVE_NPN 1
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800184#else
Miss Islington (bot)96177412018-02-25 04:18:43 -0800185# define HAVE_NPN 0
186#endif
Miss Islington (bot)01d9c232018-02-24 14:04:27 -0800187
Victor Stinner524714e2016-07-22 17:43:59 +0200188#ifndef INVALID_SOCKET /* MS defines this */
189#define INVALID_SOCKET (-1)
190#endif
191
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700192/* 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
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700200
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
Miss Islington (bot)42bd62b2018-03-24 10:37:54 -0700264#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
Miss Islington (bot)4c842b02018-02-27 03:41:04 -0800334enum 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;
Miss Islington (bot)96177412018-02-25 04:18:43 -0800407#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
Miss Islington (bot)96177412018-02-25 04:18:43 -0800411#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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800416 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;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800423 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 {
Miss Islington (bot)12296642018-09-17 12:12:13 -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;
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)12296642018-09-17 12:12:13 -0700468 err.ws = WSAGetLastError();
469 _PySSL_FIX_ERRNO;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700470#endif
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800490static 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;
Miss Islington (bot)12296642018-09-17 12:12:13 -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) {
Miss Islington (bot)12296642018-09-17 12:12:13 -0700717 err = sslsock->err;
Thomas Woutersed03b412007-08-28 21:37:11 +0000718
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)12296642018-09-17 12:12:13 -0700755 if (err.ws) {
756 return PyErr_SetFromWindowsErr(err.ws);
757 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700758#endif
Miss Islington (bot)12296642018-09-17 12:12:13 -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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800845 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) {
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -0700860 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,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800885 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;
Miss Islington (bot)12296642018-09-17 12:12:13 -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;
Miss Islington (bot)12296642018-09-17 12:12:13 -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 */
906 (void) ERR_get_state();
907 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000908
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000910 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200912 SSL_set_app_data(self->ssl, self);
913 if (sock) {
914 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
915 } else {
916 /* BIOs are reference counted and SSL_set_bio borrows our reference.
917 * To prevent a double free in memory_bio_dealloc() we need to take an
918 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200919 BIO_up_ref(inbio->bio);
920 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200921 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
922 }
Miss Islington (bot)67d19682018-05-14 10:45:45 -0700923 SSL_set_mode(self->ssl,
924 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000925
Christian Heimes61d478c2018-01-27 15:51:38 +0100926 if (server_hostname != NULL) {
927 if (_ssl_configure_hostname(self, server_hostname) < 0) {
928 Py_DECREF(self);
929 return NULL;
930 }
931 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 /* If the socket is in non-blocking mode or timeout mode, set the BIO
933 * to non-blocking mode (blocking is the default)
934 */
Victor Stinnere2452312015-03-28 03:00:46 +0100935 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
937 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
938 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 PySSL_BEGIN_ALLOW_THREADS
941 if (socket_type == PY_SSL_CLIENT)
942 SSL_set_connect_state(self->ssl);
943 else
944 SSL_set_accept_state(self->ssl);
945 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000946
Antoine Pitroud6494802011-07-21 01:11:30 +0200947 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200948 if (sock != NULL) {
949 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
950 if (self->Socket == NULL) {
951 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200952 return NULL;
953 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100954 }
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800955 if (owner && owner != Py_None) {
956 if (PySSL_set_owner(self, owner, NULL) == -1) {
957 Py_DECREF(self);
958 return NULL;
959 }
960 }
961 if (session && session != Py_None) {
962 if (PySSL_set_session(self, session, NULL) == -1) {
963 Py_DECREF(self);
964 return NULL;
965 }
966 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000968}
969
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000970/* SSL object methods */
971
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300972/*[clinic input]
973_ssl._SSLSocket.do_handshake
974[clinic start generated code]*/
975
976static PyObject *
977_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
978/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000979{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 int ret;
Miss Islington (bot)12296642018-09-17 12:12:13 -0700981 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200983 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200984 _PyTime_t timeout, deadline = 0;
985 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000986
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200987 if (sock) {
988 if (((PyObject*)sock) == Py_None) {
989 _setSSLError("Underlying socket connection gone",
990 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
991 return NULL;
992 }
993 Py_INCREF(sock);
994
995 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100996 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200997 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
998 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001000
Victor Stinner14690702015-04-06 22:46:13 +02001001 timeout = GET_SOCKET_TIMEOUT(sock);
1002 has_timeout = (timeout > 0);
1003 if (has_timeout)
1004 deadline = _PyTime_GetMonotonicClock() + timeout;
1005
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 /* Actually negotiate SSL connection */
1007 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001009 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 ret = SSL_do_handshake(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001011 err = _PySSL_errno(ret < 1, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07001013 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001014
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001015 if (PyErr_CheckSignals())
1016 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001017
Victor Stinner14690702015-04-06 22:46:13 +02001018 if (has_timeout)
1019 timeout = deadline - _PyTime_GetMonotonicClock();
1020
Miss Islington (bot)12296642018-09-17 12:12:13 -07001021 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001022 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07001023 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001024 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 } else {
1026 sockstate = SOCKET_OPERATION_OK;
1027 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001030 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001031 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001032 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1034 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001035 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001036 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1038 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001039 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001040 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001041 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1042 break;
1043 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07001044 } while (err.ssl == SSL_ERROR_WANT_READ ||
1045 err.ssl == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001046 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 if (ret < 1)
1048 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001049
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001050 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001051
1052error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001053 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001054 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001055}
1056
Thomas Woutersed03b412007-08-28 21:37:11 +00001057static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001058_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1059{
1060 char buf[X509_NAME_MAXLEN];
1061 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001063 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001064
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001065 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 if (buflen < 0) {
1067 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001068 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001070 /* initial buffer is too small for oid + terminating null byte */
1071 if (buflen > X509_NAME_MAXLEN - 1) {
1072 /* make OBJ_obj2txt() calculate the required buflen */
1073 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1074 /* allocate len + 1 for terminating NULL byte */
1075 namebuf = PyMem_Malloc(buflen + 1);
1076 if (namebuf == NULL) {
1077 PyErr_NoMemory();
1078 return NULL;
1079 }
1080 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1081 if (buflen < 0) {
1082 _setSSLError(NULL, 0, __FILE__, __LINE__);
1083 goto done;
1084 }
1085 }
1086 if (!buflen && no_name) {
1087 Py_INCREF(Py_None);
1088 name_obj = Py_None;
1089 }
1090 else {
1091 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1092 }
1093
1094 done:
1095 if (buf != namebuf) {
1096 PyMem_Free(namebuf);
1097 }
1098 return name_obj;
1099}
1100
1101static PyObject *
1102_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1103{
1104 Py_ssize_t buflen;
1105 unsigned char *valuebuf = NULL;
1106 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1109 if (buflen < 0) {
1110 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001111 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001113 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001116}
1117
1118static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001120{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1122 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1123 PyObject *rdnt;
1124 PyObject *attr = NULL; /* tuple to hold an attribute */
1125 int entry_count = X509_NAME_entry_count(xname);
1126 X509_NAME_ENTRY *entry;
1127 ASN1_OBJECT *name;
1128 ASN1_STRING *value;
1129 int index_counter;
1130 int rdn_level = -1;
1131 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 dn = PyList_New(0);
1134 if (dn == NULL)
1135 return NULL;
1136 /* now create another tuple to hold the top-level RDN */
1137 rdn = PyList_New(0);
1138 if (rdn == NULL)
1139 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 for (index_counter = 0;
1142 index_counter < entry_count;
1143 index_counter++)
1144 {
1145 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 /* check to see if we've gotten to a new RDN */
1148 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001149 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 /* yes, new RDN */
1151 /* add old RDN to DN */
1152 rdnt = PyList_AsTuple(rdn);
1153 Py_DECREF(rdn);
1154 if (rdnt == NULL)
1155 goto fail0;
1156 retcode = PyList_Append(dn, rdnt);
1157 Py_DECREF(rdnt);
1158 if (retcode < 0)
1159 goto fail0;
1160 /* create new RDN */
1161 rdn = PyList_New(0);
1162 if (rdn == NULL)
1163 goto fail0;
1164 }
1165 }
Christian Heimes598894f2016-09-05 23:19:05 +02001166 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 /* now add this attribute to the current RDN */
1169 name = X509_NAME_ENTRY_get_object(entry);
1170 value = X509_NAME_ENTRY_get_data(entry);
1171 attr = _create_tuple_for_attribute(name, value);
1172 /*
1173 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1174 entry->set,
1175 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1176 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1177 */
1178 if (attr == NULL)
1179 goto fail1;
1180 retcode = PyList_Append(rdn, attr);
1181 Py_DECREF(attr);
1182 if (retcode < 0)
1183 goto fail1;
1184 }
1185 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001186 if (rdn != NULL) {
1187 if (PyList_GET_SIZE(rdn) > 0) {
1188 rdnt = PyList_AsTuple(rdn);
1189 Py_DECREF(rdn);
1190 if (rdnt == NULL)
1191 goto fail0;
1192 retcode = PyList_Append(dn, rdnt);
1193 Py_DECREF(rdnt);
1194 if (retcode < 0)
1195 goto fail0;
1196 }
1197 else {
1198 Py_DECREF(rdn);
1199 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 /* convert list to tuple */
1203 rdnt = PyList_AsTuple(dn);
1204 Py_DECREF(dn);
1205 if (rdnt == NULL)
1206 return NULL;
1207 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
1209 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211
1212 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 Py_XDECREF(dn);
1214 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215}
1216
1217static PyObject *
1218_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 /* this code follows the procedure outlined in
1221 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1222 function to extract the STACK_OF(GENERAL_NAME),
1223 then iterates through the stack to add the
1224 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001226 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001228 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 GENERAL_NAMES *names = NULL;
1230 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 BIO *biobuf = NULL;
1232 char buf[2048];
1233 char *vptr;
1234 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 if (certificate == NULL)
1237 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 /* get a memory buffer */
1240 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001242 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1243 certificate, NID_subject_alt_name, NULL, NULL);
1244 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 if (peer_alt_names == Py_None) {
1246 peer_alt_names = PyList_New(0);
1247 if (peer_alt_names == NULL)
1248 goto fail;
1249 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001253 int gntype;
1254 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001257 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001258 switch (gntype) {
1259 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 /* we special-case DirName as a tuple of
1261 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 t = PyTuple_New(2);
1264 if (t == NULL) {
1265 goto fail;
1266 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 v = PyUnicode_FromString("DirName");
1269 if (v == NULL) {
1270 Py_DECREF(t);
1271 goto fail;
1272 }
1273 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 v = _create_tuple_for_X509_NAME (name->d.dirn);
1276 if (v == NULL) {
1277 Py_DECREF(t);
1278 goto fail;
1279 }
1280 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001281 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001282
Christian Heimes824f7f32013-08-17 00:54:47 +02001283 case GEN_EMAIL:
1284 case GEN_DNS:
1285 case GEN_URI:
1286 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1287 correctly, CVE-2013-4238 */
1288 t = PyTuple_New(2);
1289 if (t == NULL)
1290 goto fail;
1291 switch (gntype) {
1292 case GEN_EMAIL:
1293 v = PyUnicode_FromString("email");
1294 as = name->d.rfc822Name;
1295 break;
1296 case GEN_DNS:
1297 v = PyUnicode_FromString("DNS");
1298 as = name->d.dNSName;
1299 break;
1300 case GEN_URI:
1301 v = PyUnicode_FromString("URI");
1302 as = name->d.uniformResourceIdentifier;
1303 break;
1304 }
1305 if (v == NULL) {
1306 Py_DECREF(t);
1307 goto fail;
1308 }
1309 PyTuple_SET_ITEM(t, 0, v);
1310 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1311 ASN1_STRING_length(as));
1312 if (v == NULL) {
1313 Py_DECREF(t);
1314 goto fail;
1315 }
1316 PyTuple_SET_ITEM(t, 1, v);
1317 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318
Christian Heimes1c03abd2016-09-06 23:25:35 +02001319 case GEN_RID:
1320 t = PyTuple_New(2);
1321 if (t == NULL)
1322 goto fail;
1323
1324 v = PyUnicode_FromString("Registered ID");
1325 if (v == NULL) {
1326 Py_DECREF(t);
1327 goto fail;
1328 }
1329 PyTuple_SET_ITEM(t, 0, v);
1330
1331 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1332 if (len < 0) {
1333 Py_DECREF(t);
1334 _setSSLError(NULL, 0, __FILE__, __LINE__);
1335 goto fail;
1336 } else if (len >= (int)sizeof(buf)) {
1337 v = PyUnicode_FromString("<INVALID>");
1338 } else {
1339 v = PyUnicode_FromStringAndSize(buf, len);
1340 }
1341 if (v == NULL) {
1342 Py_DECREF(t);
1343 goto fail;
1344 }
1345 PyTuple_SET_ITEM(t, 1, v);
1346 break;
1347
Christian Heimes824f7f32013-08-17 00:54:47 +02001348 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001350 switch (gntype) {
1351 /* check for new general name type */
1352 case GEN_OTHERNAME:
1353 case GEN_X400:
1354 case GEN_EDIPARTY:
1355 case GEN_IPADD:
1356 case GEN_RID:
1357 break;
1358 default:
1359 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1360 "Unknown general name type %d",
1361 gntype) == -1) {
1362 goto fail;
1363 }
1364 break;
1365 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 (void) BIO_reset(biobuf);
1367 GENERAL_NAME_print(biobuf, name);
1368 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1369 if (len < 0) {
1370 _setSSLError(NULL, 0, __FILE__, __LINE__);
1371 goto fail;
1372 }
1373 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001374 if (vptr == NULL) {
1375 PyErr_Format(PyExc_ValueError,
1376 "Invalid value %.200s",
1377 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001379 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 t = PyTuple_New(2);
1381 if (t == NULL)
1382 goto fail;
1383 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1384 if (v == NULL) {
1385 Py_DECREF(t);
1386 goto fail;
1387 }
1388 PyTuple_SET_ITEM(t, 0, v);
1389 v = PyUnicode_FromStringAndSize((vptr + 1),
1390 (len - (vptr - buf + 1)));
1391 if (v == NULL) {
1392 Py_DECREF(t);
1393 goto fail;
1394 }
1395 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001396 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 if (PyList_Append(peer_alt_names, t) < 0) {
1402 Py_DECREF(t);
1403 goto fail;
1404 }
1405 Py_DECREF(t);
1406 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001407 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 }
1409 BIO_free(biobuf);
1410 if (peer_alt_names != Py_None) {
1411 v = PyList_AsTuple(peer_alt_names);
1412 Py_DECREF(peer_alt_names);
1413 return v;
1414 } else {
1415 return peer_alt_names;
1416 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418
1419 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 if (biobuf != NULL)
1421 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 if (peer_alt_names != Py_None) {
1424 Py_XDECREF(peer_alt_names);
1425 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428}
1429
1430static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001431_get_aia_uri(X509 *certificate, int nid) {
1432 PyObject *lst = NULL, *ostr = NULL;
1433 int i, result;
1434 AUTHORITY_INFO_ACCESS *info;
1435
1436 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001437 if (info == NULL)
1438 return Py_None;
1439 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1440 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001441 return Py_None;
1442 }
1443
1444 if ((lst = PyList_New(0)) == NULL) {
1445 goto fail;
1446 }
1447
1448 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1449 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1450 ASN1_IA5STRING *uri;
1451
1452 if ((OBJ_obj2nid(ad->method) != nid) ||
1453 (ad->location->type != GEN_URI)) {
1454 continue;
1455 }
1456 uri = ad->location->d.uniformResourceIdentifier;
1457 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1458 uri->length);
1459 if (ostr == NULL) {
1460 goto fail;
1461 }
1462 result = PyList_Append(lst, ostr);
1463 Py_DECREF(ostr);
1464 if (result < 0) {
1465 goto fail;
1466 }
1467 }
1468 AUTHORITY_INFO_ACCESS_free(info);
1469
1470 /* convert to tuple or None */
1471 if (PyList_Size(lst) == 0) {
1472 Py_DECREF(lst);
1473 return Py_None;
1474 } else {
1475 PyObject *tup;
1476 tup = PyList_AsTuple(lst);
1477 Py_DECREF(lst);
1478 return tup;
1479 }
1480
1481 fail:
1482 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001483 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001484 return NULL;
1485}
1486
1487static PyObject *
1488_get_crl_dp(X509 *certificate) {
1489 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001490 int i, j;
1491 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001492
Christian Heimes598894f2016-09-05 23:19:05 +02001493 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001494
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001495 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001496 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001497
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001498 lst = PyList_New(0);
1499 if (lst == NULL)
1500 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001501
1502 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1503 DIST_POINT *dp;
1504 STACK_OF(GENERAL_NAME) *gns;
1505
1506 dp = sk_DIST_POINT_value(dps, i);
1507 gns = dp->distpoint->name.fullname;
1508
1509 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1510 GENERAL_NAME *gn;
1511 ASN1_IA5STRING *uri;
1512 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001513 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001514
1515 gn = sk_GENERAL_NAME_value(gns, j);
1516 if (gn->type != GEN_URI) {
1517 continue;
1518 }
1519 uri = gn->d.uniformResourceIdentifier;
1520 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1521 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001522 if (ouri == NULL)
1523 goto done;
1524
1525 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001526 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001527 if (err < 0)
1528 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 }
1530 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001531
1532 /* Convert to tuple. */
1533 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1534
1535 done:
1536 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001537 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001538 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001539}
1540
1541static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001542_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 PyObject *retval = NULL;
1545 BIO *biobuf = NULL;
1546 PyObject *peer;
1547 PyObject *peer_alt_names = NULL;
1548 PyObject *issuer;
1549 PyObject *version;
1550 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001551 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 ASN1_INTEGER *serialNumber;
1553 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001554 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 ASN1_TIME *notBefore, *notAfter;
1556 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 retval = PyDict_New();
1559 if (retval == NULL)
1560 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 peer = _create_tuple_for_X509_NAME(
1563 X509_get_subject_name(certificate));
1564 if (peer == NULL)
1565 goto fail0;
1566 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1567 Py_DECREF(peer);
1568 goto fail0;
1569 }
1570 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001571
Antoine Pitroufb046912010-11-09 20:21:19 +00001572 issuer = _create_tuple_for_X509_NAME(
1573 X509_get_issuer_name(certificate));
1574 if (issuer == NULL)
1575 goto fail0;
1576 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001578 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001580 Py_DECREF(issuer);
1581
1582 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001583 if (version == NULL)
1584 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001585 if (PyDict_SetItemString(retval, "version", version) < 0) {
1586 Py_DECREF(version);
1587 goto fail0;
1588 }
1589 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001591 /* get a memory buffer */
1592 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001593
Antoine Pitroufb046912010-11-09 20:21:19 +00001594 (void) BIO_reset(biobuf);
1595 serialNumber = X509_get_serialNumber(certificate);
1596 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1597 i2a_ASN1_INTEGER(biobuf, serialNumber);
1598 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1599 if (len < 0) {
1600 _setSSLError(NULL, 0, __FILE__, __LINE__);
1601 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001603 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1604 if (sn_obj == NULL)
1605 goto fail1;
1606 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1607 Py_DECREF(sn_obj);
1608 goto fail1;
1609 }
1610 Py_DECREF(sn_obj);
1611
1612 (void) BIO_reset(biobuf);
1613 notBefore = X509_get_notBefore(certificate);
1614 ASN1_TIME_print(biobuf, notBefore);
1615 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1616 if (len < 0) {
1617 _setSSLError(NULL, 0, __FILE__, __LINE__);
1618 goto fail1;
1619 }
1620 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1621 if (pnotBefore == NULL)
1622 goto fail1;
1623 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1624 Py_DECREF(pnotBefore);
1625 goto fail1;
1626 }
1627 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 (void) BIO_reset(biobuf);
1630 notAfter = X509_get_notAfter(certificate);
1631 ASN1_TIME_print(biobuf, notAfter);
1632 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1633 if (len < 0) {
1634 _setSSLError(NULL, 0, __FILE__, __LINE__);
1635 goto fail1;
1636 }
1637 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1638 if (pnotAfter == NULL)
1639 goto fail1;
1640 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1641 Py_DECREF(pnotAfter);
1642 goto fail1;
1643 }
1644 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 peer_alt_names = _get_peer_alt_names(certificate);
1649 if (peer_alt_names == NULL)
1650 goto fail1;
1651 else if (peer_alt_names != Py_None) {
1652 if (PyDict_SetItemString(retval, "subjectAltName",
1653 peer_alt_names) < 0) {
1654 Py_DECREF(peer_alt_names);
1655 goto fail1;
1656 }
1657 Py_DECREF(peer_alt_names);
1658 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001659
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001660 /* Authority Information Access: OCSP URIs */
1661 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1662 if (obj == NULL) {
1663 goto fail1;
1664 } else if (obj != Py_None) {
1665 result = PyDict_SetItemString(retval, "OCSP", obj);
1666 Py_DECREF(obj);
1667 if (result < 0) {
1668 goto fail1;
1669 }
1670 }
1671
1672 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1673 if (obj == NULL) {
1674 goto fail1;
1675 } else if (obj != Py_None) {
1676 result = PyDict_SetItemString(retval, "caIssuers", obj);
1677 Py_DECREF(obj);
1678 if (result < 0) {
1679 goto fail1;
1680 }
1681 }
1682
1683 /* CDP (CRL distribution points) */
1684 obj = _get_crl_dp(certificate);
1685 if (obj == NULL) {
1686 goto fail1;
1687 } else if (obj != Py_None) {
1688 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1689 Py_DECREF(obj);
1690 if (result < 0) {
1691 goto fail1;
1692 }
1693 }
1694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 BIO_free(biobuf);
1696 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001697
1698 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 if (biobuf != NULL)
1700 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001701 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 Py_XDECREF(retval);
1703 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001704}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001705
Christian Heimes9a5395a2013-06-17 15:44:12 +02001706static PyObject *
1707_certificate_to_der(X509 *certificate)
1708{
1709 unsigned char *bytes_buf = NULL;
1710 int len;
1711 PyObject *retval;
1712
1713 bytes_buf = NULL;
1714 len = i2d_X509(certificate, &bytes_buf);
1715 if (len < 0) {
1716 _setSSLError(NULL, 0, __FILE__, __LINE__);
1717 return NULL;
1718 }
1719 /* this is actually an immutable bytes sequence */
1720 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1721 OPENSSL_free(bytes_buf);
1722 return retval;
1723}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001725/*[clinic input]
1726_ssl._test_decode_cert
1727 path: object(converter="PyUnicode_FSConverter")
1728 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001730[clinic start generated code]*/
1731
1732static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001733_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1734/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001735{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 X509 *x=NULL;
1738 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1741 PyErr_SetString(PySSLErrorObject,
1742 "Can't malloc memory to read file");
1743 goto fail0;
1744 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001746 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 PyErr_SetString(PySSLErrorObject,
1748 "Can't open file");
1749 goto fail0;
1750 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1753 if (x == NULL) {
1754 PyErr_SetString(PySSLErrorObject,
1755 "Error decoding PEM-encoded file");
1756 goto fail0;
1757 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758
Antoine Pitroufb046912010-11-09 20:21:19 +00001759 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001760 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
1762 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001763 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 if (cert != NULL) BIO_free(cert);
1765 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766}
1767
1768
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001769/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001770_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001771 der as binary_mode: bool = False
1772 /
1773
1774Returns the certificate for the peer.
1775
1776If no certificate was provided, returns None. If a certificate was
1777provided, but not validated, returns an empty dictionary. Otherwise
1778returns a dict containing information about the peer certificate.
1779
1780If the optional argument is True, returns a DER-encoded copy of the
1781peer certificate, or None if no certificate was provided. This will
1782return the certificate even if it wasn't validated.
1783[clinic start generated code]*/
1784
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001786_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1787/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001790 X509 *peer_cert;
1791 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
Christian Heimes66dc33b2017-05-23 16:02:02 -07001793 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001794 PyErr_SetString(PyExc_ValueError,
1795 "handshake not done yet");
1796 return NULL;
1797 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001798 peer_cert = SSL_get_peer_certificate(self->ssl);
1799 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801
Antoine Pitrou721738f2012-08-15 23:20:39 +02001802 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001804 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001806 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001810 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001812 X509_free(peer_cert);
1813 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814}
1815
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001816static PyObject *
1817cipher_to_tuple(const SSL_CIPHER *cipher)
1818{
1819 const char *cipher_name, *cipher_protocol;
1820 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (retval == NULL)
1822 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001823
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001826 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 PyTuple_SET_ITEM(retval, 0, Py_None);
1828 } else {
1829 v = PyUnicode_FromString(cipher_name);
1830 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001831 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001832 PyTuple_SET_ITEM(retval, 0, v);
1833 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001834
1835 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001837 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001838 PyTuple_SET_ITEM(retval, 1, Py_None);
1839 } else {
1840 v = PyUnicode_FromString(cipher_protocol);
1841 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001842 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 PyTuple_SET_ITEM(retval, 1, v);
1844 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001845
1846 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001848 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001852
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001853 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 Py_DECREF(retval);
1855 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001856}
1857
Christian Heimes25bfcd52016-09-06 00:04:45 +02001858#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1859static PyObject *
1860cipher_to_dict(const SSL_CIPHER *cipher)
1861{
1862 const char *cipher_name, *cipher_protocol;
1863
1864 unsigned long cipher_id;
1865 int alg_bits, strength_bits, len;
1866 char buf[512] = {0};
1867#if OPENSSL_VERSION_1_1
1868 int aead, nid;
1869 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1870#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001871
1872 /* can be NULL */
1873 cipher_name = SSL_CIPHER_get_name(cipher);
1874 cipher_protocol = SSL_CIPHER_get_version(cipher);
1875 cipher_id = SSL_CIPHER_get_id(cipher);
1876 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001877 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1878 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001879 if (len > 1 && buf[len-1] == '\n')
1880 buf[len-1] = '\0';
1881 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1882
1883#if OPENSSL_VERSION_1_1
1884 aead = SSL_CIPHER_is_aead(cipher);
1885 nid = SSL_CIPHER_get_cipher_nid(cipher);
1886 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1887 nid = SSL_CIPHER_get_digest_nid(cipher);
1888 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1889 nid = SSL_CIPHER_get_kx_nid(cipher);
1890 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1891 nid = SSL_CIPHER_get_auth_nid(cipher);
1892 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1893#endif
1894
Victor Stinner410b9882016-09-12 12:00:23 +02001895 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001896 "{sksssssssisi"
1897#if OPENSSL_VERSION_1_1
1898 "sOssssssss"
1899#endif
1900 "}",
1901 "id", cipher_id,
1902 "name", cipher_name,
1903 "protocol", cipher_protocol,
1904 "description", buf,
1905 "strength_bits", strength_bits,
1906 "alg_bits", alg_bits
1907#if OPENSSL_VERSION_1_1
1908 ,"aead", aead ? Py_True : Py_False,
1909 "symmetric", skcipher,
1910 "digest", digest,
1911 "kea", kx,
1912 "auth", auth
1913#endif
1914 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001915}
1916#endif
1917
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001918/*[clinic input]
1919_ssl._SSLSocket.shared_ciphers
1920[clinic start generated code]*/
1921
1922static PyObject *
1923_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1924/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001925{
1926 STACK_OF(SSL_CIPHER) *ciphers;
1927 int i;
1928 PyObject *res;
1929
Christian Heimes598894f2016-09-05 23:19:05 +02001930 ciphers = SSL_get_ciphers(self->ssl);
1931 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001932 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001933 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1934 if (!res)
1935 return NULL;
1936 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1937 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1938 if (!tup) {
1939 Py_DECREF(res);
1940 return NULL;
1941 }
1942 PyList_SET_ITEM(res, i, tup);
1943 }
1944 return res;
1945}
1946
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001947/*[clinic input]
1948_ssl._SSLSocket.cipher
1949[clinic start generated code]*/
1950
1951static PyObject *
1952_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1953/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001954{
1955 const SSL_CIPHER *current;
1956
1957 if (self->ssl == NULL)
1958 Py_RETURN_NONE;
1959 current = SSL_get_current_cipher(self->ssl);
1960 if (current == NULL)
1961 Py_RETURN_NONE;
1962 return cipher_to_tuple(current);
1963}
1964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001965/*[clinic input]
1966_ssl._SSLSocket.version
1967[clinic start generated code]*/
1968
1969static PyObject *
1970_ssl__SSLSocket_version_impl(PySSLSocket *self)
1971/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001972{
1973 const char *version;
1974
1975 if (self->ssl == NULL)
1976 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001977 if (!SSL_is_init_finished(self->ssl)) {
1978 /* handshake not finished */
1979 Py_RETURN_NONE;
1980 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001981 version = SSL_get_version(self->ssl);
1982 if (!strcmp(version, "unknown"))
1983 Py_RETURN_NONE;
1984 return PyUnicode_FromString(version);
1985}
1986
Miss Islington (bot)96177412018-02-25 04:18:43 -08001987#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001988/*[clinic input]
1989_ssl._SSLSocket.selected_npn_protocol
1990[clinic start generated code]*/
1991
1992static PyObject *
1993_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1994/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1995{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001996 const unsigned char *out;
1997 unsigned int outlen;
1998
Victor Stinner4569cd52013-06-23 14:58:43 +02001999 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002000 &out, &outlen);
2001
2002 if (out == NULL)
2003 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002004 return PyUnicode_FromStringAndSize((char *)out, outlen);
2005}
2006#endif
2007
Miss Islington (bot)96177412018-02-25 04:18:43 -08002008#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002009/*[clinic input]
2010_ssl._SSLSocket.selected_alpn_protocol
2011[clinic start generated code]*/
2012
2013static PyObject *
2014_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2015/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2016{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002017 const unsigned char *out;
2018 unsigned int outlen;
2019
2020 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2021
2022 if (out == NULL)
2023 Py_RETURN_NONE;
2024 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002025}
2026#endif
2027
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002028/*[clinic input]
2029_ssl._SSLSocket.compression
2030[clinic start generated code]*/
2031
2032static PyObject *
2033_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2034/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2035{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002036#ifdef OPENSSL_NO_COMP
2037 Py_RETURN_NONE;
2038#else
2039 const COMP_METHOD *comp_method;
2040 const char *short_name;
2041
2042 if (self->ssl == NULL)
2043 Py_RETURN_NONE;
2044 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002045 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002046 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002047 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002048 if (short_name == NULL)
2049 Py_RETURN_NONE;
2050 return PyUnicode_DecodeFSDefault(short_name);
2051#endif
2052}
2053
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002054static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2055 Py_INCREF(self->ctx);
2056 return self->ctx;
2057}
2058
2059static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2060 void *closure) {
2061
2062 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002063#if !HAVE_SNI
2064 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2065 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002066 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002067#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002068 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002069 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002070 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002071#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002072 } else {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002073 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002074 return -1;
2075 }
2076
2077 return 0;
2078}
2079
2080PyDoc_STRVAR(PySSL_set_context_doc,
2081"_setter_context(ctx)\n\
2082\
2083This changes the context associated with the SSLSocket. This is typically\n\
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002084used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085on the SSLContext to change the certificate information associated with the\n\
2086SSLSocket before the cryptographic exchange handshake messages\n");
2087
2088
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002089static PyObject *
2090PySSL_get_server_side(PySSLSocket *self, void *c)
2091{
2092 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2093}
2094
2095PyDoc_STRVAR(PySSL_get_server_side_doc,
2096"Whether this is a server-side socket.");
2097
2098static PyObject *
2099PySSL_get_server_hostname(PySSLSocket *self, void *c)
2100{
2101 if (self->server_hostname == NULL)
2102 Py_RETURN_NONE;
2103 Py_INCREF(self->server_hostname);
2104 return self->server_hostname;
2105}
2106
2107PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2108"The currently set server hostname (for SNI).");
2109
2110static PyObject *
2111PySSL_get_owner(PySSLSocket *self, void *c)
2112{
2113 PyObject *owner;
2114
2115 if (self->owner == NULL)
2116 Py_RETURN_NONE;
2117
2118 owner = PyWeakref_GetObject(self->owner);
2119 Py_INCREF(owner);
2120 return owner;
2121}
2122
2123static int
2124PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2125{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002126 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002127 if (self->owner == NULL)
2128 return -1;
2129 return 0;
2130}
2131
2132PyDoc_STRVAR(PySSL_get_owner_doc,
2133"The Python-level owner of this object.\
2134Passed as \"self\" in servername callback.");
2135
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002136
Antoine Pitrou152efa22010-05-16 18:19:27 +00002137static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002138{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 if (self->ssl)
2140 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002141 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002142 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002143 Py_XDECREF(self->server_hostname);
2144 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002145 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002146}
2147
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002148/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002149 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002150 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002151 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002152
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002153static int
Victor Stinner14690702015-04-06 22:46:13 +02002154PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002155{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002156 int rc;
2157#ifdef HAVE_POLL
2158 struct pollfd pollfd;
2159 _PyTime_t ms;
2160#else
2161 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 fd_set fds;
2163 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002164#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002167 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002169 else if (timeout < 0) {
2170 if (s->sock_timeout > 0)
2171 return SOCKET_HAS_TIMED_OUT;
2172 else
2173 return SOCKET_IS_BLOCKING;
2174 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002177 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 /* Prefer poll, if available, since you can poll() any fd
2181 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002182#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002183 pollfd.fd = s->sock_fd;
2184 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002185
Victor Stinner14690702015-04-06 22:46:13 +02002186 /* timeout is in seconds, poll() uses milliseconds */
2187 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002188 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002189
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002190 PySSL_BEGIN_ALLOW_THREADS
2191 rc = poll(&pollfd, 1, (int)ms);
2192 PySSL_END_ALLOW_THREADS
2193#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002195 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002197
Victor Stinner14690702015-04-06 22:46:13 +02002198 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 FD_ZERO(&fds);
2201 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002202
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002203 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002205 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002207 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002209 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002211#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2214 (when we are able to write or when there's something to read) */
2215 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002216}
2217
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002218/*[clinic input]
2219_ssl._SSLSocket.write
2220 b: Py_buffer
2221 /
2222
2223Writes the bytes-like object b into the SSL object.
2224
2225Returns the number of bytes written.
2226[clinic start generated code]*/
2227
2228static PyObject *
2229_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2230/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002231{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 int len;
2233 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002234 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002236 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002237 _PyTime_t timeout, deadline = 0;
2238 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002239
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002240 if (sock != NULL) {
2241 if (((PyObject*)sock) == Py_None) {
2242 _setSSLError("Underlying socket connection gone",
2243 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2244 return NULL;
2245 }
2246 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 }
2248
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002249 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002250 PyErr_Format(PyExc_OverflowError,
2251 "string longer than %d bytes", INT_MAX);
2252 goto error;
2253 }
2254
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002255 if (sock != NULL) {
2256 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002257 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002258 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2259 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2260 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261
Victor Stinner14690702015-04-06 22:46:13 +02002262 timeout = GET_SOCKET_TIMEOUT(sock);
2263 has_timeout = (timeout > 0);
2264 if (has_timeout)
2265 deadline = _PyTime_GetMonotonicClock() + timeout;
2266
2267 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002269 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002270 "The write operation timed out");
2271 goto error;
2272 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2273 PyErr_SetString(PySSLErrorObject,
2274 "Underlying socket has been closed.");
2275 goto error;
2276 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2277 PyErr_SetString(PySSLErrorObject,
2278 "Underlying socket too large for select().");
2279 goto error;
2280 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002284 len = SSL_write(self->ssl, b->buf, (int)b->len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002285 err = _PySSL_errno(len <= 0, self->ssl, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002287 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002288
2289 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002291
Victor Stinner14690702015-04-06 22:46:13 +02002292 if (has_timeout)
2293 timeout = deadline - _PyTime_GetMonotonicClock();
2294
Miss Islington (bot)12296642018-09-17 12:12:13 -07002295 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002296 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002297 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002298 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 } else {
2300 sockstate = SOCKET_OPERATION_OK;
2301 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002304 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 "The write operation timed out");
2306 goto error;
2307 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2308 PyErr_SetString(PySSLErrorObject,
2309 "Underlying socket has been closed.");
2310 goto error;
2311 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2312 break;
2313 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002314 } while (err.ssl == SSL_ERROR_WANT_READ ||
2315 err.ssl == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002316
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002317 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002318 if (len > 0)
2319 return PyLong_FromLong(len);
2320 else
2321 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002322
2323error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002324 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002325 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002326}
2327
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002328/*[clinic input]
2329_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002330
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002331Returns the number of already decrypted bytes available for read, pending on the connection.
2332[clinic start generated code]*/
2333
2334static PyObject *
2335_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2336/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002337{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 int count = 0;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002339 _PySSLError err;
Bill Janssen6e027db2007-11-15 22:23:56 +00002340
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 PySSL_BEGIN_ALLOW_THREADS
2342 count = SSL_pending(self->ssl);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002343 err = _PySSL_errno(count < 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002344 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002345 self->err = err;
2346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002347 if (count < 0)
2348 return PySSL_SetError(self, count, __FILE__, __LINE__);
2349 else
2350 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002351}
2352
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002353/*[clinic input]
2354_ssl._SSLSocket.read
2355 size as len: int
2356 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002357 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002358 ]
2359 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002360
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002361Read up to size bytes from the SSL socket.
2362[clinic start generated code]*/
2363
2364static PyObject *
2365_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2366 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002367/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002368{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002369 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002370 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002371 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002372 int sockstate;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002373 _PySSLError err;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002375 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002376 _PyTime_t timeout, deadline = 0;
2377 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002378
Martin Panter5503d472016-03-27 05:35:19 +00002379 if (!group_right_1 && len < 0) {
2380 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2381 return NULL;
2382 }
2383
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002384 if (sock != NULL) {
2385 if (((PyObject*)sock) == Py_None) {
2386 _setSSLError("Underlying socket connection gone",
2387 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2388 return NULL;
2389 }
2390 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 }
2392
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002393 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002394 dest = PyBytes_FromStringAndSize(NULL, len);
2395 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002396 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002397 if (len == 0) {
2398 Py_XDECREF(sock);
2399 return dest;
2400 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002401 mem = PyBytes_AS_STRING(dest);
2402 }
2403 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002404 mem = buffer->buf;
2405 if (len <= 0 || len > buffer->len) {
2406 len = (int) buffer->len;
2407 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002408 PyErr_SetString(PyExc_OverflowError,
2409 "maximum length can't fit in a C 'int'");
2410 goto error;
2411 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002412 if (len == 0) {
2413 count = 0;
2414 goto done;
2415 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002416 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 }
2418
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002419 if (sock != NULL) {
2420 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002421 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002422 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2423 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2424 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425
Victor Stinner14690702015-04-06 22:46:13 +02002426 timeout = GET_SOCKET_TIMEOUT(sock);
2427 has_timeout = (timeout > 0);
2428 if (has_timeout)
2429 deadline = _PyTime_GetMonotonicClock() + timeout;
2430
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002431 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 PySSL_BEGIN_ALLOW_THREADS
2433 count = SSL_read(self->ssl, mem, len);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002434 err = _PySSL_errno(count <= 0, self->ssl, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002435 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002436 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002437
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 if (PyErr_CheckSignals())
2439 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002440
Victor Stinner14690702015-04-06 22:46:13 +02002441 if (has_timeout)
2442 timeout = deadline - _PyTime_GetMonotonicClock();
2443
Miss Islington (bot)12296642018-09-17 12:12:13 -07002444 if (err.ssl == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002445 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002446 } else if (err.ssl == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002447 sockstate = PySSL_select(sock, 1, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002448 } else if (err.ssl == SSL_ERROR_ZERO_RETURN &&
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002449 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 {
2451 count = 0;
2452 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002454 else
2455 sockstate = SOCKET_OPERATION_OK;
2456
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002457 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002458 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 "The read operation timed out");
2460 goto error;
2461 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2462 break;
2463 }
Miss Islington (bot)12296642018-09-17 12:12:13 -07002464 } while (err.ssl == SSL_ERROR_WANT_READ ||
2465 err.ssl == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002466
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002467 if (count <= 0) {
2468 PySSL_SetError(self, count, __FILE__, __LINE__);
2469 goto error;
2470 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002471
2472done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002473 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002474 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002475 _PyBytes_Resize(&dest, count);
2476 return dest;
2477 }
2478 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 return PyLong_FromLong(count);
2480 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002481
2482error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002483 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002484 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002485 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002486 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002487}
2488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002489/*[clinic input]
2490_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002491
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002492Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002493[clinic start generated code]*/
2494
2495static PyObject *
2496_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002497/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002498{
Miss Islington (bot)12296642018-09-17 12:12:13 -07002499 _PySSLError err;
2500 int sockstate, nonblocking, ret;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002501 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002502 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002503 _PyTime_t timeout, deadline = 0;
2504 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002505
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002506 if (sock != NULL) {
2507 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002508 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002509 _setSSLError("Underlying socket connection gone",
2510 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2511 return NULL;
2512 }
2513 Py_INCREF(sock);
2514
2515 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002516 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002517 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2518 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002519 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002520
Victor Stinner14690702015-04-06 22:46:13 +02002521 timeout = GET_SOCKET_TIMEOUT(sock);
2522 has_timeout = (timeout > 0);
2523 if (has_timeout)
2524 deadline = _PyTime_GetMonotonicClock() + timeout;
2525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 while (1) {
2527 PySSL_BEGIN_ALLOW_THREADS
2528 /* Disable read-ahead so that unwrap can work correctly.
2529 * Otherwise OpenSSL might read in too much data,
2530 * eating clear text data that happens to be
2531 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002532 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002533 * function is used and the shutdown_seen_zero != 0
2534 * condition is met.
2535 */
2536 if (self->shutdown_seen_zero)
2537 SSL_set_read_ahead(self->ssl, 0);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002538 ret = SSL_shutdown(self->ssl);
2539 err = _PySSL_errno(ret < 0, self->ssl, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002540 PySSL_END_ALLOW_THREADS
Miss Islington (bot)12296642018-09-17 12:12:13 -07002541 self->err = err;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002544 if (ret > 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002545 break;
Miss Islington (bot)12296642018-09-17 12:12:13 -07002546 if (ret == 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002547 /* Don't loop endlessly; instead preserve legacy
2548 behaviour of trying SSL_shutdown() only twice.
2549 This looks necessary for OpenSSL < 0.9.8m */
2550 if (++zeros > 1)
2551 break;
2552 /* Shutdown was sent, now try receiving */
2553 self->shutdown_seen_zero = 1;
2554 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002555 }
2556
Victor Stinner14690702015-04-06 22:46:13 +02002557 if (has_timeout)
2558 timeout = deadline - _PyTime_GetMonotonicClock();
2559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 /* Possibly retry shutdown until timeout or failure */
Miss Islington (bot)12296642018-09-17 12:12:13 -07002561 if (err.ssl == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002562 sockstate = PySSL_select(sock, 0, timeout);
Miss Islington (bot)12296642018-09-17 12:12:13 -07002563 else if (err.ssl == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002564 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 else
2566 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Miss Islington (bot)12296642018-09-17 12:12:13 -07002569 if (err.ssl == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002570 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 "The read operation timed out");
2572 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002573 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002574 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002575 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 }
2577 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2578 PyErr_SetString(PySSLErrorObject,
2579 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002580 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 }
2582 else if (sockstate != SOCKET_OPERATION_OK)
2583 /* Retain the SSL error code */
2584 break;
2585 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002586
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002587 if (ret < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002588 Py_XDECREF(sock);
Miss Islington (bot)c00f7032018-09-21 22:00:42 -07002589 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002590 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002591 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002592 /* It's already INCREF'ed */
2593 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002594 else
2595 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002596
2597error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002598 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002599 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002600}
2601
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002602/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002603_ssl._SSLSocket.get_channel_binding
2604 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002605
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002606Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002607
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002608Raise ValueError if the requested `cb_type` is not supported. Return bytes
2609of the data or None if the data is not available (e.g. before the handshake).
2610Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002611[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002612
Antoine Pitroud6494802011-07-21 01:11:30 +02002613static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002614_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2615 const char *cb_type)
2616/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002617{
Antoine Pitroud6494802011-07-21 01:11:30 +02002618 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002619 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002620
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002621 if (strcmp(cb_type, "tls-unique") == 0) {
2622 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2623 /* if session is resumed XOR we are the client */
2624 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2625 }
2626 else {
2627 /* if a new session XOR we are the server */
2628 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2629 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002630 }
2631 else {
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002632 PyErr_Format(
2633 PyExc_ValueError,
2634 "'%s' channel binding type not implemented",
2635 cb_type
2636 );
2637 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002638 }
2639
2640 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002641 if (len == 0)
2642 Py_RETURN_NONE;
2643
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002644 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002645}
2646
Christian Heimes99a65702016-09-10 23:44:53 +02002647#ifdef OPENSSL_VERSION_1_1
2648
2649static SSL_SESSION*
2650_ssl_session_dup(SSL_SESSION *session) {
2651 SSL_SESSION *newsession = NULL;
2652 int slen;
2653 unsigned char *senc = NULL, *p;
2654 const unsigned char *const_p;
2655
2656 if (session == NULL) {
2657 PyErr_SetString(PyExc_ValueError, "Invalid session");
2658 goto error;
2659 }
2660
2661 /* get length */
2662 slen = i2d_SSL_SESSION(session, NULL);
2663 if (slen == 0 || slen > 0xFF00) {
2664 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2665 goto error;
2666 }
2667 if ((senc = PyMem_Malloc(slen)) == NULL) {
2668 PyErr_NoMemory();
2669 goto error;
2670 }
2671 p = senc;
2672 if (!i2d_SSL_SESSION(session, &p)) {
2673 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2674 goto error;
2675 }
2676 const_p = senc;
2677 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2678 if (session == NULL) {
2679 goto error;
2680 }
2681 PyMem_Free(senc);
2682 return newsession;
2683 error:
2684 if (senc != NULL) {
2685 PyMem_Free(senc);
2686 }
2687 return NULL;
2688}
2689#endif
2690
2691static PyObject *
2692PySSL_get_session(PySSLSocket *self, void *closure) {
2693 /* get_session can return sessions from a server-side connection,
2694 * it does not check for handshake done or client socket. */
2695 PySSLSession *pysess;
2696 SSL_SESSION *session;
2697
2698#ifdef OPENSSL_VERSION_1_1
2699 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2700 * https://github.com/openssl/openssl/issues/1550 */
2701 session = SSL_get0_session(self->ssl); /* borrowed reference */
2702 if (session == NULL) {
2703 Py_RETURN_NONE;
2704 }
2705 if ((session = _ssl_session_dup(session)) == NULL) {
2706 return NULL;
2707 }
2708#else
2709 session = SSL_get1_session(self->ssl);
2710 if (session == NULL) {
2711 Py_RETURN_NONE;
2712 }
2713#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002714 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002715 if (pysess == NULL) {
2716 SSL_SESSION_free(session);
2717 return NULL;
2718 }
2719
2720 assert(self->ctx);
2721 pysess->ctx = self->ctx;
2722 Py_INCREF(pysess->ctx);
2723 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002724 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002725 return (PyObject *)pysess;
2726}
2727
2728static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2729 void *closure)
2730 {
2731 PySSLSession *pysess;
2732#ifdef OPENSSL_VERSION_1_1
2733 SSL_SESSION *session;
2734#endif
2735 int result;
2736
2737 if (!PySSLSession_Check(value)) {
Miss Islington (bot)42198572018-06-11 17:58:06 -07002738 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002739 return -1;
2740 }
2741 pysess = (PySSLSession *)value;
2742
2743 if (self->ctx->ctx != pysess->ctx->ctx) {
2744 PyErr_SetString(PyExc_ValueError,
2745 "Session refers to a different SSLContext.");
2746 return -1;
2747 }
2748 if (self->socket_type != PY_SSL_CLIENT) {
2749 PyErr_SetString(PyExc_ValueError,
2750 "Cannot set session for server-side SSLSocket.");
2751 return -1;
2752 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002753 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002754 PyErr_SetString(PyExc_ValueError,
2755 "Cannot set session after handshake.");
2756 return -1;
2757 }
2758#ifdef OPENSSL_VERSION_1_1
2759 /* duplicate session */
2760 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2761 return -1;
2762 }
2763 result = SSL_set_session(self->ssl, session);
2764 /* free duplicate, SSL_set_session() bumps ref count */
2765 SSL_SESSION_free(session);
2766#else
2767 result = SSL_set_session(self->ssl, pysess->session);
2768#endif
2769 if (result == 0) {
2770 _setSSLError(NULL, 0, __FILE__, __LINE__);
2771 return -1;
2772 }
2773 return 0;
2774}
2775
2776PyDoc_STRVAR(PySSL_set_session_doc,
2777"_setter_session(session)\n\
2778\
2779Get / set SSLSession.");
2780
2781static PyObject *
2782PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2783 if (SSL_session_reused(self->ssl)) {
2784 Py_RETURN_TRUE;
2785 } else {
2786 Py_RETURN_FALSE;
2787 }
2788}
2789
2790PyDoc_STRVAR(PySSL_get_session_reused_doc,
2791"Was the client session reused during handshake?");
2792
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002793static PyGetSetDef ssl_getsetlist[] = {
2794 {"context", (getter) PySSL_get_context,
2795 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002796 {"server_side", (getter) PySSL_get_server_side, NULL,
2797 PySSL_get_server_side_doc},
2798 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2799 PySSL_get_server_hostname_doc},
2800 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2801 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002802 {"session", (getter) PySSL_get_session,
2803 (setter) PySSL_set_session, PySSL_set_session_doc},
2804 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2805 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002806 {NULL}, /* sentinel */
2807};
2808
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002809static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002810 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2811 _SSL__SSLSOCKET_WRITE_METHODDEF
2812 _SSL__SSLSOCKET_READ_METHODDEF
2813 _SSL__SSLSOCKET_PENDING_METHODDEF
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002814 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2815 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002816 _SSL__SSLSOCKET_CIPHER_METHODDEF
2817 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2818 _SSL__SSLSOCKET_VERSION_METHODDEF
2819 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2820 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2821 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2822 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002823 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002824};
2825
Antoine Pitrou152efa22010-05-16 18:19:27 +00002826static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002827 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002828 "_ssl._SSLSocket", /*tp_name*/
2829 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002830 0, /*tp_itemsize*/
2831 /* methods */
2832 (destructor)PySSL_dealloc, /*tp_dealloc*/
2833 0, /*tp_print*/
2834 0, /*tp_getattr*/
2835 0, /*tp_setattr*/
2836 0, /*tp_reserved*/
2837 0, /*tp_repr*/
2838 0, /*tp_as_number*/
2839 0, /*tp_as_sequence*/
2840 0, /*tp_as_mapping*/
2841 0, /*tp_hash*/
2842 0, /*tp_call*/
2843 0, /*tp_str*/
2844 0, /*tp_getattro*/
2845 0, /*tp_setattro*/
2846 0, /*tp_as_buffer*/
2847 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2848 0, /*tp_doc*/
2849 0, /*tp_traverse*/
2850 0, /*tp_clear*/
2851 0, /*tp_richcompare*/
2852 0, /*tp_weaklistoffset*/
2853 0, /*tp_iter*/
2854 0, /*tp_iternext*/
2855 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002856 0, /*tp_members*/
2857 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002858};
2859
Antoine Pitrou152efa22010-05-16 18:19:27 +00002860
2861/*
2862 * _SSLContext objects
2863 */
2864
Christian Heimes5fe668c2016-09-12 00:01:11 +02002865static int
2866_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2867{
2868 int mode;
2869 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2870
2871 switch(n) {
2872 case PY_SSL_CERT_NONE:
2873 mode = SSL_VERIFY_NONE;
2874 break;
2875 case PY_SSL_CERT_OPTIONAL:
2876 mode = SSL_VERIFY_PEER;
2877 break;
2878 case PY_SSL_CERT_REQUIRED:
2879 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2880 break;
2881 default:
2882 PyErr_SetString(PyExc_ValueError,
2883 "invalid value for verify_mode");
2884 return -1;
2885 }
2886 /* keep current verify cb */
2887 verify_cb = SSL_CTX_get_verify_callback(ctx);
2888 SSL_CTX_set_verify(ctx, mode, verify_cb);
2889 return 0;
2890}
2891
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002892/*[clinic input]
2893@classmethod
2894_ssl._SSLContext.__new__
2895 protocol as proto_version: int
2896 /
2897[clinic start generated code]*/
2898
Antoine Pitrou152efa22010-05-16 18:19:27 +00002899static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002900_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2901/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002902{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002903 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002904 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002905 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002906 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002907 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002908#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002909 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002910#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002911
Antoine Pitrou152efa22010-05-16 18:19:27 +00002912 PySSL_BEGIN_ALLOW_THREADS
2913 if (proto_version == PY_SSL_VERSION_TLS1)
2914 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002915#if HAVE_TLSv1_2
2916 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2917 ctx = SSL_CTX_new(TLSv1_1_method());
2918 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2919 ctx = SSL_CTX_new(TLSv1_2_method());
2920#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002921#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002922 else if (proto_version == PY_SSL_VERSION_SSL3)
2923 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002924#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002925#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002926 else if (proto_version == PY_SSL_VERSION_SSL2)
2927 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002928#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002929 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002930 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002931 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2932 ctx = SSL_CTX_new(TLS_client_method());
2933 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2934 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002935 else
2936 proto_version = -1;
2937 PySSL_END_ALLOW_THREADS
2938
2939 if (proto_version == -1) {
2940 PyErr_SetString(PyExc_ValueError,
2941 "invalid protocol version");
2942 return NULL;
2943 }
2944 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002945 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002946 return NULL;
2947 }
2948
2949 assert(type != NULL && type->tp_alloc != NULL);
2950 self = (PySSLContext *) type->tp_alloc(type, 0);
2951 if (self == NULL) {
2952 SSL_CTX_free(ctx);
2953 return NULL;
2954 }
2955 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002956 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002957 self->protocol = proto_version;
Miss Islington (bot)96177412018-02-25 04:18:43 -08002958#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002959 self->npn_protocols = NULL;
2960#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08002961#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002962 self->alpn_protocols = NULL;
2963#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002964#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002965 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002966#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002967 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002968 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2969 self->check_hostname = 1;
2970 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2971 Py_DECREF(self);
2972 return NULL;
2973 }
2974 } else {
2975 self->check_hostname = 0;
2976 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2977 Py_DECREF(self);
2978 return NULL;
2979 }
2980 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002981 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002982 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2983 if (proto_version != PY_SSL_VERSION_SSL2)
2984 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002985 if (proto_version != PY_SSL_VERSION_SSL3)
2986 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002987 /* Minimal security flags for server and client side context.
2988 * Client sockets ignore server-side parameters. */
2989#ifdef SSL_OP_NO_COMPRESSION
2990 options |= SSL_OP_NO_COMPRESSION;
2991#endif
2992#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2993 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2994#endif
2995#ifdef SSL_OP_SINGLE_DH_USE
2996 options |= SSL_OP_SINGLE_DH_USE;
2997#endif
2998#ifdef SSL_OP_SINGLE_ECDH_USE
2999 options |= SSL_OP_SINGLE_ECDH_USE;
3000#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01003001 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003002
Semen Zhydenko1295e112017-10-15 21:28:31 +02003003 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02003004 * It's far from perfect but gives users a better head start. */
3005 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003006#if PY_SSL_DEFAULT_CIPHERS == 2
3007 /* stick to OpenSSL's default settings */
3008 result = 1;
3009#else
3010 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3011#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003012 } else {
3013 /* SSLv2 needs MD5 */
3014 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3015 }
3016 if (result == 0) {
3017 Py_DECREF(self);
3018 ERR_clear_error();
3019 PyErr_SetString(PySSLErrorObject,
3020 "No cipher can be selected.");
3021 return NULL;
3022 }
3023
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003024#if defined(SSL_MODE_RELEASE_BUFFERS)
3025 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3026 usage for no cost at all. However, don't do this for OpenSSL versions
3027 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3028 2014-0198. I can't find exactly which beta fixed this CVE, so be
3029 conservative and assume it wasn't fixed until release. We do this check
3030 at runtime to avoid problems from the dynamic linker.
3031 See #25672 for more on this. */
3032 libver = SSLeay();
3033 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3034 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3035 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3036 }
3037#endif
3038
3039
Donald Stufft8ae264c2017-03-02 11:45:29 -05003040#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003041 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3042 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003043 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3044 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003045#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003046 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3047#else
3048 {
3049 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3050 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3051 EC_KEY_free(key);
3052 }
3053#endif
3054#endif
3055
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003056#define SID_CTX "Python"
3057 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3058 sizeof(SID_CTX));
3059#undef SID_CTX
3060
Christian Heimes61d478c2018-01-27 15:51:38 +01003061 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003062#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003063 /* Improve trust chain building when cross-signed intermediate
3064 certificates are present. See https://bugs.python.org/issue23476. */
3065 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003066#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003067 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003068
Antoine Pitrou152efa22010-05-16 18:19:27 +00003069 return (PyObject *)self;
3070}
3071
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003072static int
3073context_traverse(PySSLContext *self, visitproc visit, void *arg)
3074{
3075#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003076 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003077#endif
3078 return 0;
3079}
3080
3081static int
3082context_clear(PySSLContext *self)
3083{
3084#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003085 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003086#endif
3087 return 0;
3088}
3089
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090static void
3091context_dealloc(PySSLContext *self)
3092{
INADA Naokia6296d32017-08-24 14:55:17 +09003093 /* bpo-31095: UnTrack is needed before calling any callbacks */
3094 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003095 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003096 SSL_CTX_free(self->ctx);
Miss Islington (bot)96177412018-02-25 04:18:43 -08003097#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003098 PyMem_FREE(self->npn_protocols);
3099#endif
Miss Islington (bot)96177412018-02-25 04:18:43 -08003100#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003101 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003102#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003103 Py_TYPE(self)->tp_free(self);
3104}
3105
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003106/*[clinic input]
3107_ssl._SSLContext.set_ciphers
3108 cipherlist: str
3109 /
3110[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003111
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003112static PyObject *
3113_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3114/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3115{
3116 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003117 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003118 /* Clearing the error queue is necessary on some OpenSSL versions,
3119 otherwise the error will be reported again when another SSL call
3120 is done. */
3121 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003122 PyErr_SetString(PySSLErrorObject,
3123 "No cipher can be selected.");
3124 return NULL;
3125 }
3126 Py_RETURN_NONE;
3127}
3128
Christian Heimes25bfcd52016-09-06 00:04:45 +02003129#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3130/*[clinic input]
3131_ssl._SSLContext.get_ciphers
3132[clinic start generated code]*/
3133
3134static PyObject *
3135_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3136/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3137{
3138 SSL *ssl = NULL;
3139 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003140 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003141 int i=0;
3142 PyObject *result = NULL, *dct;
3143
3144 ssl = SSL_new(self->ctx);
3145 if (ssl == NULL) {
3146 _setSSLError(NULL, 0, __FILE__, __LINE__);
3147 goto exit;
3148 }
3149 sk = SSL_get_ciphers(ssl);
3150
3151 result = PyList_New(sk_SSL_CIPHER_num(sk));
3152 if (result == NULL) {
3153 goto exit;
3154 }
3155
3156 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3157 cipher = sk_SSL_CIPHER_value(sk, i);
3158 dct = cipher_to_dict(cipher);
3159 if (dct == NULL) {
3160 Py_CLEAR(result);
3161 goto exit;
3162 }
3163 PyList_SET_ITEM(result, i, dct);
3164 }
3165
3166 exit:
3167 if (ssl != NULL)
3168 SSL_free(ssl);
3169 return result;
3170
3171}
3172#endif
3173
3174
Miss Islington (bot)96177412018-02-25 04:18:43 -08003175#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003176static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003177do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3178 const unsigned char *server_protocols, unsigned int server_protocols_len,
3179 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003180{
Benjamin Peterson88615022015-01-23 17:30:26 -05003181 int ret;
3182 if (client_protocols == NULL) {
3183 client_protocols = (unsigned char *)"";
3184 client_protocols_len = 0;
3185 }
3186 if (server_protocols == NULL) {
3187 server_protocols = (unsigned char *)"";
3188 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003189 }
3190
Benjamin Peterson88615022015-01-23 17:30:26 -05003191 ret = SSL_select_next_proto(out, outlen,
3192 server_protocols, server_protocols_len,
3193 client_protocols, client_protocols_len);
3194 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3195 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003196
3197 return SSL_TLSEXT_ERR_OK;
3198}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003199#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003200
Miss Islington (bot)96177412018-02-25 04:18:43 -08003201#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003202/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3203static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003204_advertiseNPN_cb(SSL *s,
3205 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003206 void *args)
3207{
3208 PySSLContext *ssl_ctx = (PySSLContext *) args;
3209
3210 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003211 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003212 *len = 0;
3213 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003214 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003215 *len = ssl_ctx->npn_protocols_len;
3216 }
3217
3218 return SSL_TLSEXT_ERR_OK;
3219}
3220/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3221static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003222_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003223 unsigned char **out, unsigned char *outlen,
3224 const unsigned char *server, unsigned int server_len,
3225 void *args)
3226{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003227 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003228 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003229 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003230}
3231#endif
3232
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003233/*[clinic input]
3234_ssl._SSLContext._set_npn_protocols
3235 protos: Py_buffer
3236 /
3237[clinic start generated code]*/
3238
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003239static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3241 Py_buffer *protos)
3242/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003243{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003244#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003245 PyMem_Free(self->npn_protocols);
3246 self->npn_protocols = PyMem_Malloc(protos->len);
3247 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003248 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003249 memcpy(self->npn_protocols, protos->buf, protos->len);
3250 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003251
3252 /* set both server and client callbacks, because the context can
3253 * be used to create both types of sockets */
3254 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3255 _advertiseNPN_cb,
3256 self);
3257 SSL_CTX_set_next_proto_select_cb(self->ctx,
3258 _selectNPN_cb,
3259 self);
3260
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003261 Py_RETURN_NONE;
3262#else
3263 PyErr_SetString(PyExc_NotImplementedError,
3264 "The NPN extension requires OpenSSL 1.0.1 or later.");
3265 return NULL;
3266#endif
3267}
3268
Miss Islington (bot)96177412018-02-25 04:18:43 -08003269#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003270static int
3271_selectALPN_cb(SSL *s,
3272 const unsigned char **out, unsigned char *outlen,
3273 const unsigned char *client_protocols, unsigned int client_protocols_len,
3274 void *args)
3275{
3276 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003277 return do_protocol_selection(1, (unsigned char **)out, outlen,
3278 ctx->alpn_protocols, ctx->alpn_protocols_len,
3279 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003280}
3281#endif
3282
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003283/*[clinic input]
3284_ssl._SSLContext._set_alpn_protocols
3285 protos: Py_buffer
3286 /
3287[clinic start generated code]*/
3288
Benjamin Petersoncca27322015-01-23 16:35:37 -05003289static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003290_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3291 Py_buffer *protos)
3292/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003293{
Miss Islington (bot)96177412018-02-25 04:18:43 -08003294#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003295 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003296 PyErr_Format(PyExc_OverflowError,
3297 "protocols longer than %d bytes", UINT_MAX);
3298 return NULL;
3299 }
3300
Benjamin Petersoncca27322015-01-23 16:35:37 -05003301 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003302 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003303 if (!self->alpn_protocols)
3304 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003305 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003306 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003307
3308 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3309 return PyErr_NoMemory();
3310 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3311
Benjamin Petersoncca27322015-01-23 16:35:37 -05003312 Py_RETURN_NONE;
3313#else
3314 PyErr_SetString(PyExc_NotImplementedError,
3315 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3316 return NULL;
3317#endif
3318}
3319
Antoine Pitrou152efa22010-05-16 18:19:27 +00003320static PyObject *
3321get_verify_mode(PySSLContext *self, void *c)
3322{
3323 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3324 case SSL_VERIFY_NONE:
3325 return PyLong_FromLong(PY_SSL_CERT_NONE);
3326 case SSL_VERIFY_PEER:
3327 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3328 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3329 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3330 }
3331 PyErr_SetString(PySSLErrorObject,
3332 "invalid return value from SSL_CTX_get_verify_mode");
3333 return NULL;
3334}
3335
3336static int
3337set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3338{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003339 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003340 if (!PyArg_Parse(arg, "i", &n))
3341 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003342 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003343 PyErr_SetString(PyExc_ValueError,
3344 "Cannot set verify_mode to CERT_NONE when "
3345 "check_hostname is enabled.");
3346 return -1;
3347 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003348 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003349}
3350
3351static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003352get_verify_flags(PySSLContext *self, void *c)
3353{
Christian Heimes598894f2016-09-05 23:19:05 +02003354 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003355 unsigned long flags;
3356
Christian Heimes61d478c2018-01-27 15:51:38 +01003357 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003358 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003359 return PyLong_FromUnsignedLong(flags);
3360}
3361
3362static int
3363set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3364{
Christian Heimes598894f2016-09-05 23:19:05 +02003365 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003366 unsigned long new_flags, flags, set, clear;
3367
3368 if (!PyArg_Parse(arg, "k", &new_flags))
3369 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003370 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003371 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003372 clear = flags & ~new_flags;
3373 set = ~flags & new_flags;
3374 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003375 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003376 _setSSLError(NULL, 0, __FILE__, __LINE__);
3377 return -1;
3378 }
3379 }
3380 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003381 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003382 _setSSLError(NULL, 0, __FILE__, __LINE__);
3383 return -1;
3384 }
3385 }
3386 return 0;
3387}
3388
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08003389/* Getter and setter for protocol version */
3390#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3391
3392
3393static int
3394set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3395{
3396 long v;
3397 int result;
3398
3399 if (!PyArg_Parse(arg, "l", &v))
3400 return -1;
3401 if (v > INT_MAX) {
3402 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3403 return -1;
3404 }
3405
3406 switch(self->protocol) {
3407 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3408 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3409 case PY_SSL_VERSION_TLS:
3410 break;
3411 default:
3412 PyErr_SetString(
3413 PyExc_ValueError,
3414 "The context's protocol doesn't support modification of "
3415 "highest and lowest version."
3416 );
3417 return -1;
3418 }
3419
3420 if (what == 0) {
3421 switch(v) {
3422 case PY_PROTO_MINIMUM_SUPPORTED:
3423 v = 0;
3424 break;
3425 case PY_PROTO_MAXIMUM_SUPPORTED:
3426 /* Emulate max for set_min_proto_version */
3427 v = PY_PROTO_MAXIMUM_AVAILABLE;
3428 break;
3429 default:
3430 break;
3431 }
3432 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3433 }
3434 else {
3435 switch(v) {
3436 case PY_PROTO_MAXIMUM_SUPPORTED:
3437 v = 0;
3438 break;
3439 case PY_PROTO_MINIMUM_SUPPORTED:
3440 /* Emulate max for set_min_proto_version */
3441 v = PY_PROTO_MINIMUM_AVAILABLE;
3442 break;
3443 default:
3444 break;
3445 }
3446 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3447 }
3448 if (result == 0) {
3449 PyErr_Format(PyExc_ValueError,
3450 "Unsupported protocol version 0x%x", v);
3451 return -1;
3452 }
3453 return 0;
3454}
3455
3456static PyObject *
3457get_minimum_version(PySSLContext *self, void *c)
3458{
3459 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3460 if (v == 0) {
3461 v = PY_PROTO_MINIMUM_SUPPORTED;
3462 }
3463 return PyLong_FromLong(v);
3464}
3465
3466static int
3467set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3468{
3469 return set_min_max_proto_version(self, arg, 0);
3470}
3471
3472static PyObject *
3473get_maximum_version(PySSLContext *self, void *c)
3474{
3475 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3476 if (v == 0) {
3477 v = PY_PROTO_MAXIMUM_SUPPORTED;
3478 }
3479 return PyLong_FromLong(v);
3480}
3481
3482static int
3483set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3484{
3485 return set_min_max_proto_version(self, arg, 1);
3486}
3487#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3488
Christian Heimes22587792013-11-21 23:56:13 +01003489static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003490get_options(PySSLContext *self, void *c)
3491{
3492 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3493}
3494
3495static int
3496set_options(PySSLContext *self, PyObject *arg, void *c)
3497{
3498 long new_opts, opts, set, clear;
3499 if (!PyArg_Parse(arg, "l", &new_opts))
3500 return -1;
3501 opts = SSL_CTX_get_options(self->ctx);
3502 clear = opts & ~new_opts;
3503 set = ~opts & new_opts;
3504 if (clear) {
3505#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3506 SSL_CTX_clear_options(self->ctx, clear);
3507#else
3508 PyErr_SetString(PyExc_ValueError,
3509 "can't clear options before OpenSSL 0.9.8m");
3510 return -1;
3511#endif
3512 }
3513 if (set)
3514 SSL_CTX_set_options(self->ctx, set);
3515 return 0;
3516}
3517
Christian Heimes1aa9a752013-12-02 02:41:19 +01003518static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003519get_host_flags(PySSLContext *self, void *c)
3520{
3521 return PyLong_FromUnsignedLong(self->hostflags);
3522}
3523
3524static int
3525set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3526{
3527 X509_VERIFY_PARAM *param;
3528 unsigned int new_flags = 0;
3529
3530 if (!PyArg_Parse(arg, "I", &new_flags))
3531 return -1;
3532
3533 param = SSL_CTX_get0_param(self->ctx);
3534 self->hostflags = new_flags;
3535 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3536 return 0;
3537}
3538
3539static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003540get_check_hostname(PySSLContext *self, void *c)
3541{
3542 return PyBool_FromLong(self->check_hostname);
3543}
3544
3545static int
3546set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3547{
3548 int check_hostname;
3549 if (!PyArg_Parse(arg, "p", &check_hostname))
3550 return -1;
3551 if (check_hostname &&
3552 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003553 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3554 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3555 return -1;
3556 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003557 }
3558 self->check_hostname = check_hostname;
3559 return 0;
3560}
3561
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003562static PyObject *
3563get_protocol(PySSLContext *self, void *c) {
3564 return PyLong_FromLong(self->protocol);
3565}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003566
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003567typedef struct {
3568 PyThreadState *thread_state;
3569 PyObject *callable;
3570 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003571 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003572 int error;
3573} _PySSLPasswordInfo;
3574
3575static int
3576_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3577 const char *bad_type_error)
3578{
3579 /* Set the password and size fields of a _PySSLPasswordInfo struct
3580 from a unicode, bytes, or byte array object.
3581 The password field will be dynamically allocated and must be freed
3582 by the caller */
3583 PyObject *password_bytes = NULL;
3584 const char *data = NULL;
3585 Py_ssize_t size;
3586
3587 if (PyUnicode_Check(password)) {
3588 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3589 if (!password_bytes) {
3590 goto error;
3591 }
3592 data = PyBytes_AS_STRING(password_bytes);
3593 size = PyBytes_GET_SIZE(password_bytes);
3594 } else if (PyBytes_Check(password)) {
3595 data = PyBytes_AS_STRING(password);
3596 size = PyBytes_GET_SIZE(password);
3597 } else if (PyByteArray_Check(password)) {
3598 data = PyByteArray_AS_STRING(password);
3599 size = PyByteArray_GET_SIZE(password);
3600 } else {
3601 PyErr_SetString(PyExc_TypeError, bad_type_error);
3602 goto error;
3603 }
3604
Victor Stinner9ee02032013-06-23 15:08:23 +02003605 if (size > (Py_ssize_t)INT_MAX) {
3606 PyErr_Format(PyExc_ValueError,
3607 "password cannot be longer than %d bytes", INT_MAX);
3608 goto error;
3609 }
3610
Victor Stinner11ebff22013-07-07 17:07:52 +02003611 PyMem_Free(pw_info->password);
3612 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003613 if (!pw_info->password) {
3614 PyErr_SetString(PyExc_MemoryError,
3615 "unable to allocate password buffer");
3616 goto error;
3617 }
3618 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003619 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003620
3621 Py_XDECREF(password_bytes);
3622 return 1;
3623
3624error:
3625 Py_XDECREF(password_bytes);
3626 return 0;
3627}
3628
3629static int
3630_password_callback(char *buf, int size, int rwflag, void *userdata)
3631{
3632 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3633 PyObject *fn_ret = NULL;
3634
3635 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3636
3637 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003638 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003639 if (!fn_ret) {
3640 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3641 core python API, so we could use it to add a frame here */
3642 goto error;
3643 }
3644
3645 if (!_pwinfo_set(pw_info, fn_ret,
3646 "password callback must return a string")) {
3647 goto error;
3648 }
3649 Py_CLEAR(fn_ret);
3650 }
3651
3652 if (pw_info->size > size) {
3653 PyErr_Format(PyExc_ValueError,
3654 "password cannot be longer than %d bytes", size);
3655 goto error;
3656 }
3657
3658 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3659 memcpy(buf, pw_info->password, pw_info->size);
3660 return pw_info->size;
3661
3662error:
3663 Py_XDECREF(fn_ret);
3664 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3665 pw_info->error = 1;
3666 return -1;
3667}
3668
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003669/*[clinic input]
3670_ssl._SSLContext.load_cert_chain
3671 certfile: object
3672 keyfile: object = NULL
3673 password: object = NULL
3674
3675[clinic start generated code]*/
3676
Antoine Pitroub5218772010-05-21 09:56:06 +00003677static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003678_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3679 PyObject *keyfile, PyObject *password)
3680/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003681{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003682 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003683 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3684 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003685 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003686 int r;
3687
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003688 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003689 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003690 if (keyfile == Py_None)
3691 keyfile = NULL;
3692 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3693 PyErr_SetString(PyExc_TypeError,
3694 "certfile should be a valid filesystem path");
3695 return NULL;
3696 }
3697 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3698 PyErr_SetString(PyExc_TypeError,
3699 "keyfile should be a valid filesystem path");
3700 goto error;
3701 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003702 if (password && password != Py_None) {
3703 if (PyCallable_Check(password)) {
3704 pw_info.callable = password;
3705 } else if (!_pwinfo_set(&pw_info, password,
3706 "password should be a string or callable")) {
3707 goto error;
3708 }
3709 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3710 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3711 }
3712 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003713 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3714 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003715 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003716 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003717 if (pw_info.error) {
3718 ERR_clear_error();
3719 /* the password callback has already set the error information */
3720 }
3721 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003722 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003723 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003724 }
3725 else {
3726 _setSSLError(NULL, 0, __FILE__, __LINE__);
3727 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003728 goto error;
3729 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003730 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003731 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003732 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3733 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003734 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3735 Py_CLEAR(keyfile_bytes);
3736 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003737 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003738 if (pw_info.error) {
3739 ERR_clear_error();
3740 /* the password callback has already set the error information */
3741 }
3742 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003743 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003744 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003745 }
3746 else {
3747 _setSSLError(NULL, 0, __FILE__, __LINE__);
3748 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003749 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003750 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003751 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003752 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003753 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003754 if (r != 1) {
3755 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003756 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003757 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003758 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3759 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003760 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003761 Py_RETURN_NONE;
3762
3763error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003764 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3765 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003766 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003767 Py_XDECREF(keyfile_bytes);
3768 Py_XDECREF(certfile_bytes);
3769 return NULL;
3770}
3771
Christian Heimesefff7062013-11-21 03:35:02 +01003772/* internal helper function, returns -1 on error
3773 */
3774static int
3775_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3776 int filetype)
3777{
3778 BIO *biobuf = NULL;
3779 X509_STORE *store;
3780 int retval = 0, err, loaded = 0;
3781
3782 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3783
3784 if (len <= 0) {
3785 PyErr_SetString(PyExc_ValueError,
3786 "Empty certificate data");
3787 return -1;
3788 } else if (len > INT_MAX) {
3789 PyErr_SetString(PyExc_OverflowError,
3790 "Certificate data is too long.");
3791 return -1;
3792 }
3793
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003794 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003795 if (biobuf == NULL) {
3796 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3797 return -1;
3798 }
3799
3800 store = SSL_CTX_get_cert_store(self->ctx);
3801 assert(store != NULL);
3802
3803 while (1) {
3804 X509 *cert = NULL;
3805 int r;
3806
3807 if (filetype == SSL_FILETYPE_ASN1) {
3808 cert = d2i_X509_bio(biobuf, NULL);
3809 } else {
3810 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003811 SSL_CTX_get_default_passwd_cb(self->ctx),
3812 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3813 );
Christian Heimesefff7062013-11-21 03:35:02 +01003814 }
3815 if (cert == NULL) {
3816 break;
3817 }
3818 r = X509_STORE_add_cert(store, cert);
3819 X509_free(cert);
3820 if (!r) {
3821 err = ERR_peek_last_error();
3822 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3823 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3824 /* cert already in hash table, not an error */
3825 ERR_clear_error();
3826 } else {
3827 break;
3828 }
3829 }
3830 loaded++;
3831 }
3832
3833 err = ERR_peek_last_error();
3834 if ((filetype == SSL_FILETYPE_ASN1) &&
3835 (loaded > 0) &&
3836 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3837 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3838 /* EOF ASN1 file, not an error */
3839 ERR_clear_error();
3840 retval = 0;
3841 } else if ((filetype == SSL_FILETYPE_PEM) &&
3842 (loaded > 0) &&
3843 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3844 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3845 /* EOF PEM file, not an error */
3846 ERR_clear_error();
3847 retval = 0;
3848 } else {
3849 _setSSLError(NULL, 0, __FILE__, __LINE__);
3850 retval = -1;
3851 }
3852
3853 BIO_free(biobuf);
3854 return retval;
3855}
3856
3857
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003858/*[clinic input]
3859_ssl._SSLContext.load_verify_locations
3860 cafile: object = NULL
3861 capath: object = NULL
3862 cadata: object = NULL
3863
3864[clinic start generated code]*/
3865
Antoine Pitrou152efa22010-05-16 18:19:27 +00003866static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003867_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3868 PyObject *cafile,
3869 PyObject *capath,
3870 PyObject *cadata)
3871/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003872{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003873 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3874 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003875 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003876
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003877 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003878 if (cafile == Py_None)
3879 cafile = NULL;
3880 if (capath == Py_None)
3881 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003882 if (cadata == Py_None)
3883 cadata = NULL;
3884
3885 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003886 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003887 "cafile, capath and cadata cannot be all omitted");
3888 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889 }
3890 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3891 PyErr_SetString(PyExc_TypeError,
3892 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003893 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003894 }
3895 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003896 PyErr_SetString(PyExc_TypeError,
3897 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003898 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003899 }
Christian Heimesefff7062013-11-21 03:35:02 +01003900
3901 /* validata cadata type and load cadata */
3902 if (cadata) {
3903 Py_buffer buf;
3904 PyObject *cadata_ascii = NULL;
3905
3906 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3907 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3908 PyBuffer_Release(&buf);
3909 PyErr_SetString(PyExc_TypeError,
3910 "cadata should be a contiguous buffer with "
3911 "a single dimension");
3912 goto error;
3913 }
3914 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3915 PyBuffer_Release(&buf);
3916 if (r == -1) {
3917 goto error;
3918 }
3919 } else {
3920 PyErr_Clear();
3921 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3922 if (cadata_ascii == NULL) {
3923 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003924 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003925 "bytes-like object");
3926 goto error;
3927 }
3928 r = _add_ca_certs(self,
3929 PyBytes_AS_STRING(cadata_ascii),
3930 PyBytes_GET_SIZE(cadata_ascii),
3931 SSL_FILETYPE_PEM);
3932 Py_DECREF(cadata_ascii);
3933 if (r == -1) {
3934 goto error;
3935 }
3936 }
3937 }
3938
3939 /* load cafile or capath */
3940 if (cafile || capath) {
3941 if (cafile)
3942 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3943 if (capath)
3944 capath_buf = PyBytes_AS_STRING(capath_bytes);
3945 PySSL_BEGIN_ALLOW_THREADS
3946 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3947 PySSL_END_ALLOW_THREADS
3948 if (r != 1) {
3949 ok = 0;
3950 if (errno != 0) {
3951 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003952 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003953 }
3954 else {
3955 _setSSLError(NULL, 0, __FILE__, __LINE__);
3956 }
3957 goto error;
3958 }
3959 }
3960 goto end;
3961
3962 error:
3963 ok = 0;
3964 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003965 Py_XDECREF(cafile_bytes);
3966 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003967 if (ok) {
3968 Py_RETURN_NONE;
3969 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003970 return NULL;
3971 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003972}
3973
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003974/*[clinic input]
3975_ssl._SSLContext.load_dh_params
3976 path as filepath: object
3977 /
3978
3979[clinic start generated code]*/
3980
Antoine Pitrou152efa22010-05-16 18:19:27 +00003981static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003982_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3983/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003984{
3985 FILE *f;
3986 DH *dh;
3987
Victor Stinnerdaf45552013-08-28 00:53:59 +02003988 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003989 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003990 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003991
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003992 errno = 0;
3993 PySSL_BEGIN_ALLOW_THREADS
3994 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003995 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003996 PySSL_END_ALLOW_THREADS
3997 if (dh == NULL) {
3998 if (errno != 0) {
3999 ERR_clear_error();
4000 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
4001 }
4002 else {
4003 _setSSLError(NULL, 0, __FILE__, __LINE__);
4004 }
4005 return NULL;
4006 }
4007 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4008 _setSSLError(NULL, 0, __FILE__, __LINE__);
4009 DH_free(dh);
4010 Py_RETURN_NONE;
4011}
4012
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004013/*[clinic input]
4014_ssl._SSLContext._wrap_socket
4015 sock: object(subclass_of="PySocketModule.Sock_Type")
4016 server_side: int
4017 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004018 *
4019 owner: object = None
4020 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004021
4022[clinic start generated code]*/
4023
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004024static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004025_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004026 int server_side, PyObject *hostname_obj,
4027 PyObject *owner, PyObject *session)
4028/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004029{
Antoine Pitroud5323212010-10-22 18:19:07 +00004030 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004031 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004032
Antoine Pitroud5323212010-10-22 18:19:07 +00004033 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004034 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004035 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004036 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004037 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004038 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004040 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4041 server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004042 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004043 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004044 if (hostname != NULL)
4045 PyMem_Free(hostname);
4046 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004047}
4048
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004049/*[clinic input]
4050_ssl._SSLContext._wrap_bio
4051 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4052 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4053 server_side: int
4054 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004055 *
4056 owner: object = None
4057 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004058
4059[clinic start generated code]*/
4060
Antoine Pitroub0182c82010-10-12 20:09:02 +00004061static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4063 PySSLMemoryBIO *outgoing, int server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004064 PyObject *hostname_obj, PyObject *owner,
4065 PyObject *session)
4066/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004068 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004069 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070
4071 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)2dd885e2018-03-25 04:28:20 -07004072 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004073 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004074 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004075 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004076 }
4077
4078 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08004079 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004080 incoming, outgoing);
4081
4082 PyMem_Free(hostname);
4083 return res;
4084}
4085
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004086/*[clinic input]
4087_ssl._SSLContext.session_stats
4088[clinic start generated code]*/
4089
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004090static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004091_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4092/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004093{
4094 int r;
4095 PyObject *value, *stats = PyDict_New();
4096 if (!stats)
4097 return NULL;
4098
4099#define ADD_STATS(SSL_NAME, KEY_NAME) \
4100 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4101 if (value == NULL) \
4102 goto error; \
4103 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4104 Py_DECREF(value); \
4105 if (r < 0) \
4106 goto error;
4107
4108 ADD_STATS(number, "number");
4109 ADD_STATS(connect, "connect");
4110 ADD_STATS(connect_good, "connect_good");
4111 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4112 ADD_STATS(accept, "accept");
4113 ADD_STATS(accept_good, "accept_good");
4114 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4115 ADD_STATS(accept, "accept");
4116 ADD_STATS(hits, "hits");
4117 ADD_STATS(misses, "misses");
4118 ADD_STATS(timeouts, "timeouts");
4119 ADD_STATS(cache_full, "cache_full");
4120
4121#undef ADD_STATS
4122
4123 return stats;
4124
4125error:
4126 Py_DECREF(stats);
4127 return NULL;
4128}
4129
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130/*[clinic input]
4131_ssl._SSLContext.set_default_verify_paths
4132[clinic start generated code]*/
4133
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004134static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004135_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4136/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004137{
4138 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4139 _setSSLError(NULL, 0, __FILE__, __LINE__);
4140 return NULL;
4141 }
4142 Py_RETURN_NONE;
4143}
4144
Antoine Pitrou501da612011-12-21 09:27:41 +01004145#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004146/*[clinic input]
4147_ssl._SSLContext.set_ecdh_curve
4148 name: object
4149 /
4150
4151[clinic start generated code]*/
4152
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004153static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004154_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4155/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004156{
4157 PyObject *name_bytes;
4158 int nid;
4159 EC_KEY *key;
4160
4161 if (!PyUnicode_FSConverter(name, &name_bytes))
4162 return NULL;
4163 assert(PyBytes_Check(name_bytes));
4164 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4165 Py_DECREF(name_bytes);
4166 if (nid == 0) {
4167 PyErr_Format(PyExc_ValueError,
4168 "unknown elliptic curve name %R", name);
4169 return NULL;
4170 }
4171 key = EC_KEY_new_by_curve_name(nid);
4172 if (key == NULL) {
4173 _setSSLError(NULL, 0, __FILE__, __LINE__);
4174 return NULL;
4175 }
4176 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4177 EC_KEY_free(key);
4178 Py_RETURN_NONE;
4179}
Antoine Pitrou501da612011-12-21 09:27:41 +01004180#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004181
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004182#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004183static int
4184_servername_callback(SSL *s, int *al, void *args)
4185{
4186 int ret;
4187 PySSLContext *ssl_ctx = (PySSLContext *) args;
4188 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004189 PyObject *result;
4190 /* The high-level ssl.SSLSocket object */
4191 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004192 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004193 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004194
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004195 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004196 /* remove race condition in this the call back while if removing the
4197 * callback is in progress */
4198 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004199 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004200 }
4201
4202 ssl = SSL_get_app_data(s);
4203 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004204
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004205 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004206 * SSL connection and that has a .context attribute that can be changed to
4207 * identify the requested hostname. Since the official API is the Python
4208 * level API we want to pass the callback a Python level object rather than
4209 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4210 * SSLObject) that will be passed. Otherwise if there's a socket then that
4211 * will be passed. If both do not exist only then the C-level object is
4212 * passed. */
4213 if (ssl->owner)
4214 ssl_socket = PyWeakref_GetObject(ssl->owner);
4215 else if (ssl->Socket)
4216 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4217 else
4218 ssl_socket = (PyObject *) ssl;
4219
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004220 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004221 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004222 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004223
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004224 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004225 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004226 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004227 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004228 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004229 PyObject *servername_bytes;
4230 PyObject *servername_str;
4231
4232 servername_bytes = PyBytes_FromString(servername);
4233 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004234 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4235 goto error;
4236 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004237 /* server_hostname was encoded to an A-label by our caller; put it
4238 * back into a str object, but still as an A-label (bpo-28414)
4239 */
4240 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4241 Py_DECREF(servername_bytes);
4242 if (servername_str == NULL) {
4243 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004244 goto error;
4245 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004246 result = PyObject_CallFunctionObjArgs(
4247 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4248 ssl_ctx, NULL);
4249 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004250 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004251 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004252
4253 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004254 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004255 *al = SSL_AD_HANDSHAKE_FAILURE;
4256 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4257 }
4258 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004259 /* Result may be None, a SSLContext or an integer
4260 * None and SSLContext are OK, integer or other values are an error.
4261 */
4262 if (result == Py_None) {
4263 ret = SSL_TLSEXT_ERR_OK;
4264 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004265 *al = (int) PyLong_AsLong(result);
4266 if (PyErr_Occurred()) {
4267 PyErr_WriteUnraisable(result);
4268 *al = SSL_AD_INTERNAL_ERROR;
4269 }
4270 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4271 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004272 Py_DECREF(result);
4273 }
4274
4275 PyGILState_Release(gstate);
4276 return ret;
4277
4278error:
4279 Py_DECREF(ssl_socket);
4280 *al = SSL_AD_INTERNAL_ERROR;
4281 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4282 PyGILState_Release(gstate);
4283 return ret;
4284}
Antoine Pitroua5963382013-03-30 16:39:00 +01004285#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004286
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004287static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004288get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004289{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004290 PyObject *cb = self->set_sni_cb;
4291 if (cb == NULL) {
4292 Py_RETURN_NONE;
4293 }
4294 Py_INCREF(cb);
4295 return cb;
4296}
4297
4298static int
4299set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4300{
4301 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4302 PyErr_SetString(PyExc_ValueError,
4303 "sni_callback cannot be set on TLS_CLIENT context");
4304 return -1;
4305 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004306#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004307 Py_CLEAR(self->set_sni_cb);
4308 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004309 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4310 }
4311 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004312 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004313 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4314 PyErr_SetString(PyExc_TypeError,
4315 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004316 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004317 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004318 Py_INCREF(arg);
4319 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004320 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4321 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4322 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004323 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004324#else
4325 PyErr_SetString(PyExc_NotImplementedError,
4326 "The TLS extension servername callback, "
4327 "SSL_CTX_set_tlsext_servername_callback, "
4328 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004329 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004330#endif
4331}
4332
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004333PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4334"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4335\n\
4336If the argument is None then the callback is disabled. The method is called\n\
4337with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4338See RFC 6066 for details of the SNI extension.");
4339
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004340/*[clinic input]
4341_ssl._SSLContext.cert_store_stats
4342
4343Returns quantities of loaded X.509 certificates.
4344
4345X.509 certificates with a CA extension and certificate revocation lists
4346inside the context's cert store.
4347
4348NOTE: Certificates in a capath directory aren't loaded unless they have
4349been used at least once.
4350[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004351
4352static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004353_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4354/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004355{
4356 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004357 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004358 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004359 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004360
4361 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004362 objs = X509_STORE_get0_objects(store);
4363 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4364 obj = sk_X509_OBJECT_value(objs, i);
4365 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004366 case X509_LU_X509:
4367 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004368 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004369 ca++;
4370 }
4371 break;
4372 case X509_LU_CRL:
4373 crl++;
4374 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004375 default:
4376 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4377 * As far as I can tell they are internal states and never
4378 * stored in a cert store */
4379 break;
4380 }
4381 }
4382 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4383 "x509_ca", ca);
4384}
4385
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004386/*[clinic input]
4387_ssl._SSLContext.get_ca_certs
4388 binary_form: bool = False
4389
4390Returns a list of dicts with information of loaded CA certs.
4391
4392If the optional argument is True, returns a DER-encoded copy of the CA
4393certificate.
4394
4395NOTE: Certificates in a capath directory aren't loaded unless they have
4396been used at least once.
4397[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004398
4399static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004400_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4401/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004402{
4403 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004404 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004405 PyObject *ci = NULL, *rlist = NULL;
4406 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004407
4408 if ((rlist = PyList_New(0)) == NULL) {
4409 return NULL;
4410 }
4411
4412 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004413 objs = X509_STORE_get0_objects(store);
4414 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004415 X509_OBJECT *obj;
4416 X509 *cert;
4417
Christian Heimes598894f2016-09-05 23:19:05 +02004418 obj = sk_X509_OBJECT_value(objs, i);
4419 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004420 /* not a x509 cert */
4421 continue;
4422 }
4423 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004424 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004425 if (!X509_check_ca(cert)) {
4426 continue;
4427 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004428 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004429 ci = _certificate_to_der(cert);
4430 } else {
4431 ci = _decode_certificate(cert);
4432 }
4433 if (ci == NULL) {
4434 goto error;
4435 }
4436 if (PyList_Append(rlist, ci) == -1) {
4437 goto error;
4438 }
4439 Py_CLEAR(ci);
4440 }
4441 return rlist;
4442
4443 error:
4444 Py_XDECREF(ci);
4445 Py_XDECREF(rlist);
4446 return NULL;
4447}
4448
4449
Antoine Pitrou152efa22010-05-16 18:19:27 +00004450static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004451 {"check_hostname", (getter) get_check_hostname,
4452 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004453 {"_host_flags", (getter) get_host_flags,
4454 (setter) set_host_flags, NULL},
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004455#if SSL_CTRL_GET_MAX_PROTO_VERSION
4456 {"minimum_version", (getter) get_minimum_version,
4457 (setter) set_minimum_version, NULL},
4458 {"maximum_version", (getter) get_maximum_version,
4459 (setter) set_maximum_version, NULL},
4460#endif
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004461 {"sni_callback", (getter) get_sni_callback,
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08004462 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004463 {"options", (getter) get_options,
4464 (setter) set_options, NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004465 {"protocol", (getter) get_protocol,
4466 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004467 {"verify_flags", (getter) get_verify_flags,
4468 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004469 {"verify_mode", (getter) get_verify_mode,
4470 (setter) set_verify_mode, NULL},
4471 {NULL}, /* sentinel */
4472};
4473
4474static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004475 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4476 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4477 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4478 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4479 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4480 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4481 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4482 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4483 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4484 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4485 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004486 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4487 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004488 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004489 {NULL, NULL} /* sentinel */
4490};
4491
4492static PyTypeObject PySSLContext_Type = {
4493 PyVarObject_HEAD_INIT(NULL, 0)
4494 "_ssl._SSLContext", /*tp_name*/
4495 sizeof(PySSLContext), /*tp_basicsize*/
4496 0, /*tp_itemsize*/
4497 (destructor)context_dealloc, /*tp_dealloc*/
4498 0, /*tp_print*/
4499 0, /*tp_getattr*/
4500 0, /*tp_setattr*/
4501 0, /*tp_reserved*/
4502 0, /*tp_repr*/
4503 0, /*tp_as_number*/
4504 0, /*tp_as_sequence*/
4505 0, /*tp_as_mapping*/
4506 0, /*tp_hash*/
4507 0, /*tp_call*/
4508 0, /*tp_str*/
4509 0, /*tp_getattro*/
4510 0, /*tp_setattro*/
4511 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004512 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004513 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004514 (traverseproc) context_traverse, /*tp_traverse*/
4515 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004516 0, /*tp_richcompare*/
4517 0, /*tp_weaklistoffset*/
4518 0, /*tp_iter*/
4519 0, /*tp_iternext*/
4520 context_methods, /*tp_methods*/
4521 0, /*tp_members*/
4522 context_getsetlist, /*tp_getset*/
4523 0, /*tp_base*/
4524 0, /*tp_dict*/
4525 0, /*tp_descr_get*/
4526 0, /*tp_descr_set*/
4527 0, /*tp_dictoffset*/
4528 0, /*tp_init*/
4529 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004530 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004531};
4532
4533
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004534/*
4535 * MemoryBIO objects
4536 */
4537
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004538/*[clinic input]
4539@classmethod
4540_ssl.MemoryBIO.__new__
4541
4542[clinic start generated code]*/
4543
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004544static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004545_ssl_MemoryBIO_impl(PyTypeObject *type)
4546/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004547{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004548 BIO *bio;
4549 PySSLMemoryBIO *self;
4550
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004551 bio = BIO_new(BIO_s_mem());
4552 if (bio == NULL) {
4553 PyErr_SetString(PySSLErrorObject,
4554 "failed to allocate BIO");
4555 return NULL;
4556 }
4557 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4558 * just that no data is currently available. The SSL routines should retry
4559 * the read, which we can achieve by calling BIO_set_retry_read(). */
4560 BIO_set_retry_read(bio);
4561 BIO_set_mem_eof_return(bio, -1);
4562
4563 assert(type != NULL && type->tp_alloc != NULL);
4564 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4565 if (self == NULL) {
4566 BIO_free(bio);
4567 return NULL;
4568 }
4569 self->bio = bio;
4570 self->eof_written = 0;
4571
4572 return (PyObject *) self;
4573}
4574
4575static void
4576memory_bio_dealloc(PySSLMemoryBIO *self)
4577{
4578 BIO_free(self->bio);
4579 Py_TYPE(self)->tp_free(self);
4580}
4581
4582static PyObject *
4583memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4584{
Segev Finer5cff6372017-07-27 01:19:17 +03004585 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004586}
4587
4588PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4589"The number of bytes pending in the memory BIO.");
4590
4591static PyObject *
4592memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4593{
4594 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4595 && self->eof_written);
4596}
4597
4598PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4599"Whether the memory BIO is at EOF.");
4600
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004601/*[clinic input]
4602_ssl.MemoryBIO.read
4603 size as len: int = -1
4604 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004605
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004606Read up to size bytes from the memory BIO.
4607
4608If size is not specified, read the entire buffer.
4609If the return value is an empty bytes instance, this means either
4610EOF or that no data is available. Use the "eof" property to
4611distinguish between the two.
4612[clinic start generated code]*/
4613
4614static PyObject *
4615_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4616/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4617{
4618 int avail, nbytes;
4619 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004620
Segev Finer5cff6372017-07-27 01:19:17 +03004621 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004622 if ((len < 0) || (len > avail))
4623 len = avail;
4624
4625 result = PyBytes_FromStringAndSize(NULL, len);
4626 if ((result == NULL) || (len == 0))
4627 return result;
4628
4629 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4630 /* There should never be any short reads but check anyway. */
4631 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4632 Py_DECREF(result);
4633 return NULL;
4634 }
4635
4636 return result;
4637}
4638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004639/*[clinic input]
4640_ssl.MemoryBIO.write
4641 b: Py_buffer
4642 /
4643
4644Writes the bytes b into the memory BIO.
4645
4646Returns the number of bytes written.
4647[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004648
4649static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004650_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4651/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004652{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004653 int nbytes;
4654
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004655 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004656 PyErr_Format(PyExc_OverflowError,
4657 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004658 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004659 }
4660
4661 if (self->eof_written) {
4662 PyErr_SetString(PySSLErrorObject,
4663 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004665 }
4666
Segev Finer5cff6372017-07-27 01:19:17 +03004667 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004668 if (nbytes < 0) {
4669 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004670 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004671 }
4672
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004673 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004674}
4675
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004676/*[clinic input]
4677_ssl.MemoryBIO.write_eof
4678
4679Write an EOF marker to the memory BIO.
4680
4681When all data has been read, the "eof" property will be True.
4682[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004683
4684static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004685_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4686/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004687{
4688 self->eof_written = 1;
4689 /* After an EOF is written, a zero return from read() should be a real EOF
4690 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4691 BIO_clear_retry_flags(self->bio);
4692 BIO_set_mem_eof_return(self->bio, 0);
4693
4694 Py_RETURN_NONE;
4695}
4696
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004697static PyGetSetDef memory_bio_getsetlist[] = {
4698 {"pending", (getter) memory_bio_get_pending, NULL,
4699 PySSL_memory_bio_pending_doc},
4700 {"eof", (getter) memory_bio_get_eof, NULL,
4701 PySSL_memory_bio_eof_doc},
4702 {NULL}, /* sentinel */
4703};
4704
4705static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004706 _SSL_MEMORYBIO_READ_METHODDEF
4707 _SSL_MEMORYBIO_WRITE_METHODDEF
4708 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004709 {NULL, NULL} /* sentinel */
4710};
4711
4712static PyTypeObject PySSLMemoryBIO_Type = {
4713 PyVarObject_HEAD_INIT(NULL, 0)
4714 "_ssl.MemoryBIO", /*tp_name*/
4715 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4716 0, /*tp_itemsize*/
4717 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4718 0, /*tp_print*/
4719 0, /*tp_getattr*/
4720 0, /*tp_setattr*/
4721 0, /*tp_reserved*/
4722 0, /*tp_repr*/
4723 0, /*tp_as_number*/
4724 0, /*tp_as_sequence*/
4725 0, /*tp_as_mapping*/
4726 0, /*tp_hash*/
4727 0, /*tp_call*/
4728 0, /*tp_str*/
4729 0, /*tp_getattro*/
4730 0, /*tp_setattro*/
4731 0, /*tp_as_buffer*/
4732 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4733 0, /*tp_doc*/
4734 0, /*tp_traverse*/
4735 0, /*tp_clear*/
4736 0, /*tp_richcompare*/
4737 0, /*tp_weaklistoffset*/
4738 0, /*tp_iter*/
4739 0, /*tp_iternext*/
4740 memory_bio_methods, /*tp_methods*/
4741 0, /*tp_members*/
4742 memory_bio_getsetlist, /*tp_getset*/
4743 0, /*tp_base*/
4744 0, /*tp_dict*/
4745 0, /*tp_descr_get*/
4746 0, /*tp_descr_set*/
4747 0, /*tp_dictoffset*/
4748 0, /*tp_init*/
4749 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004750 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004751};
4752
Antoine Pitrou152efa22010-05-16 18:19:27 +00004753
Christian Heimes99a65702016-09-10 23:44:53 +02004754/*
4755 * SSL Session object
4756 */
4757
4758static void
4759PySSLSession_dealloc(PySSLSession *self)
4760{
INADA Naokia6296d32017-08-24 14:55:17 +09004761 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004762 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004763 Py_XDECREF(self->ctx);
4764 if (self->session != NULL) {
4765 SSL_SESSION_free(self->session);
4766 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004767 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004768}
4769
4770static PyObject *
4771PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4772{
4773 int result;
4774
4775 if (left == NULL || right == NULL) {
4776 PyErr_BadInternalCall();
4777 return NULL;
4778 }
4779
4780 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4781 Py_RETURN_NOTIMPLEMENTED;
4782 }
4783
4784 if (left == right) {
4785 result = 0;
4786 } else {
4787 const unsigned char *left_id, *right_id;
4788 unsigned int left_len, right_len;
4789 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4790 &left_len);
4791 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4792 &right_len);
4793 if (left_len == right_len) {
4794 result = memcmp(left_id, right_id, left_len);
4795 } else {
4796 result = 1;
4797 }
4798 }
4799
4800 switch (op) {
4801 case Py_EQ:
4802 if (result == 0) {
4803 Py_RETURN_TRUE;
4804 } else {
4805 Py_RETURN_FALSE;
4806 }
4807 break;
4808 case Py_NE:
4809 if (result != 0) {
4810 Py_RETURN_TRUE;
4811 } else {
4812 Py_RETURN_FALSE;
4813 }
4814 break;
4815 case Py_LT:
4816 case Py_LE:
4817 case Py_GT:
4818 case Py_GE:
4819 Py_RETURN_NOTIMPLEMENTED;
4820 break;
4821 default:
4822 PyErr_BadArgument();
4823 return NULL;
4824 }
4825}
4826
4827static int
4828PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4829{
4830 Py_VISIT(self->ctx);
4831 return 0;
4832}
4833
4834static int
4835PySSLSession_clear(PySSLSession *self)
4836{
4837 Py_CLEAR(self->ctx);
4838 return 0;
4839}
4840
4841
4842static PyObject *
4843PySSLSession_get_time(PySSLSession *self, void *closure) {
4844 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4845}
4846
4847PyDoc_STRVAR(PySSLSession_get_time_doc,
4848"Session creation time (seconds since epoch).");
4849
4850
4851static PyObject *
4852PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4853 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4854}
4855
4856PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4857"Session timeout (delta in seconds).");
4858
4859
4860static PyObject *
4861PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4862 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4863 return PyLong_FromUnsignedLong(hint);
4864}
4865
4866PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4867"Ticket life time hint.");
4868
4869
4870static PyObject *
4871PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4872 const unsigned char *id;
4873 unsigned int len;
4874 id = SSL_SESSION_get_id(self->session, &len);
4875 return PyBytes_FromStringAndSize((const char *)id, len);
4876}
4877
4878PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4879"Session id");
4880
4881
4882static PyObject *
4883PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4884 if (SSL_SESSION_has_ticket(self->session)) {
4885 Py_RETURN_TRUE;
4886 } else {
4887 Py_RETURN_FALSE;
4888 }
4889}
4890
4891PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4892"Does the session contain a ticket?");
4893
4894
4895static PyGetSetDef PySSLSession_getsetlist[] = {
4896 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4897 PySSLSession_get_has_ticket_doc},
4898 {"id", (getter) PySSLSession_get_session_id, NULL,
4899 PySSLSession_get_session_id_doc},
4900 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4901 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4902 {"time", (getter) PySSLSession_get_time, NULL,
4903 PySSLSession_get_time_doc},
4904 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4905 PySSLSession_get_timeout_doc},
4906 {NULL}, /* sentinel */
4907};
4908
4909static PyTypeObject PySSLSession_Type = {
4910 PyVarObject_HEAD_INIT(NULL, 0)
4911 "_ssl.Session", /*tp_name*/
4912 sizeof(PySSLSession), /*tp_basicsize*/
4913 0, /*tp_itemsize*/
4914 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4915 0, /*tp_print*/
4916 0, /*tp_getattr*/
4917 0, /*tp_setattr*/
4918 0, /*tp_reserved*/
4919 0, /*tp_repr*/
4920 0, /*tp_as_number*/
4921 0, /*tp_as_sequence*/
4922 0, /*tp_as_mapping*/
4923 0, /*tp_hash*/
4924 0, /*tp_call*/
4925 0, /*tp_str*/
4926 0, /*tp_getattro*/
4927 0, /*tp_setattro*/
4928 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004929 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004930 0, /*tp_doc*/
4931 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4932 (inquiry)PySSLSession_clear, /*tp_clear*/
4933 PySSLSession_richcompare, /*tp_richcompare*/
4934 0, /*tp_weaklistoffset*/
4935 0, /*tp_iter*/
4936 0, /*tp_iternext*/
4937 0, /*tp_methods*/
4938 0, /*tp_members*/
4939 PySSLSession_getsetlist, /*tp_getset*/
4940};
4941
4942
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004943/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004944/*[clinic input]
4945_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004946 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004947 entropy: double
4948 /
4949
4950Mix string into the OpenSSL PRNG state.
4951
4952entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304953string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004954[clinic start generated code]*/
4955
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004956static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004957_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004958/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004959{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004960 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004961 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004962
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004963 buf = (const char *)view->buf;
4964 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004965 do {
4966 written = Py_MIN(len, INT_MAX);
4967 RAND_add(buf, (int)written, entropy);
4968 buf += written;
4969 len -= written;
4970 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004971 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004972}
4973
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004974static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004975PySSL_RAND(int len, int pseudo)
4976{
4977 int ok;
4978 PyObject *bytes;
4979 unsigned long err;
4980 const char *errstr;
4981 PyObject *v;
4982
Victor Stinner1e81a392013-12-19 16:47:04 +01004983 if (len < 0) {
4984 PyErr_SetString(PyExc_ValueError, "num must be positive");
4985 return NULL;
4986 }
4987
Victor Stinner99c8b162011-05-24 12:05:19 +02004988 bytes = PyBytes_FromStringAndSize(NULL, len);
4989 if (bytes == NULL)
4990 return NULL;
4991 if (pseudo) {
4992 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4993 if (ok == 0 || ok == 1)
4994 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4995 }
4996 else {
4997 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4998 if (ok == 1)
4999 return bytes;
5000 }
5001 Py_DECREF(bytes);
5002
5003 err = ERR_get_error();
5004 errstr = ERR_reason_error_string(err);
5005 v = Py_BuildValue("(ks)", err, errstr);
5006 if (v != NULL) {
5007 PyErr_SetObject(PySSLErrorObject, v);
5008 Py_DECREF(v);
5009 }
5010 return NULL;
5011}
5012
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005013/*[clinic input]
5014_ssl.RAND_bytes
5015 n: int
5016 /
5017
5018Generate n cryptographically strong pseudo-random bytes.
5019[clinic start generated code]*/
5020
Victor Stinner99c8b162011-05-24 12:05:19 +02005021static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005022_ssl_RAND_bytes_impl(PyObject *module, int n)
5023/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005024{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005025 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005026}
5027
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005028/*[clinic input]
5029_ssl.RAND_pseudo_bytes
5030 n: int
5031 /
5032
5033Generate n pseudo-random bytes.
5034
5035Return a pair (bytes, is_cryptographic). is_cryptographic is True
5036if the bytes generated are cryptographically strong.
5037[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005038
5039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005040_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5041/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005042{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005043 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005044}
5045
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005046/*[clinic input]
5047_ssl.RAND_status
5048
5049Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5050
5051It is necessary to seed the PRNG with RAND_add() on some platforms before
5052using the ssl() function.
5053[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005054
5055static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005056_ssl_RAND_status_impl(PyObject *module)
5057/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005058{
Christian Heimes217cfd12007-12-02 14:31:20 +00005059 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005060}
5061
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005062#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005063/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005064/*[clinic input]
5065_ssl.RAND_egd
5066 path: object(converter="PyUnicode_FSConverter")
5067 /
5068
5069Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5070
5071Returns number of bytes read. Raises SSLError if connection to EGD
5072fails or if it does not provide enough data to seed PRNG.
5073[clinic start generated code]*/
5074
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005075static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005076_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5077/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005078{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005079 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005080 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005081 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005082 PyErr_SetString(PySSLErrorObject,
5083 "EGD connection failed or EGD did not return "
5084 "enough data to seed the PRNG");
5085 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005086 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005087 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005088}
Christian Heimesa5d07652016-09-24 10:48:05 +02005089/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005090#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005091
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005092
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005093
5094/*[clinic input]
5095_ssl.get_default_verify_paths
5096
5097Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5098
5099The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5100[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005101
5102static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005103_ssl_get_default_verify_paths_impl(PyObject *module)
5104/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005105{
5106 PyObject *ofile_env = NULL;
5107 PyObject *ofile = NULL;
5108 PyObject *odir_env = NULL;
5109 PyObject *odir = NULL;
5110
Benjamin Petersond113c962015-07-18 10:59:13 -07005111#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005112 const char *tmp = (info); \
5113 target = NULL; \
5114 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5115 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5116 target = PyBytes_FromString(tmp); } \
5117 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005118 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005119
Benjamin Petersond113c962015-07-18 10:59:13 -07005120 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5121 CONVERT(X509_get_default_cert_file(), ofile);
5122 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5123 CONVERT(X509_get_default_cert_dir(), odir);
5124#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005125
Christian Heimes200bb1b2013-06-14 15:14:29 +02005126 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005127
5128 error:
5129 Py_XDECREF(ofile_env);
5130 Py_XDECREF(ofile);
5131 Py_XDECREF(odir_env);
5132 Py_XDECREF(odir);
5133 return NULL;
5134}
5135
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005136static PyObject*
5137asn1obj2py(ASN1_OBJECT *obj)
5138{
5139 int nid;
5140 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005141
5142 nid = OBJ_obj2nid(obj);
5143 if (nid == NID_undef) {
5144 PyErr_Format(PyExc_ValueError, "Unknown object");
5145 return NULL;
5146 }
5147 sn = OBJ_nid2sn(nid);
5148 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005149 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005150}
5151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005152/*[clinic input]
5153_ssl.txt2obj
5154 txt: str
5155 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005156
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005157Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5158
5159By default objects are looked up by OID. With name=True short and
5160long name are also matched.
5161[clinic start generated code]*/
5162
5163static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005164_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5165/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005166{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005167 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005168 ASN1_OBJECT *obj;
5169
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005170 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5171 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005172 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005173 return NULL;
5174 }
5175 result = asn1obj2py(obj);
5176 ASN1_OBJECT_free(obj);
5177 return result;
5178}
5179
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005180/*[clinic input]
5181_ssl.nid2obj
5182 nid: int
5183 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005184
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005185Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5186[clinic start generated code]*/
5187
5188static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005189_ssl_nid2obj_impl(PyObject *module, int nid)
5190/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005191{
5192 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005193 ASN1_OBJECT *obj;
5194
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005195 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005196 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005197 return NULL;
5198 }
5199 obj = OBJ_nid2obj(nid);
5200 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005201 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005202 return NULL;
5203 }
5204 result = asn1obj2py(obj);
5205 ASN1_OBJECT_free(obj);
5206 return result;
5207}
5208
Christian Heimes46bebee2013-06-09 19:03:31 +02005209#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005210
5211static PyObject*
5212certEncodingType(DWORD encodingType)
5213{
5214 static PyObject *x509_asn = NULL;
5215 static PyObject *pkcs_7_asn = NULL;
5216
5217 if (x509_asn == NULL) {
5218 x509_asn = PyUnicode_InternFromString("x509_asn");
5219 if (x509_asn == NULL)
5220 return NULL;
5221 }
5222 if (pkcs_7_asn == NULL) {
5223 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5224 if (pkcs_7_asn == NULL)
5225 return NULL;
5226 }
5227 switch(encodingType) {
5228 case X509_ASN_ENCODING:
5229 Py_INCREF(x509_asn);
5230 return x509_asn;
5231 case PKCS_7_ASN_ENCODING:
5232 Py_INCREF(pkcs_7_asn);
5233 return pkcs_7_asn;
5234 default:
5235 return PyLong_FromLong(encodingType);
5236 }
5237}
5238
5239static PyObject*
5240parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5241{
5242 CERT_ENHKEY_USAGE *usage;
5243 DWORD size, error, i;
5244 PyObject *retval;
5245
5246 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5247 error = GetLastError();
5248 if (error == CRYPT_E_NOT_FOUND) {
5249 Py_RETURN_TRUE;
5250 }
5251 return PyErr_SetFromWindowsErr(error);
5252 }
5253
5254 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5255 if (usage == NULL) {
5256 return PyErr_NoMemory();
5257 }
5258
5259 /* Now get the actual enhanced usage property */
5260 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5261 PyMem_Free(usage);
5262 error = GetLastError();
5263 if (error == CRYPT_E_NOT_FOUND) {
5264 Py_RETURN_TRUE;
5265 }
5266 return PyErr_SetFromWindowsErr(error);
5267 }
5268 retval = PySet_New(NULL);
5269 if (retval == NULL) {
5270 goto error;
5271 }
5272 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5273 if (usage->rgpszUsageIdentifier[i]) {
5274 PyObject *oid;
5275 int err;
5276 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5277 if (oid == NULL) {
5278 Py_CLEAR(retval);
5279 goto error;
5280 }
5281 err = PySet_Add(retval, oid);
5282 Py_DECREF(oid);
5283 if (err == -1) {
5284 Py_CLEAR(retval);
5285 goto error;
5286 }
5287 }
5288 }
5289 error:
5290 PyMem_Free(usage);
5291 return retval;
5292}
5293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005294/*[clinic input]
5295_ssl.enum_certificates
5296 store_name: str
5297
5298Retrieve certificates from Windows' cert store.
5299
5300store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5301more cert storages, too. The function returns a list of (bytes,
5302encoding_type, trust) tuples. The encoding_type flag can be interpreted
5303with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5304a set of OIDs or the boolean True.
5305[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005306
Christian Heimes46bebee2013-06-09 19:03:31 +02005307static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005308_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5309/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005310{
Christian Heimes46bebee2013-06-09 19:03:31 +02005311 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005312 PCCERT_CONTEXT pCertCtx = NULL;
5313 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005314 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005315
Christian Heimes44109d72013-11-22 01:51:30 +01005316 result = PyList_New(0);
5317 if (result == NULL) {
5318 return NULL;
5319 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005320 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5321 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5322 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005323 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005324 Py_DECREF(result);
5325 return PyErr_SetFromWindowsErr(GetLastError());
5326 }
5327
Christian Heimes44109d72013-11-22 01:51:30 +01005328 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5329 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5330 pCertCtx->cbCertEncoded);
5331 if (!cert) {
5332 Py_CLEAR(result);
5333 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005334 }
Christian Heimes44109d72013-11-22 01:51:30 +01005335 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5336 Py_CLEAR(result);
5337 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005338 }
Christian Heimes44109d72013-11-22 01:51:30 +01005339 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5340 if (keyusage == Py_True) {
5341 Py_DECREF(keyusage);
5342 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005343 }
Christian Heimes44109d72013-11-22 01:51:30 +01005344 if (keyusage == NULL) {
5345 Py_CLEAR(result);
5346 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005347 }
Christian Heimes44109d72013-11-22 01:51:30 +01005348 if ((tup = PyTuple_New(3)) == NULL) {
5349 Py_CLEAR(result);
5350 break;
5351 }
5352 PyTuple_SET_ITEM(tup, 0, cert);
5353 cert = NULL;
5354 PyTuple_SET_ITEM(tup, 1, enc);
5355 enc = NULL;
5356 PyTuple_SET_ITEM(tup, 2, keyusage);
5357 keyusage = NULL;
5358 if (PyList_Append(result, tup) < 0) {
5359 Py_CLEAR(result);
5360 break;
5361 }
5362 Py_CLEAR(tup);
5363 }
5364 if (pCertCtx) {
5365 /* loop ended with an error, need to clean up context manually */
5366 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005367 }
5368
5369 /* In error cases cert, enc and tup may not be NULL */
5370 Py_XDECREF(cert);
5371 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005372 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005373 Py_XDECREF(tup);
5374
5375 if (!CertCloseStore(hStore, 0)) {
5376 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005377 Py_XDECREF(result);
5378 return PyErr_SetFromWindowsErr(GetLastError());
5379 }
5380 return result;
5381}
5382
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005383/*[clinic input]
5384_ssl.enum_crls
5385 store_name: str
5386
5387Retrieve CRLs from Windows' cert store.
5388
5389store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5390more cert storages, too. The function returns a list of (bytes,
5391encoding_type) tuples. The encoding_type flag can be interpreted with
5392X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5393[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005394
5395static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005396_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5397/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005398{
Christian Heimes44109d72013-11-22 01:51:30 +01005399 HCERTSTORE hStore = NULL;
5400 PCCRL_CONTEXT pCrlCtx = NULL;
5401 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5402 PyObject *result = NULL;
5403
Christian Heimes44109d72013-11-22 01:51:30 +01005404 result = PyList_New(0);
5405 if (result == NULL) {
5406 return NULL;
5407 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005408 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5409 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5410 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005411 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005412 Py_DECREF(result);
5413 return PyErr_SetFromWindowsErr(GetLastError());
5414 }
Christian Heimes44109d72013-11-22 01:51:30 +01005415
5416 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5417 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5418 pCrlCtx->cbCrlEncoded);
5419 if (!crl) {
5420 Py_CLEAR(result);
5421 break;
5422 }
5423 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5424 Py_CLEAR(result);
5425 break;
5426 }
5427 if ((tup = PyTuple_New(2)) == NULL) {
5428 Py_CLEAR(result);
5429 break;
5430 }
5431 PyTuple_SET_ITEM(tup, 0, crl);
5432 crl = NULL;
5433 PyTuple_SET_ITEM(tup, 1, enc);
5434 enc = NULL;
5435
5436 if (PyList_Append(result, tup) < 0) {
5437 Py_CLEAR(result);
5438 break;
5439 }
5440 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005441 }
Christian Heimes44109d72013-11-22 01:51:30 +01005442 if (pCrlCtx) {
5443 /* loop ended with an error, need to clean up context manually */
5444 CertFreeCRLContext(pCrlCtx);
5445 }
5446
5447 /* In error cases cert, enc and tup may not be NULL */
5448 Py_XDECREF(crl);
5449 Py_XDECREF(enc);
5450 Py_XDECREF(tup);
5451
5452 if (!CertCloseStore(hStore, 0)) {
5453 /* This error case might shadow another exception.*/
5454 Py_XDECREF(result);
5455 return PyErr_SetFromWindowsErr(GetLastError());
5456 }
5457 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005458}
Christian Heimes44109d72013-11-22 01:51:30 +01005459
5460#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005461
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005462/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005463static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005464 _SSL__TEST_DECODE_CERT_METHODDEF
5465 _SSL_RAND_ADD_METHODDEF
5466 _SSL_RAND_BYTES_METHODDEF
5467 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5468 _SSL_RAND_EGD_METHODDEF
5469 _SSL_RAND_STATUS_METHODDEF
5470 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5471 _SSL_ENUM_CERTIFICATES_METHODDEF
5472 _SSL_ENUM_CRLS_METHODDEF
5473 _SSL_TXT2OBJ_METHODDEF
5474 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005475 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005476};
5477
5478
Christian Heimes598894f2016-09-05 23:19:05 +02005479#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005480
5481/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005482 * of the Python C thread library
5483 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5484 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005485
5486static PyThread_type_lock *_ssl_locks = NULL;
5487
Christian Heimes4d98ca92013-08-19 17:36:29 +02005488#if OPENSSL_VERSION_NUMBER >= 0x10000000
5489/* use new CRYPTO_THREADID API. */
5490static void
5491_ssl_threadid_callback(CRYPTO_THREADID *id)
5492{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005493 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005494}
5495#else
5496/* deprecated CRYPTO_set_id_callback() API. */
5497static unsigned long
5498_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005499 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005500}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005501#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005502
Bill Janssen6e027db2007-11-15 22:23:56 +00005503static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005504 (int mode, int n, const char *file, int line) {
5505 /* this function is needed to perform locking on shared data
5506 structures. (Note that OpenSSL uses a number of global data
5507 structures that will be implicitly shared whenever multiple
5508 threads use OpenSSL.) Multi-threaded applications will
5509 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005511 locking_function() must be able to handle up to
5512 CRYPTO_num_locks() different mutex locks. It sets the n-th
5513 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005515 file and line are the file number of the function setting the
5516 lock. They can be useful for debugging.
5517 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005518
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005519 if ((_ssl_locks == NULL) ||
5520 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5521 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005523 if (mode & CRYPTO_LOCK) {
5524 PyThread_acquire_lock(_ssl_locks[n], 1);
5525 } else {
5526 PyThread_release_lock(_ssl_locks[n]);
5527 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005528}
5529
5530static int _setup_ssl_threads(void) {
5531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005532 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005534 if (_ssl_locks == NULL) {
5535 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005536 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5537 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005538 if (_ssl_locks == NULL) {
5539 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005540 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005541 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005542 for (i = 0; i < _ssl_locks_count; i++) {
5543 _ssl_locks[i] = PyThread_allocate_lock();
5544 if (_ssl_locks[i] == NULL) {
5545 unsigned int j;
5546 for (j = 0; j < i; j++) {
5547 PyThread_free_lock(_ssl_locks[j]);
5548 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005549 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005550 return 0;
5551 }
5552 }
5553 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005554#if OPENSSL_VERSION_NUMBER >= 0x10000000
5555 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5556#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005557 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005558#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005559 }
5560 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005561}
5562
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005563#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005564
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005565PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005566"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005567for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005568
Martin v. Löwis1a214512008-06-11 05:26:20 +00005569
5570static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005571 PyModuleDef_HEAD_INIT,
5572 "_ssl",
5573 module_doc,
5574 -1,
5575 PySSL_methods,
5576 NULL,
5577 NULL,
5578 NULL,
5579 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005580};
5581
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005582
5583static void
5584parse_openssl_version(unsigned long libver,
5585 unsigned int *major, unsigned int *minor,
5586 unsigned int *fix, unsigned int *patch,
5587 unsigned int *status)
5588{
5589 *status = libver & 0xF;
5590 libver >>= 4;
5591 *patch = libver & 0xFF;
5592 libver >>= 8;
5593 *fix = libver & 0xFF;
5594 libver >>= 8;
5595 *minor = libver & 0xFF;
5596 libver >>= 8;
5597 *major = libver & 0xFF;
5598}
5599
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005600PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005601PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005602{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005603 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005604 unsigned long libver;
5605 unsigned int major, minor, fix, patch, status;
5606 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005607 struct py_ssl_error_code *errcode;
5608 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005609
Antoine Pitrou152efa22010-05-16 18:19:27 +00005610 if (PyType_Ready(&PySSLContext_Type) < 0)
5611 return NULL;
5612 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005613 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005614 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5615 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005616 if (PyType_Ready(&PySSLSession_Type) < 0)
5617 return NULL;
5618
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005620 m = PyModule_Create(&_sslmodule);
5621 if (m == NULL)
5622 return NULL;
5623 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005625 /* Load _socket module and its C API */
5626 socket_api = PySocketModule_ImportModuleAndAPI();
5627 if (!socket_api)
5628 return NULL;
5629 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005630
Christian Heimesc941e622017-09-05 15:47:11 +02005631#ifndef OPENSSL_VERSION_1_1
5632 /* Load all algorithms and initialize cpuid */
5633 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005634 /* Init OpenSSL */
5635 SSL_load_error_strings();
5636 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005637#endif
5638
Christian Heimes598894f2016-09-05 23:19:05 +02005639#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005640 /* note that this will start threading if not already started */
5641 if (!_setup_ssl_threads()) {
5642 return NULL;
5643 }
Christian Heimes598894f2016-09-05 23:19:05 +02005644#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5645 /* OpenSSL 1.1.0 builtin thread support is enabled */
5646 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005647#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005649 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005650 sslerror_type_slots[0].pfunc = PyExc_OSError;
5651 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005652 if (PySSLErrorObject == NULL)
5653 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005654
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005655 /* ssl.CertificateError used to be a subclass of ValueError */
5656 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5657 if (bases == NULL)
5658 return NULL;
5659 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5660 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5661 bases, NULL);
5662 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005663 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5664 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5665 PySSLErrorObject, NULL);
5666 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5667 "ssl.SSLWantReadError", SSLWantReadError_doc,
5668 PySSLErrorObject, NULL);
5669 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5670 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5671 PySSLErrorObject, NULL);
5672 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5673 "ssl.SSLSyscallError", SSLSyscallError_doc,
5674 PySSLErrorObject, NULL);
5675 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5676 "ssl.SSLEOFError", SSLEOFError_doc,
5677 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005678 if (PySSLCertVerificationErrorObject == NULL
5679 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005680 || PySSLWantReadErrorObject == NULL
5681 || PySSLWantWriteErrorObject == NULL
5682 || PySSLSyscallErrorObject == NULL
5683 || PySSLEOFErrorObject == NULL)
5684 return NULL;
5685 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005686 || PyDict_SetItemString(d, "SSLCertVerificationError",
5687 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005688 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5689 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5690 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5691 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5692 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005693 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005694 if (PyDict_SetItemString(d, "_SSLContext",
5695 (PyObject *)&PySSLContext_Type) != 0)
5696 return NULL;
5697 if (PyDict_SetItemString(d, "_SSLSocket",
5698 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005699 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005700 if (PyDict_SetItemString(d, "MemoryBIO",
5701 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5702 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005703 if (PyDict_SetItemString(d, "SSLSession",
5704 (PyObject *)&PySSLSession_Type) != 0)
5705 return NULL;
5706
Christian Heimes892d66e2018-01-29 14:10:18 +01005707 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5708 PY_SSL_DEFAULT_CIPHER_STRING);
5709
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005710 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5711 PY_SSL_ERROR_ZERO_RETURN);
5712 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5713 PY_SSL_ERROR_WANT_READ);
5714 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5715 PY_SSL_ERROR_WANT_WRITE);
5716 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5717 PY_SSL_ERROR_WANT_X509_LOOKUP);
5718 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5719 PY_SSL_ERROR_SYSCALL);
5720 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5721 PY_SSL_ERROR_SSL);
5722 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5723 PY_SSL_ERROR_WANT_CONNECT);
5724 /* non ssl.h errorcodes */
5725 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5726 PY_SSL_ERROR_EOF);
5727 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5728 PY_SSL_ERROR_INVALID_ERROR_CODE);
5729 /* cert requirements */
5730 PyModule_AddIntConstant(m, "CERT_NONE",
5731 PY_SSL_CERT_NONE);
5732 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5733 PY_SSL_CERT_OPTIONAL);
5734 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5735 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005736 /* CRL verification for verification_flags */
5737 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5738 0);
5739 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5740 X509_V_FLAG_CRL_CHECK);
5741 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5742 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5743 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5744 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005745#ifdef X509_V_FLAG_TRUSTED_FIRST
5746 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5747 X509_V_FLAG_TRUSTED_FIRST);
5748#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005749
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005750 /* Alert Descriptions from ssl.h */
5751 /* note RESERVED constants no longer intended for use have been removed */
5752 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5753
5754#define ADD_AD_CONSTANT(s) \
5755 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5756 SSL_AD_##s)
5757
5758 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5759 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5760 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5761 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5762 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5763 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5764 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5765 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5766 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5767 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5768 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5769 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5770 ADD_AD_CONSTANT(UNKNOWN_CA);
5771 ADD_AD_CONSTANT(ACCESS_DENIED);
5772 ADD_AD_CONSTANT(DECODE_ERROR);
5773 ADD_AD_CONSTANT(DECRYPT_ERROR);
5774 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5775 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5776 ADD_AD_CONSTANT(INTERNAL_ERROR);
5777 ADD_AD_CONSTANT(USER_CANCELLED);
5778 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005779 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005780#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5781 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5782#endif
5783#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5784 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5785#endif
5786#ifdef SSL_AD_UNRECOGNIZED_NAME
5787 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5788#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005789#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5790 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5791#endif
5792#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5793 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5794#endif
5795#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5796 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5797#endif
5798
5799#undef ADD_AD_CONSTANT
5800
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005801 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005802#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005803 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5804 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005805#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005806#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005807 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5808 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005809#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005810 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005811 PY_SSL_VERSION_TLS);
5812 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5813 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005814 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5815 PY_SSL_VERSION_TLS_CLIENT);
5816 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5817 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005818 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5819 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005820#if HAVE_TLSv1_2
5821 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5822 PY_SSL_VERSION_TLS1_1);
5823 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5824 PY_SSL_VERSION_TLS1_2);
5825#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005826
Antoine Pitroub5218772010-05-21 09:56:06 +00005827 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005828 PyModule_AddIntConstant(m, "OP_ALL",
5829 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005830 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5831 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5832 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005833#if HAVE_TLSv1_2
5834 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5835 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5836#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005837#ifdef SSL_OP_NO_TLSv1_3
5838 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5839#else
5840 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5841#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005842 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5843 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005844 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005845 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005846#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005847 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005848#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005849#ifdef SSL_OP_NO_COMPRESSION
5850 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5851 SSL_OP_NO_COMPRESSION);
5852#endif
Miss Islington (bot)2614ed42018-02-27 00:17:49 -08005853#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5854 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5855 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5856#endif
Miss Islington (bot)e2db6ad2018-05-16 07:26:19 -07005857#ifdef SSL_OP_NO_RENEGOTIATION
5858 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5859 SSL_OP_NO_RENEGOTIATION);
5860#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005861
Christian Heimes61d478c2018-01-27 15:51:38 +01005862#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5863 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5864 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5865#endif
5866#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5867 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5868 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5869#endif
5870#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5871 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5872 X509_CHECK_FLAG_NO_WILDCARDS);
5873#endif
5874#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5875 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5876 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5877#endif
5878#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5879 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5880 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5881#endif
5882#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5883 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5884 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5885#endif
5886
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005887 /* protocol versions */
5888 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5889 PY_PROTO_MINIMUM_SUPPORTED);
5890 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5891 PY_PROTO_MAXIMUM_SUPPORTED);
5892 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5893 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5894 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5895 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5896 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005897
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005898#define addbool(m, v, b) \
5899 Py_INCREF((b) ? Py_True : Py_False); \
5900 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5901
5902#if HAVE_SNI
5903 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005904#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005905 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005906#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005907
5908 addbool(m, "HAS_TLS_UNIQUE", 1);
5909
5910#ifndef OPENSSL_NO_ECDH
5911 addbool(m, "HAS_ECDH", 1);
5912#else
5913 addbool(m, "HAS_ECDH", 0);
5914#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005915
Miss Islington (bot)96177412018-02-25 04:18:43 -08005916#if HAVE_NPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005917 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005918#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005919 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005920#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005921
Miss Islington (bot)96177412018-02-25 04:18:43 -08005922#if HAVE_ALPN
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005923 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005924#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005925 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005926#endif
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005927
5928#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5929 addbool(m, "HAS_SSLv2", 1);
5930#else
5931 addbool(m, "HAS_SSLv2", 0);
5932#endif
5933
5934#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5935 addbool(m, "HAS_SSLv3", 1);
5936#else
5937 addbool(m, "HAS_SSLv3", 0);
5938#endif
5939
5940#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5941 addbool(m, "HAS_TLSv1", 1);
5942#else
5943 addbool(m, "HAS_TLSv1", 0);
5944#endif
5945
5946#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5947 addbool(m, "HAS_TLSv1_1", 1);
5948#else
5949 addbool(m, "HAS_TLSv1_1", 0);
5950#endif
5951
5952#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5953 addbool(m, "HAS_TLSv1_2", 1);
5954#else
5955 addbool(m, "HAS_TLSv1_2", 0);
5956#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005957
Christian Heimescb5b68a2017-09-07 18:07:00 -07005958#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005959 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005960#else
Miss Islington (bot)4c842b02018-02-27 03:41:04 -08005961 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005962#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005963
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005964 /* Mappings for error codes */
5965 err_codes_to_names = PyDict_New();
5966 err_names_to_codes = PyDict_New();
5967 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5968 return NULL;
5969 errcode = error_codes;
5970 while (errcode->mnemonic != NULL) {
5971 PyObject *mnemo, *key;
5972 mnemo = PyUnicode_FromString(errcode->mnemonic);
5973 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5974 if (mnemo == NULL || key == NULL)
5975 return NULL;
5976 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5977 return NULL;
5978 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5979 return NULL;
5980 Py_DECREF(key);
5981 Py_DECREF(mnemo);
5982 errcode++;
5983 }
5984 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5985 return NULL;
5986 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5987 return NULL;
5988
5989 lib_codes_to_names = PyDict_New();
5990 if (lib_codes_to_names == NULL)
5991 return NULL;
5992 libcode = library_codes;
5993 while (libcode->library != NULL) {
5994 PyObject *mnemo, *key;
5995 key = PyLong_FromLong(libcode->code);
5996 mnemo = PyUnicode_FromString(libcode->library);
5997 if (key == NULL || mnemo == NULL)
5998 return NULL;
5999 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
6000 return NULL;
6001 Py_DECREF(key);
6002 Py_DECREF(mnemo);
6003 libcode++;
6004 }
6005 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
6006 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02006007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006008 /* OpenSSL version */
6009 /* SSLeay() gives us the version of the library linked against,
6010 which could be different from the headers version.
6011 */
6012 libver = SSLeay();
6013 r = PyLong_FromUnsignedLong(libver);
6014 if (r == NULL)
6015 return NULL;
6016 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6017 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006018 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006019 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6020 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6021 return NULL;
6022 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6023 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6024 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006025
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006026 libver = OPENSSL_VERSION_NUMBER;
6027 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6028 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6029 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6030 return NULL;
6031
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006032 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006033}