blob: 4baabd52bc9f2e1e0eb70884d89422a826333d91 [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"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066
Christian Heimesff5be6e2018-01-20 13:19:21 +010067#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010068# ifdef LIBRESSL_VERSION_NUMBER
69# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
70# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010071# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010072# else
73# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010074# endif
75#endif
76
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077/* SSL error object */
78static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070079static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080static PyObject *PySSLZeroReturnErrorObject;
81static PyObject *PySSLWantReadErrorObject;
82static PyObject *PySSLWantWriteErrorObject;
83static PyObject *PySSLSyscallErrorObject;
84static PyObject *PySSLEOFErrorObject;
85
86/* Error mappings */
87static PyObject *err_codes_to_names;
88static PyObject *err_names_to_codes;
89static PyObject *lib_codes_to_names;
90
91struct py_ssl_error_code {
92 const char *mnemonic;
93 int library, reason;
94};
95struct py_ssl_library_code {
96 const char *library;
97 int code;
98};
99
Steve Dower68d663c2017-07-17 11:15:48 +0200100#if defined(MS_WINDOWS) && defined(Py_DEBUG)
101/* Debug builds on Windows rely on getting errno directly from OpenSSL.
102 * However, because it uses a different CRT, we need to transfer the
103 * value of errno from OpenSSL into our debug CRT.
104 *
105 * Don't be fooled - this is horribly ugly code. The only reasonable
106 * alternative is to do both debug and release builds of OpenSSL, which
107 * requires much uglier code to transform their automatically generated
108 * makefile. This is the lesser of all the evils.
109 */
110
111static void _PySSLFixErrno(void) {
112 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
113 if (!ucrtbase) {
114 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
115 * have a catastrophic failure, but this function is not the
116 * place to raise it. */
117 return;
118 }
119
120 typedef int *(__stdcall *errno_func)(void);
121 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
122 if (ssl_errno) {
123 errno = *ssl_errno();
124 *ssl_errno() = 0;
125 } else {
126 errno = ENOTRECOVERABLE;
127 }
128}
129
130#undef _PySSL_FIX_ERRNO
131#define _PySSL_FIX_ERRNO _PySSLFixErrno()
132#endif
133
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100134/* Include generated data (error codes) */
135#include "_ssl_data.h"
136
Christian Heimes598894f2016-09-05 23:19:05 +0200137#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
138# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100139# define PY_OPENSSL_1_1_API 1
140#endif
141
142/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
143#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
144# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200145#endif
146
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
148 http://www.openssl.org/news/changelog.html
149 */
150#if OPENSSL_VERSION_NUMBER >= 0x10001000L
151# define HAVE_TLSv1_2 1
152#else
153# define HAVE_TLSv1_2 0
154#endif
155
Christian Heimes470fba12013-11-28 15:12:15 +0100156/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100157 * This includes the SSL_set_SSL_CTX() function.
158 */
159#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
160# define HAVE_SNI 1
161#else
162# define HAVE_SNI 0
163#endif
164
Benjamin Petersond3308222015-09-27 00:09:02 -0700165#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100166# define HAVE_ALPN 1
167#else
168# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500169#endif
170
Christian Heimes6cdb7952018-02-24 22:12:40 +0100171/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
172 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
173 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
174 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100175 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100176 */
177#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_NPN 0
179#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
180# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100181#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100182# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100183#else
Christian Heimes29eab552018-02-25 12:31:33 +0100184# define HAVE_NPN 0
185#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100186
Victor Stinner524714e2016-07-22 17:43:59 +0200187#ifndef INVALID_SOCKET /* MS defines this */
188#define INVALID_SOCKET (-1)
189#endif
190
Christian Heimes4ca07392018-03-24 15:41:37 +0100191/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
192#ifndef OPENSSL_VERSION_1_1
193#define HAVE_OPENSSL_CRYPTO_LOCK
194#endif
195
196#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200197#define OPENSSL_NO_SSL2
198#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100199
200#ifndef PY_OPENSSL_1_1_API
201/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200202
203#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200204#define TLS_client_method SSLv23_client_method
205#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200206
207static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
208{
209 return ne->set;
210}
211
212#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200213/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200214static int COMP_get_type(const COMP_METHOD *meth)
215{
216 return meth->type;
217}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200218/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200219#endif
220
221static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
222{
223 return ctx->default_passwd_callback;
224}
225
226static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
227{
228 return ctx->default_passwd_callback_userdata;
229}
230
231static int X509_OBJECT_get_type(X509_OBJECT *x)
232{
233 return x->type;
234}
235
236static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
237{
238 return x->data.x509;
239}
240
241static int BIO_up_ref(BIO *b)
242{
243 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
244 return 1;
245}
246
247static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
248 return store->objs;
249}
250
Christian Heimes99a65702016-09-10 23:44:53 +0200251static int
252SSL_SESSION_has_ticket(const SSL_SESSION *s)
253{
254 return (s->tlsext_ticklen > 0) ? 1 : 0;
255}
256
257static unsigned long
258SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
259{
260 return s->tlsext_tick_lifetime_hint;
261}
262
Christian Heimes4ca07392018-03-24 15:41:37 +0100263#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200264
Christian Heimes892d66e2018-01-29 14:10:18 +0100265/* Default cipher suites */
266#ifndef PY_SSL_DEFAULT_CIPHERS
267#define PY_SSL_DEFAULT_CIPHERS 1
268#endif
269
270#if PY_SSL_DEFAULT_CIPHERS == 0
271 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
272 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
273 #endif
274#elif PY_SSL_DEFAULT_CIPHERS == 1
275/* Python custom selection of sensible ciper suites
276 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
277 * !aNULL:!eNULL: really no NULL ciphers
278 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
279 * !aDSS: no authentication with discrete logarithm DSA algorithm
280 * !SRP:!PSK: no secure remote password or pre-shared key authentication
281 */
282 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
283#elif PY_SSL_DEFAULT_CIPHERS == 2
284/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
285 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
286#else
287 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
288#endif
289
Christian Heimes598894f2016-09-05 23:19:05 +0200290
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000291enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 /* these mirror ssl.h */
293 PY_SSL_ERROR_NONE,
294 PY_SSL_ERROR_SSL,
295 PY_SSL_ERROR_WANT_READ,
296 PY_SSL_ERROR_WANT_WRITE,
297 PY_SSL_ERROR_WANT_X509_LOOKUP,
298 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
299 PY_SSL_ERROR_ZERO_RETURN,
300 PY_SSL_ERROR_WANT_CONNECT,
301 /* start of non ssl.h errorcodes */
302 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
303 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
304 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000305};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Thomas Woutersed03b412007-08-28 21:37:11 +0000307enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000308 PY_SSL_CLIENT,
309 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000310};
311
312enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 PY_SSL_CERT_NONE,
314 PY_SSL_CERT_OPTIONAL,
315 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000316};
317
318enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000319 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200320 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200321 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100322#if HAVE_TLSv1_2
323 PY_SSL_VERSION_TLS1,
324 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200325 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100326#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200327 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000328#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200329 PY_SSL_VERSION_TLS_CLIENT=0x10,
330 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100331};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200332
Christian Heimes698dde12018-02-27 11:54:43 +0100333enum py_proto_version {
334 PY_PROTO_MINIMUM_SUPPORTED = -2,
335 PY_PROTO_SSLv3 = SSL3_VERSION,
336 PY_PROTO_TLSv1 = TLS1_VERSION,
337 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
338 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
339#ifdef TLS1_3_VERSION
340 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
341#else
342 PY_PROTO_TLSv1_3 = 0x304,
343#endif
344 PY_PROTO_MAXIMUM_SUPPORTED = -1,
345
346/* OpenSSL has no dedicated API to set the minimum version to the maximum
347 * available version, and the other way around. We have to figure out the
348 * minimum and maximum available version on our own and hope for the best.
349 */
350#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
351 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
352#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
353 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
354#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
355 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
356#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
357 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
358#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
359 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
360#else
361 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
362#endif
363
364#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
365 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
366#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
367 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
368#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
369 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
370#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
371 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
372#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
373 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
374#else
375 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
376#endif
377};
378
379
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380/* serves as a flag to see whether we've initialized the SSL thread support. */
381/* 0 means no, greater than 0 means yes */
382
383static unsigned int _ssl_locks_count = 0;
384
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000385/* SSL socket object */
386
387#define X509_NAME_MAXLEN 256
388
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000389/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
390 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
391 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
392#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000393# define HAVE_SSL_CTX_CLEAR_OPTIONS
394#else
395# undef HAVE_SSL_CTX_CLEAR_OPTIONS
396#endif
397
Antoine Pitroud6494802011-07-21 01:11:30 +0200398/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
399 * older SSL, but let's be safe */
400#define PySSL_CB_MAXLEN 128
401
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100402
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000405 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100406#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500407 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100408 int npn_protocols_len;
409#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100410#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500411 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300412 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500413#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100414#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100415 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100416#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100417 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100418 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
419 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
420 */
421 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100422 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000423} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000424
Antoine Pitrou152efa22010-05-16 18:19:27 +0000425typedef struct {
426 PyObject_HEAD
427 PyObject *Socket; /* weakref to socket on which we're layered */
428 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100429 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200430 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200431 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200432 PyObject *owner; /* Python level "owner" passed to servername callback */
433 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700434 int ssl_errno; /* last seen error from SSL */
435 int c_errno; /* last seen error from libc */
436#ifdef MS_WINDOWS
437 int ws_errno; /* last seen error from winsock */
438#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000439} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000440
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200441typedef struct {
442 PyObject_HEAD
443 BIO *bio;
444 int eof_written;
445} PySSLMemoryBIO;
446
Christian Heimes99a65702016-09-10 23:44:53 +0200447typedef struct {
448 PyObject_HEAD
449 SSL_SESSION *session;
450 PySSLContext *ctx;
451} PySSLSession;
452
Antoine Pitrou152efa22010-05-16 18:19:27 +0000453static PyTypeObject PySSLContext_Type;
454static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200455static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200456static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000457
Steve Dowere6eb48c2017-09-08 15:16:15 -0700458#ifdef MS_WINDOWS
459#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
460 (sock)->ws_errno = WSAGetLastError(); \
461 _PySSL_FIX_ERRNO; \
462 (sock)->c_errno = errno; \
463 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
464 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
465#else
466#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
467 (sock)->c_errno = errno; \
468 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
469 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
470#endif
471#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
472
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300473/*[clinic input]
474module _ssl
475class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
476class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
477class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200478class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300479[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200480/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300481
482#include "clinic/_ssl.c.h"
483
Victor Stinner14690702015-04-06 22:46:13 +0200484static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000485
Christian Heimes141c5e82018-02-24 21:10:57 +0100486static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
487static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000488#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200489#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200490#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000491
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000492typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 SOCKET_IS_NONBLOCKING,
494 SOCKET_IS_BLOCKING,
495 SOCKET_HAS_TIMED_OUT,
496 SOCKET_HAS_BEEN_CLOSED,
497 SOCKET_TOO_LARGE_FOR_SELECT,
498 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000499} timeout_state;
500
Thomas Woutersed03b412007-08-28 21:37:11 +0000501/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000502#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200503#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000504
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200505/* Get the socket from a PySSLSocket, if it has one */
506#define GET_SOCKET(obj) ((obj)->Socket ? \
507 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200508
Victor Stinner14690702015-04-06 22:46:13 +0200509/* If sock is NULL, use a timeout of 0 second */
510#define GET_SOCKET_TIMEOUT(sock) \
511 ((sock != NULL) ? (sock)->sock_timeout : 0)
512
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200513/*
514 * SSL errors.
515 */
516
517PyDoc_STRVAR(SSLError_doc,
518"An error occurred in the SSL implementation.");
519
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700520PyDoc_STRVAR(SSLCertVerificationError_doc,
521"A certificate could not be verified.");
522
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200523PyDoc_STRVAR(SSLZeroReturnError_doc,
524"SSL/TLS session closed cleanly.");
525
526PyDoc_STRVAR(SSLWantReadError_doc,
527"Non-blocking SSL socket needs to read more data\n"
528"before the requested operation can be completed.");
529
530PyDoc_STRVAR(SSLWantWriteError_doc,
531"Non-blocking SSL socket needs to write more data\n"
532"before the requested operation can be completed.");
533
534PyDoc_STRVAR(SSLSyscallError_doc,
535"System error when attempting SSL operation.");
536
537PyDoc_STRVAR(SSLEOFError_doc,
538"SSL/TLS connection terminated abruptly.");
539
540static PyObject *
541SSLError_str(PyOSErrorObject *self)
542{
543 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
544 Py_INCREF(self->strerror);
545 return self->strerror;
546 }
547 else
548 return PyObject_Str(self->args);
549}
550
551static PyType_Slot sslerror_type_slots[] = {
552 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
553 {Py_tp_doc, SSLError_doc},
554 {Py_tp_str, SSLError_str},
555 {0, 0},
556};
557
558static PyType_Spec sslerror_type_spec = {
559 "ssl.SSLError",
560 sizeof(PyOSErrorObject),
561 0,
562 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
563 sslerror_type_slots
564};
565
566static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700567fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
568 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569{
570 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200572 PyObject *init_value, *msg, *key;
573 _Py_IDENTIFIER(reason);
574 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700575 _Py_IDENTIFIER(verify_message);
576 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577
578 if (errcode != 0) {
579 int lib, reason;
580
581 lib = ERR_GET_LIB(errcode);
582 reason = ERR_GET_REASON(errcode);
583 key = Py_BuildValue("ii", lib, reason);
584 if (key == NULL)
585 goto fail;
586 reason_obj = PyDict_GetItem(err_codes_to_names, key);
587 Py_DECREF(key);
588 if (reason_obj == NULL) {
589 /* XXX if reason < 100, it might reflect a library number (!!) */
590 PyErr_Clear();
591 }
592 key = PyLong_FromLong(lib);
593 if (key == NULL)
594 goto fail;
595 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
596 Py_DECREF(key);
597 if (lib_obj == NULL) {
598 PyErr_Clear();
599 }
600 if (errstr == NULL)
601 errstr = ERR_reason_error_string(errcode);
602 }
603 if (errstr == NULL)
604 errstr = "unknown error";
605
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700606 /* verify code for cert validation error */
607 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
608 const char *verify_str = NULL;
609 long verify_code;
610
611 verify_code = SSL_get_verify_result(sslsock->ssl);
612 verify_code_obj = PyLong_FromLong(verify_code);
613 if (verify_code_obj == NULL) {
614 goto fail;
615 }
616
617 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700618#ifdef X509_V_ERR_HOSTNAME_MISMATCH
619 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700620 case X509_V_ERR_HOSTNAME_MISMATCH:
621 verify_obj = PyUnicode_FromFormat(
622 "Hostname mismatch, certificate is not valid for '%S'.",
623 sslsock->server_hostname
624 );
625 break;
Christian Heimes09153602017-09-08 14:47:58 -0700626#endif
627#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700628 case X509_V_ERR_IP_ADDRESS_MISMATCH:
629 verify_obj = PyUnicode_FromFormat(
630 "IP address mismatch, certificate is not valid for '%S'.",
631 sslsock->server_hostname
632 );
633 break;
Christian Heimes09153602017-09-08 14:47:58 -0700634#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 default:
636 verify_str = X509_verify_cert_error_string(verify_code);
637 if (verify_str != NULL) {
638 verify_obj = PyUnicode_FromString(verify_str);
639 } else {
640 verify_obj = Py_None;
641 Py_INCREF(verify_obj);
642 }
643 break;
644 }
645 if (verify_obj == NULL) {
646 goto fail;
647 }
648 }
649
650 if (verify_obj && reason_obj && lib_obj)
651 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
652 lib_obj, reason_obj, errstr, verify_obj,
653 lineno);
654 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200655 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
656 lib_obj, reason_obj, errstr, lineno);
657 else if (lib_obj)
658 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
659 lib_obj, errstr, lineno);
660 else
661 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200662 if (msg == NULL)
663 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100664
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200665 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100666 if (init_value == NULL)
667 goto fail;
668
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200669 err_value = PyObject_CallObject(type, init_value);
670 Py_DECREF(init_value);
671 if (err_value == NULL)
672 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100673
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200674 if (reason_obj == NULL)
675 reason_obj = Py_None;
676 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
677 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700678
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200679 if (lib_obj == NULL)
680 lib_obj = Py_None;
681 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
682 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700683
684 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
685 /* Only set verify code / message for SSLCertVerificationError */
686 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
687 verify_code_obj))
688 goto fail;
689 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
690 goto fail;
691 }
692
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200693 PyErr_SetObject(type, err_value);
694fail:
695 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700696 Py_XDECREF(verify_code_obj);
697 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200698}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000699
700static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700701PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000702{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200703 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200704 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 int err;
706 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200707 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200710 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000711
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700712 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700713 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000714
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 switch (err) {
716 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200717 errstr = "TLS/SSL connection has been closed (EOF)";
718 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 p = PY_SSL_ERROR_ZERO_RETURN;
720 break;
721 case SSL_ERROR_WANT_READ:
722 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200723 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 p = PY_SSL_ERROR_WANT_READ;
725 break;
726 case SSL_ERROR_WANT_WRITE:
727 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200728 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 errstr = "The operation did not complete (write)";
730 break;
731 case SSL_ERROR_WANT_X509_LOOKUP:
732 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000733 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 break;
735 case SSL_ERROR_WANT_CONNECT:
736 p = PY_SSL_ERROR_WANT_CONNECT;
737 errstr = "The operation did not complete (connect)";
738 break;
739 case SSL_ERROR_SYSCALL:
740 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700742 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000744 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200745 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000746 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200747 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000748 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000749 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700750#ifdef MS_WINDOWS
751 if (sslsock->ws_errno)
752 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
753#endif
754 if (sslsock->c_errno) {
755 errno = sslsock->c_errno;
756 return PyErr_SetFromErrno(PyExc_OSError);
757 }
758 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200759 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000760 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200761 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000762 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000763 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200764 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000765 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 }
767 } else {
768 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 }
770 break;
771 }
772 case SSL_ERROR_SSL:
773 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700775 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200776 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000777 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700778 }
779 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
780 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
781 type = PySSLCertVerificationErrorObject;
782 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 break;
784 }
785 default:
786 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
787 errstr = "Invalid error code";
788 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700790 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000791 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000793}
794
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200796_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200798 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200800 else
801 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700802 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000803 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805}
806
Christian Heimes61d478c2018-01-27 15:51:38 +0100807/*
808 * SSL objects
809 */
810
811static int
812_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
813{
814 int retval = -1;
815 ASN1_OCTET_STRING *ip;
816 PyObject *hostname;
817 size_t len;
818
819 assert(server_hostname);
820
821 /* Disable OpenSSL's special mode with leading dot in hostname:
822 * When name starts with a dot (e.g ".example.com"), it will be
823 * matched by a certificate valid for any sub-domain of name.
824 */
825 len = strlen(server_hostname);
826 if (len == 0 || *server_hostname == '.') {
827 PyErr_SetString(
828 PyExc_ValueError,
829 "server_hostname cannot be an empty string or start with a "
830 "leading dot.");
831 return retval;
832 }
833
834 /* inet_pton is not available on all platforms. */
835 ip = a2i_IPADDRESS(server_hostname);
836 if (ip == NULL) {
837 ERR_clear_error();
838 }
839
Christian Heimes11a14932018-02-24 02:35:08 +0100840 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100841 if (hostname == NULL) {
842 goto error;
843 }
844 self->server_hostname = hostname;
845
846 /* Only send SNI extension for non-IP hostnames */
847 if (ip == NULL) {
848 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
849 _setSSLError(NULL, 0, __FILE__, __LINE__);
850 }
851 }
852 if (self->ctx->check_hostname) {
853 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
854 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200855 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
856 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100857 _setSSLError(NULL, 0, __FILE__, __LINE__);
858 goto error;
859 }
860 } else {
861 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
862 ASN1_STRING_length(ip))) {
863 _setSSLError(NULL, 0, __FILE__, __LINE__);
864 goto error;
865 }
866 }
867 }
868 retval = 0;
869 error:
870 if (ip != NULL) {
871 ASN1_OCTET_STRING_free(ip);
872 }
873 return retval;
874}
875
Antoine Pitrou152efa22010-05-16 18:19:27 +0000876static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100877newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000878 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200879 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100880 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200881 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000882{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000883 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100884 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200885 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000886
Antoine Pitrou152efa22010-05-16 18:19:27 +0000887 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 if (self == NULL)
889 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100893 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700894 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200895 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200896 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700897 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700898 self->ssl_errno = 0;
899 self->c_errno = 0;
900#ifdef MS_WINDOWS
901 self->ws_errno = 0;
902#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 /* Make sure the SSL error state is initialized */
905 (void) ERR_get_state();
906 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000909 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200911 SSL_set_app_data(self->ssl, self);
912 if (sock) {
913 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
914 } else {
915 /* BIOs are reference counted and SSL_set_bio borrows our reference.
916 * To prevent a double free in memory_bio_dealloc() we need to take an
917 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200918 BIO_up_ref(inbio->bio);
919 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200920 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
921 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200922 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000923#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200924 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000925#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200926 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000927
Christian Heimes61d478c2018-01-27 15:51:38 +0100928 if (server_hostname != NULL) {
929 if (_ssl_configure_hostname(self, server_hostname) < 0) {
930 Py_DECREF(self);
931 return NULL;
932 }
933 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* If the socket is in non-blocking mode or timeout mode, set the BIO
935 * to non-blocking mode (blocking is the default)
936 */
Victor Stinnere2452312015-03-28 03:00:46 +0100937 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
939 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
940 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000941
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 PySSL_BEGIN_ALLOW_THREADS
943 if (socket_type == PY_SSL_CLIENT)
944 SSL_set_connect_state(self->ssl);
945 else
946 SSL_set_accept_state(self->ssl);
947 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000948
Antoine Pitroud6494802011-07-21 01:11:30 +0200949 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200950 if (sock != NULL) {
951 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
952 if (self->Socket == NULL) {
953 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200954 return NULL;
955 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100956 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100957 if (owner && owner != Py_None) {
958 if (PySSL_set_owner(self, owner, NULL) == -1) {
959 Py_DECREF(self);
960 return NULL;
961 }
962 }
963 if (session && session != Py_None) {
964 if (PySSL_set_session(self, session, NULL) == -1) {
965 Py_DECREF(self);
966 return NULL;
967 }
968 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000970}
971
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000972/* SSL object methods */
973
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300974/*[clinic input]
975_ssl._SSLSocket.do_handshake
976[clinic start generated code]*/
977
978static PyObject *
979_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
980/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000981{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 int ret;
983 int err;
984 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200985 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200986 _PyTime_t timeout, deadline = 0;
987 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000988
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200989 if (sock) {
990 if (((PyObject*)sock) == Py_None) {
991 _setSSLError("Underlying socket connection gone",
992 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
993 return NULL;
994 }
995 Py_INCREF(sock);
996
997 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100998 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200999 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1000 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001002
Victor Stinner14690702015-04-06 22:46:13 +02001003 timeout = GET_SOCKET_TIMEOUT(sock);
1004 has_timeout = (timeout > 0);
1005 if (has_timeout)
1006 deadline = _PyTime_GetMonotonicClock() + timeout;
1007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 /* Actually negotiate SSL connection */
1009 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001011 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07001013 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07001015 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001016
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001017 if (PyErr_CheckSignals())
1018 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001019
Victor Stinner14690702015-04-06 22:46:13 +02001020 if (has_timeout)
1021 timeout = deadline - _PyTime_GetMonotonicClock();
1022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001024 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001026 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 } else {
1028 sockstate = SOCKET_OPERATION_OK;
1029 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001030
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001032 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001033 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001034 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001035 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1036 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001037 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001038 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1040 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001041 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001042 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1044 break;
1045 }
1046 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001047 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001048 if (ret < 1)
1049 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001050
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001051 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001052
1053error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001054 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001055 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001056}
1057
Thomas Woutersed03b412007-08-28 21:37:11 +00001058static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001059_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1060{
1061 char buf[X509_NAME_MAXLEN];
1062 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001064 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001065
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001066 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 if (buflen < 0) {
1068 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001069 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001070 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001071 /* initial buffer is too small for oid + terminating null byte */
1072 if (buflen > X509_NAME_MAXLEN - 1) {
1073 /* make OBJ_obj2txt() calculate the required buflen */
1074 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1075 /* allocate len + 1 for terminating NULL byte */
1076 namebuf = PyMem_Malloc(buflen + 1);
1077 if (namebuf == NULL) {
1078 PyErr_NoMemory();
1079 return NULL;
1080 }
1081 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1082 if (buflen < 0) {
1083 _setSSLError(NULL, 0, __FILE__, __LINE__);
1084 goto done;
1085 }
1086 }
1087 if (!buflen && no_name) {
1088 Py_INCREF(Py_None);
1089 name_obj = Py_None;
1090 }
1091 else {
1092 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1093 }
1094
1095 done:
1096 if (buf != namebuf) {
1097 PyMem_Free(namebuf);
1098 }
1099 return name_obj;
1100}
1101
1102static PyObject *
1103_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1104{
1105 Py_ssize_t buflen;
1106 unsigned char *valuebuf = NULL;
1107 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1110 if (buflen < 0) {
1111 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001112 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001114 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001117}
1118
1119static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001120_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001121{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1123 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1124 PyObject *rdnt;
1125 PyObject *attr = NULL; /* tuple to hold an attribute */
1126 int entry_count = X509_NAME_entry_count(xname);
1127 X509_NAME_ENTRY *entry;
1128 ASN1_OBJECT *name;
1129 ASN1_STRING *value;
1130 int index_counter;
1131 int rdn_level = -1;
1132 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 dn = PyList_New(0);
1135 if (dn == NULL)
1136 return NULL;
1137 /* now create another tuple to hold the top-level RDN */
1138 rdn = PyList_New(0);
1139 if (rdn == NULL)
1140 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 for (index_counter = 0;
1143 index_counter < entry_count;
1144 index_counter++)
1145 {
1146 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001147
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 /* check to see if we've gotten to a new RDN */
1149 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001150 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001151 /* yes, new RDN */
1152 /* add old RDN to DN */
1153 rdnt = PyList_AsTuple(rdn);
1154 Py_DECREF(rdn);
1155 if (rdnt == NULL)
1156 goto fail0;
1157 retcode = PyList_Append(dn, rdnt);
1158 Py_DECREF(rdnt);
1159 if (retcode < 0)
1160 goto fail0;
1161 /* create new RDN */
1162 rdn = PyList_New(0);
1163 if (rdn == NULL)
1164 goto fail0;
1165 }
1166 }
Christian Heimes598894f2016-09-05 23:19:05 +02001167 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001169 /* now add this attribute to the current RDN */
1170 name = X509_NAME_ENTRY_get_object(entry);
1171 value = X509_NAME_ENTRY_get_data(entry);
1172 attr = _create_tuple_for_attribute(name, value);
1173 /*
1174 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1175 entry->set,
1176 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1177 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1178 */
1179 if (attr == NULL)
1180 goto fail1;
1181 retcode = PyList_Append(rdn, attr);
1182 Py_DECREF(attr);
1183 if (retcode < 0)
1184 goto fail1;
1185 }
1186 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001187 if (rdn != NULL) {
1188 if (PyList_GET_SIZE(rdn) > 0) {
1189 rdnt = PyList_AsTuple(rdn);
1190 Py_DECREF(rdn);
1191 if (rdnt == NULL)
1192 goto fail0;
1193 retcode = PyList_Append(dn, rdnt);
1194 Py_DECREF(rdnt);
1195 if (retcode < 0)
1196 goto fail0;
1197 }
1198 else {
1199 Py_DECREF(rdn);
1200 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001202
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 /* convert list to tuple */
1204 rdnt = PyList_AsTuple(dn);
1205 Py_DECREF(dn);
1206 if (rdnt == NULL)
1207 return NULL;
1208 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
1210 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212
1213 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001214 Py_XDECREF(dn);
1215 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216}
1217
1218static PyObject *
1219_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001220
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 /* this code follows the procedure outlined in
1222 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1223 function to extract the STACK_OF(GENERAL_NAME),
1224 then iterates through the stack to add the
1225 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001226
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001227 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001229 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001230 GENERAL_NAMES *names = NULL;
1231 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001232 BIO *biobuf = NULL;
1233 char buf[2048];
1234 char *vptr;
1235 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 if (certificate == NULL)
1238 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001240 /* get a memory buffer */
1241 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001243 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1244 certificate, NID_subject_alt_name, NULL, NULL);
1245 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 if (peer_alt_names == Py_None) {
1247 peer_alt_names = PyList_New(0);
1248 if (peer_alt_names == NULL)
1249 goto fail;
1250 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001254 int gntype;
1255 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001256
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001258 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001259 switch (gntype) {
1260 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 /* we special-case DirName as a tuple of
1262 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 t = PyTuple_New(2);
1265 if (t == NULL) {
1266 goto fail;
1267 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 v = PyUnicode_FromString("DirName");
1270 if (v == NULL) {
1271 Py_DECREF(t);
1272 goto fail;
1273 }
1274 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 v = _create_tuple_for_X509_NAME (name->d.dirn);
1277 if (v == NULL) {
1278 Py_DECREF(t);
1279 goto fail;
1280 }
1281 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001282 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001283
Christian Heimes824f7f32013-08-17 00:54:47 +02001284 case GEN_EMAIL:
1285 case GEN_DNS:
1286 case GEN_URI:
1287 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1288 correctly, CVE-2013-4238 */
1289 t = PyTuple_New(2);
1290 if (t == NULL)
1291 goto fail;
1292 switch (gntype) {
1293 case GEN_EMAIL:
1294 v = PyUnicode_FromString("email");
1295 as = name->d.rfc822Name;
1296 break;
1297 case GEN_DNS:
1298 v = PyUnicode_FromString("DNS");
1299 as = name->d.dNSName;
1300 break;
1301 case GEN_URI:
1302 v = PyUnicode_FromString("URI");
1303 as = name->d.uniformResourceIdentifier;
1304 break;
1305 }
1306 if (v == NULL) {
1307 Py_DECREF(t);
1308 goto fail;
1309 }
1310 PyTuple_SET_ITEM(t, 0, v);
1311 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1312 ASN1_STRING_length(as));
1313 if (v == NULL) {
1314 Py_DECREF(t);
1315 goto fail;
1316 }
1317 PyTuple_SET_ITEM(t, 1, v);
1318 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001319
Christian Heimes1c03abd2016-09-06 23:25:35 +02001320 case GEN_RID:
1321 t = PyTuple_New(2);
1322 if (t == NULL)
1323 goto fail;
1324
1325 v = PyUnicode_FromString("Registered ID");
1326 if (v == NULL) {
1327 Py_DECREF(t);
1328 goto fail;
1329 }
1330 PyTuple_SET_ITEM(t, 0, v);
1331
1332 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1333 if (len < 0) {
1334 Py_DECREF(t);
1335 _setSSLError(NULL, 0, __FILE__, __LINE__);
1336 goto fail;
1337 } else if (len >= (int)sizeof(buf)) {
1338 v = PyUnicode_FromString("<INVALID>");
1339 } else {
1340 v = PyUnicode_FromStringAndSize(buf, len);
1341 }
1342 if (v == NULL) {
1343 Py_DECREF(t);
1344 goto fail;
1345 }
1346 PyTuple_SET_ITEM(t, 1, v);
1347 break;
1348
Christian Heimes824f7f32013-08-17 00:54:47 +02001349 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001350 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001351 switch (gntype) {
1352 /* check for new general name type */
1353 case GEN_OTHERNAME:
1354 case GEN_X400:
1355 case GEN_EDIPARTY:
1356 case GEN_IPADD:
1357 case GEN_RID:
1358 break;
1359 default:
1360 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1361 "Unknown general name type %d",
1362 gntype) == -1) {
1363 goto fail;
1364 }
1365 break;
1366 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 (void) BIO_reset(biobuf);
1368 GENERAL_NAME_print(biobuf, name);
1369 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1370 if (len < 0) {
1371 _setSSLError(NULL, 0, __FILE__, __LINE__);
1372 goto fail;
1373 }
1374 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001375 if (vptr == NULL) {
1376 PyErr_Format(PyExc_ValueError,
1377 "Invalid value %.200s",
1378 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001380 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 t = PyTuple_New(2);
1382 if (t == NULL)
1383 goto fail;
1384 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1385 if (v == NULL) {
1386 Py_DECREF(t);
1387 goto fail;
1388 }
1389 PyTuple_SET_ITEM(t, 0, v);
1390 v = PyUnicode_FromStringAndSize((vptr + 1),
1391 (len - (vptr - buf + 1)));
1392 if (v == NULL) {
1393 Py_DECREF(t);
1394 goto fail;
1395 }
1396 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001397 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001399
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001401
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 if (PyList_Append(peer_alt_names, t) < 0) {
1403 Py_DECREF(t);
1404 goto fail;
1405 }
1406 Py_DECREF(t);
1407 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001408 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 }
1410 BIO_free(biobuf);
1411 if (peer_alt_names != Py_None) {
1412 v = PyList_AsTuple(peer_alt_names);
1413 Py_DECREF(peer_alt_names);
1414 return v;
1415 } else {
1416 return peer_alt_names;
1417 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001418
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419
1420 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 if (biobuf != NULL)
1422 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 if (peer_alt_names != Py_None) {
1425 Py_XDECREF(peer_alt_names);
1426 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001429}
1430
1431static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001432_get_aia_uri(X509 *certificate, int nid) {
1433 PyObject *lst = NULL, *ostr = NULL;
1434 int i, result;
1435 AUTHORITY_INFO_ACCESS *info;
1436
1437 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001438 if (info == NULL)
1439 return Py_None;
1440 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1441 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001442 return Py_None;
1443 }
1444
1445 if ((lst = PyList_New(0)) == NULL) {
1446 goto fail;
1447 }
1448
1449 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1450 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1451 ASN1_IA5STRING *uri;
1452
1453 if ((OBJ_obj2nid(ad->method) != nid) ||
1454 (ad->location->type != GEN_URI)) {
1455 continue;
1456 }
1457 uri = ad->location->d.uniformResourceIdentifier;
1458 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1459 uri->length);
1460 if (ostr == NULL) {
1461 goto fail;
1462 }
1463 result = PyList_Append(lst, ostr);
1464 Py_DECREF(ostr);
1465 if (result < 0) {
1466 goto fail;
1467 }
1468 }
1469 AUTHORITY_INFO_ACCESS_free(info);
1470
1471 /* convert to tuple or None */
1472 if (PyList_Size(lst) == 0) {
1473 Py_DECREF(lst);
1474 return Py_None;
1475 } else {
1476 PyObject *tup;
1477 tup = PyList_AsTuple(lst);
1478 Py_DECREF(lst);
1479 return tup;
1480 }
1481
1482 fail:
1483 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001484 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001485 return NULL;
1486}
1487
1488static PyObject *
1489_get_crl_dp(X509 *certificate) {
1490 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001491 int i, j;
1492 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001493
Christian Heimes598894f2016-09-05 23:19:05 +02001494 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001495
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001496 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001497 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001498
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001499 lst = PyList_New(0);
1500 if (lst == NULL)
1501 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001502
1503 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1504 DIST_POINT *dp;
1505 STACK_OF(GENERAL_NAME) *gns;
1506
1507 dp = sk_DIST_POINT_value(dps, i);
1508 gns = dp->distpoint->name.fullname;
1509
1510 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1511 GENERAL_NAME *gn;
1512 ASN1_IA5STRING *uri;
1513 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001514 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001515
1516 gn = sk_GENERAL_NAME_value(gns, j);
1517 if (gn->type != GEN_URI) {
1518 continue;
1519 }
1520 uri = gn->d.uniformResourceIdentifier;
1521 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1522 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001523 if (ouri == NULL)
1524 goto done;
1525
1526 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001527 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001528 if (err < 0)
1529 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001530 }
1531 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001532
1533 /* Convert to tuple. */
1534 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1535
1536 done:
1537 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001538 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001539 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001540}
1541
1542static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001543_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001544
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 PyObject *retval = NULL;
1546 BIO *biobuf = NULL;
1547 PyObject *peer;
1548 PyObject *peer_alt_names = NULL;
1549 PyObject *issuer;
1550 PyObject *version;
1551 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001552 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 ASN1_INTEGER *serialNumber;
1554 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001555 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 ASN1_TIME *notBefore, *notAfter;
1557 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 retval = PyDict_New();
1560 if (retval == NULL)
1561 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 peer = _create_tuple_for_X509_NAME(
1564 X509_get_subject_name(certificate));
1565 if (peer == NULL)
1566 goto fail0;
1567 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1568 Py_DECREF(peer);
1569 goto fail0;
1570 }
1571 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001572
Antoine Pitroufb046912010-11-09 20:21:19 +00001573 issuer = _create_tuple_for_X509_NAME(
1574 X509_get_issuer_name(certificate));
1575 if (issuer == NULL)
1576 goto fail0;
1577 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001578 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001579 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001581 Py_DECREF(issuer);
1582
1583 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001584 if (version == NULL)
1585 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001586 if (PyDict_SetItemString(retval, "version", version) < 0) {
1587 Py_DECREF(version);
1588 goto fail0;
1589 }
1590 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001591
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 /* get a memory buffer */
1593 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001594
Antoine Pitroufb046912010-11-09 20:21:19 +00001595 (void) BIO_reset(biobuf);
1596 serialNumber = X509_get_serialNumber(certificate);
1597 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1598 i2a_ASN1_INTEGER(biobuf, serialNumber);
1599 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1600 if (len < 0) {
1601 _setSSLError(NULL, 0, __FILE__, __LINE__);
1602 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001603 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001604 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1605 if (sn_obj == NULL)
1606 goto fail1;
1607 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1608 Py_DECREF(sn_obj);
1609 goto fail1;
1610 }
1611 Py_DECREF(sn_obj);
1612
1613 (void) BIO_reset(biobuf);
1614 notBefore = X509_get_notBefore(certificate);
1615 ASN1_TIME_print(biobuf, notBefore);
1616 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1617 if (len < 0) {
1618 _setSSLError(NULL, 0, __FILE__, __LINE__);
1619 goto fail1;
1620 }
1621 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1622 if (pnotBefore == NULL)
1623 goto fail1;
1624 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1625 Py_DECREF(pnotBefore);
1626 goto fail1;
1627 }
1628 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001629
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 (void) BIO_reset(biobuf);
1631 notAfter = X509_get_notAfter(certificate);
1632 ASN1_TIME_print(biobuf, notAfter);
1633 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1634 if (len < 0) {
1635 _setSSLError(NULL, 0, __FILE__, __LINE__);
1636 goto fail1;
1637 }
1638 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1639 if (pnotAfter == NULL)
1640 goto fail1;
1641 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1642 Py_DECREF(pnotAfter);
1643 goto fail1;
1644 }
1645 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001649 peer_alt_names = _get_peer_alt_names(certificate);
1650 if (peer_alt_names == NULL)
1651 goto fail1;
1652 else if (peer_alt_names != Py_None) {
1653 if (PyDict_SetItemString(retval, "subjectAltName",
1654 peer_alt_names) < 0) {
1655 Py_DECREF(peer_alt_names);
1656 goto fail1;
1657 }
1658 Py_DECREF(peer_alt_names);
1659 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001660
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001661 /* Authority Information Access: OCSP URIs */
1662 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1663 if (obj == NULL) {
1664 goto fail1;
1665 } else if (obj != Py_None) {
1666 result = PyDict_SetItemString(retval, "OCSP", obj);
1667 Py_DECREF(obj);
1668 if (result < 0) {
1669 goto fail1;
1670 }
1671 }
1672
1673 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1674 if (obj == NULL) {
1675 goto fail1;
1676 } else if (obj != Py_None) {
1677 result = PyDict_SetItemString(retval, "caIssuers", obj);
1678 Py_DECREF(obj);
1679 if (result < 0) {
1680 goto fail1;
1681 }
1682 }
1683
1684 /* CDP (CRL distribution points) */
1685 obj = _get_crl_dp(certificate);
1686 if (obj == NULL) {
1687 goto fail1;
1688 } else if (obj != Py_None) {
1689 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1690 Py_DECREF(obj);
1691 if (result < 0) {
1692 goto fail1;
1693 }
1694 }
1695
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 BIO_free(biobuf);
1697 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001698
1699 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700 if (biobuf != NULL)
1701 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001702 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001703 Py_XDECREF(retval);
1704 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001705}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001706
Christian Heimes9a5395a2013-06-17 15:44:12 +02001707static PyObject *
1708_certificate_to_der(X509 *certificate)
1709{
1710 unsigned char *bytes_buf = NULL;
1711 int len;
1712 PyObject *retval;
1713
1714 bytes_buf = NULL;
1715 len = i2d_X509(certificate, &bytes_buf);
1716 if (len < 0) {
1717 _setSSLError(NULL, 0, __FILE__, __LINE__);
1718 return NULL;
1719 }
1720 /* this is actually an immutable bytes sequence */
1721 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1722 OPENSSL_free(bytes_buf);
1723 return retval;
1724}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001725
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001726/*[clinic input]
1727_ssl._test_decode_cert
1728 path: object(converter="PyUnicode_FSConverter")
1729 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001730
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001731[clinic start generated code]*/
1732
1733static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001734_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1735/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001736{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 X509 *x=NULL;
1739 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001740
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001741 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1742 PyErr_SetString(PySSLErrorObject,
1743 "Can't malloc memory to read file");
1744 goto fail0;
1745 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001746
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001747 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 PyErr_SetString(PySSLErrorObject,
1749 "Can't open file");
1750 goto fail0;
1751 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001752
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1754 if (x == NULL) {
1755 PyErr_SetString(PySSLErrorObject,
1756 "Error decoding PEM-encoded file");
1757 goto fail0;
1758 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759
Antoine Pitroufb046912010-11-09 20:21:19 +00001760 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001761 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001762
1763 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001764 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 if (cert != NULL) BIO_free(cert);
1766 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767}
1768
1769
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001770/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001771_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001772 der as binary_mode: bool = False
1773 /
1774
1775Returns the certificate for the peer.
1776
1777If no certificate was provided, returns None. If a certificate was
1778provided, but not validated, returns an empty dictionary. Otherwise
1779returns a dict containing information about the peer certificate.
1780
1781If the optional argument is True, returns a DER-encoded copy of the
1782peer certificate, or None if no certificate was provided. This will
1783return the certificate even if it wasn't validated.
1784[clinic start generated code]*/
1785
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001786static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001787_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1788/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001789{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001791 X509 *peer_cert;
1792 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001793
Christian Heimes66dc33b2017-05-23 16:02:02 -07001794 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001795 PyErr_SetString(PyExc_ValueError,
1796 "handshake not done yet");
1797 return NULL;
1798 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001799 peer_cert = SSL_get_peer_certificate(self->ssl);
1800 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001802
Antoine Pitrou721738f2012-08-15 23:20:39 +02001803 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001805 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001807 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001809 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001810 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001811 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001812 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001813 X509_free(peer_cert);
1814 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001815}
1816
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001817static PyObject *
1818cipher_to_tuple(const SSL_CIPHER *cipher)
1819{
1820 const char *cipher_name, *cipher_protocol;
1821 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 if (retval == NULL)
1823 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001824
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001825 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001827 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 PyTuple_SET_ITEM(retval, 0, Py_None);
1829 } else {
1830 v = PyUnicode_FromString(cipher_name);
1831 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001832 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 PyTuple_SET_ITEM(retval, 0, v);
1834 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001835
1836 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001838 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 PyTuple_SET_ITEM(retval, 1, Py_None);
1840 } else {
1841 v = PyUnicode_FromString(cipher_protocol);
1842 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001843 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 PyTuple_SET_ITEM(retval, 1, v);
1845 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001846
1847 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001849 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001851
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001853
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001854 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 Py_DECREF(retval);
1856 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001857}
1858
Christian Heimes25bfcd52016-09-06 00:04:45 +02001859#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1860static PyObject *
1861cipher_to_dict(const SSL_CIPHER *cipher)
1862{
1863 const char *cipher_name, *cipher_protocol;
1864
1865 unsigned long cipher_id;
1866 int alg_bits, strength_bits, len;
1867 char buf[512] = {0};
1868#if OPENSSL_VERSION_1_1
1869 int aead, nid;
1870 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1871#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001872
1873 /* can be NULL */
1874 cipher_name = SSL_CIPHER_get_name(cipher);
1875 cipher_protocol = SSL_CIPHER_get_version(cipher);
1876 cipher_id = SSL_CIPHER_get_id(cipher);
1877 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001878 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1879 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001880 if (len > 1 && buf[len-1] == '\n')
1881 buf[len-1] = '\0';
1882 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1883
1884#if OPENSSL_VERSION_1_1
1885 aead = SSL_CIPHER_is_aead(cipher);
1886 nid = SSL_CIPHER_get_cipher_nid(cipher);
1887 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1888 nid = SSL_CIPHER_get_digest_nid(cipher);
1889 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1890 nid = SSL_CIPHER_get_kx_nid(cipher);
1891 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1892 nid = SSL_CIPHER_get_auth_nid(cipher);
1893 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1894#endif
1895
Victor Stinner410b9882016-09-12 12:00:23 +02001896 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001897 "{sksssssssisi"
1898#if OPENSSL_VERSION_1_1
1899 "sOssssssss"
1900#endif
1901 "}",
1902 "id", cipher_id,
1903 "name", cipher_name,
1904 "protocol", cipher_protocol,
1905 "description", buf,
1906 "strength_bits", strength_bits,
1907 "alg_bits", alg_bits
1908#if OPENSSL_VERSION_1_1
1909 ,"aead", aead ? Py_True : Py_False,
1910 "symmetric", skcipher,
1911 "digest", digest,
1912 "kea", kx,
1913 "auth", auth
1914#endif
1915 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001916}
1917#endif
1918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001919/*[clinic input]
1920_ssl._SSLSocket.shared_ciphers
1921[clinic start generated code]*/
1922
1923static PyObject *
1924_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1925/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001926{
1927 STACK_OF(SSL_CIPHER) *ciphers;
1928 int i;
1929 PyObject *res;
1930
Christian Heimes598894f2016-09-05 23:19:05 +02001931 ciphers = SSL_get_ciphers(self->ssl);
1932 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001933 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001934 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1935 if (!res)
1936 return NULL;
1937 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1938 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1939 if (!tup) {
1940 Py_DECREF(res);
1941 return NULL;
1942 }
1943 PyList_SET_ITEM(res, i, tup);
1944 }
1945 return res;
1946}
1947
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001948/*[clinic input]
1949_ssl._SSLSocket.cipher
1950[clinic start generated code]*/
1951
1952static PyObject *
1953_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1954/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001955{
1956 const SSL_CIPHER *current;
1957
1958 if (self->ssl == NULL)
1959 Py_RETURN_NONE;
1960 current = SSL_get_current_cipher(self->ssl);
1961 if (current == NULL)
1962 Py_RETURN_NONE;
1963 return cipher_to_tuple(current);
1964}
1965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001966/*[clinic input]
1967_ssl._SSLSocket.version
1968[clinic start generated code]*/
1969
1970static PyObject *
1971_ssl__SSLSocket_version_impl(PySSLSocket *self)
1972/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001973{
1974 const char *version;
1975
1976 if (self->ssl == NULL)
1977 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001978 if (!SSL_is_init_finished(self->ssl)) {
1979 /* handshake not finished */
1980 Py_RETURN_NONE;
1981 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001982 version = SSL_get_version(self->ssl);
1983 if (!strcmp(version, "unknown"))
1984 Py_RETURN_NONE;
1985 return PyUnicode_FromString(version);
1986}
1987
Christian Heimes29eab552018-02-25 12:31:33 +01001988#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001989/*[clinic input]
1990_ssl._SSLSocket.selected_npn_protocol
1991[clinic start generated code]*/
1992
1993static PyObject *
1994_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1995/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1996{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001997 const unsigned char *out;
1998 unsigned int outlen;
1999
Victor Stinner4569cd52013-06-23 14:58:43 +02002000 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002001 &out, &outlen);
2002
2003 if (out == NULL)
2004 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002005 return PyUnicode_FromStringAndSize((char *)out, outlen);
2006}
2007#endif
2008
Christian Heimes29eab552018-02-25 12:31:33 +01002009#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002010/*[clinic input]
2011_ssl._SSLSocket.selected_alpn_protocol
2012[clinic start generated code]*/
2013
2014static PyObject *
2015_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2016/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2017{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002018 const unsigned char *out;
2019 unsigned int outlen;
2020
2021 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2022
2023 if (out == NULL)
2024 Py_RETURN_NONE;
2025 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002026}
2027#endif
2028
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002029/*[clinic input]
2030_ssl._SSLSocket.compression
2031[clinic start generated code]*/
2032
2033static PyObject *
2034_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2035/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2036{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002037#ifdef OPENSSL_NO_COMP
2038 Py_RETURN_NONE;
2039#else
2040 const COMP_METHOD *comp_method;
2041 const char *short_name;
2042
2043 if (self->ssl == NULL)
2044 Py_RETURN_NONE;
2045 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002046 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002047 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002048 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002049 if (short_name == NULL)
2050 Py_RETURN_NONE;
2051 return PyUnicode_DecodeFSDefault(short_name);
2052#endif
2053}
2054
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002055static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2056 Py_INCREF(self->ctx);
2057 return self->ctx;
2058}
2059
2060static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2061 void *closure) {
2062
2063 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002064#if !HAVE_SNI
2065 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2066 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002067 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002068#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002069 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002070 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002071 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002072#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002073 } else {
2074 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2075 return -1;
2076 }
2077
2078 return 0;
2079}
2080
2081PyDoc_STRVAR(PySSL_set_context_doc,
2082"_setter_context(ctx)\n\
2083\
2084This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002085used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002086on the SSLContext to change the certificate information associated with the\n\
2087SSLSocket before the cryptographic exchange handshake messages\n");
2088
2089
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002090static PyObject *
2091PySSL_get_server_side(PySSLSocket *self, void *c)
2092{
2093 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2094}
2095
2096PyDoc_STRVAR(PySSL_get_server_side_doc,
2097"Whether this is a server-side socket.");
2098
2099static PyObject *
2100PySSL_get_server_hostname(PySSLSocket *self, void *c)
2101{
2102 if (self->server_hostname == NULL)
2103 Py_RETURN_NONE;
2104 Py_INCREF(self->server_hostname);
2105 return self->server_hostname;
2106}
2107
2108PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2109"The currently set server hostname (for SNI).");
2110
2111static PyObject *
2112PySSL_get_owner(PySSLSocket *self, void *c)
2113{
2114 PyObject *owner;
2115
2116 if (self->owner == NULL)
2117 Py_RETURN_NONE;
2118
2119 owner = PyWeakref_GetObject(self->owner);
2120 Py_INCREF(owner);
2121 return owner;
2122}
2123
2124static int
2125PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2126{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002127 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002128 if (self->owner == NULL)
2129 return -1;
2130 return 0;
2131}
2132
2133PyDoc_STRVAR(PySSL_get_owner_doc,
2134"The Python-level owner of this object.\
2135Passed as \"self\" in servername callback.");
2136
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002137
Antoine Pitrou152efa22010-05-16 18:19:27 +00002138static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002139{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 if (self->ssl)
2141 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002143 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002144 Py_XDECREF(self->server_hostname);
2145 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002147}
2148
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002149/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002150 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002151 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002152 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002153
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002154static int
Victor Stinner14690702015-04-06 22:46:13 +02002155PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002156{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002157 int rc;
2158#ifdef HAVE_POLL
2159 struct pollfd pollfd;
2160 _PyTime_t ms;
2161#else
2162 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 fd_set fds;
2164 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002165#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002168 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002169 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002170 else if (timeout < 0) {
2171 if (s->sock_timeout > 0)
2172 return SOCKET_HAS_TIMED_OUT;
2173 else
2174 return SOCKET_IS_BLOCKING;
2175 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002178 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 /* Prefer poll, if available, since you can poll() any fd
2182 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002183#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002184 pollfd.fd = s->sock_fd;
2185 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002186
Victor Stinner14690702015-04-06 22:46:13 +02002187 /* timeout is in seconds, poll() uses milliseconds */
2188 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002189 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002190
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002191 PySSL_BEGIN_ALLOW_THREADS
2192 rc = poll(&pollfd, 1, (int)ms);
2193 PySSL_END_ALLOW_THREADS
2194#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002196 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002197 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002198
Victor Stinner14690702015-04-06 22:46:13 +02002199 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002200
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002201 FD_ZERO(&fds);
2202 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002203
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002204 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002208 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002210 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002212#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2215 (when we are able to write or when there's something to read) */
2216 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002217}
2218
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002219/*[clinic input]
2220_ssl._SSLSocket.write
2221 b: Py_buffer
2222 /
2223
2224Writes the bytes-like object b into the SSL object.
2225
2226Returns the number of bytes written.
2227[clinic start generated code]*/
2228
2229static PyObject *
2230_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2231/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002232{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 int len;
2234 int sockstate;
2235 int err;
2236 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002237 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002238 _PyTime_t timeout, deadline = 0;
2239 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002240
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002241 if (sock != NULL) {
2242 if (((PyObject*)sock) == Py_None) {
2243 _setSSLError("Underlying socket connection gone",
2244 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2245 return NULL;
2246 }
2247 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 }
2249
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002250 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002251 PyErr_Format(PyExc_OverflowError,
2252 "string longer than %d bytes", INT_MAX);
2253 goto error;
2254 }
2255
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002256 if (sock != NULL) {
2257 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002258 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002259 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2260 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2261 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262
Victor Stinner14690702015-04-06 22:46:13 +02002263 timeout = GET_SOCKET_TIMEOUT(sock);
2264 has_timeout = (timeout > 0);
2265 if (has_timeout)
2266 deadline = _PyTime_GetMonotonicClock() + timeout;
2267
2268 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002270 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 "The write operation timed out");
2272 goto error;
2273 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2274 PyErr_SetString(PySSLErrorObject,
2275 "Underlying socket has been closed.");
2276 goto error;
2277 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2278 PyErr_SetString(PySSLErrorObject,
2279 "Underlying socket too large for select().");
2280 goto error;
2281 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002282
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002285 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002286 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002288 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002289
2290 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002292
Victor Stinner14690702015-04-06 22:46:13 +02002293 if (has_timeout)
2294 timeout = deadline - _PyTime_GetMonotonicClock();
2295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002297 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002299 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 } else {
2301 sockstate = SOCKET_OPERATION_OK;
2302 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002303
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002305 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002306 "The write operation timed out");
2307 goto error;
2308 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2309 PyErr_SetString(PySSLErrorObject,
2310 "Underlying socket has been closed.");
2311 goto error;
2312 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2313 break;
2314 }
2315 } while (err == SSL_ERROR_WANT_READ || err == 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;
Bill Janssen6e027db2007-11-15 22:23:56 +00002339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 PySSL_BEGIN_ALLOW_THREADS
2341 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002342 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 PySSL_END_ALLOW_THREADS
2344 if (count < 0)
2345 return PySSL_SetError(self, count, __FILE__, __LINE__);
2346 else
2347 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002348}
2349
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002350/*[clinic input]
2351_ssl._SSLSocket.read
2352 size as len: int
2353 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002354 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002355 ]
2356 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002357
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002358Read up to size bytes from the SSL socket.
2359[clinic start generated code]*/
2360
2361static PyObject *
2362_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2363 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002364/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002365{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002367 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002368 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002369 int sockstate;
2370 int err;
2371 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002372 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002373 _PyTime_t timeout, deadline = 0;
2374 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002375
Martin Panter5503d472016-03-27 05:35:19 +00002376 if (!group_right_1 && len < 0) {
2377 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2378 return NULL;
2379 }
2380
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002381 if (sock != NULL) {
2382 if (((PyObject*)sock) == Py_None) {
2383 _setSSLError("Underlying socket connection gone",
2384 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2385 return NULL;
2386 }
2387 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 }
2389
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002390 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002391 dest = PyBytes_FromStringAndSize(NULL, len);
2392 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002393 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002394 if (len == 0) {
2395 Py_XDECREF(sock);
2396 return dest;
2397 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002398 mem = PyBytes_AS_STRING(dest);
2399 }
2400 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002401 mem = buffer->buf;
2402 if (len <= 0 || len > buffer->len) {
2403 len = (int) buffer->len;
2404 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002405 PyErr_SetString(PyExc_OverflowError,
2406 "maximum length can't fit in a C 'int'");
2407 goto error;
2408 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002409 if (len == 0) {
2410 count = 0;
2411 goto done;
2412 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002413 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002414 }
2415
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002416 if (sock != NULL) {
2417 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002418 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002419 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2420 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2421 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002422
Victor Stinner14690702015-04-06 22:46:13 +02002423 timeout = GET_SOCKET_TIMEOUT(sock);
2424 has_timeout = (timeout > 0);
2425 if (has_timeout)
2426 deadline = _PyTime_GetMonotonicClock() + timeout;
2427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002429 PySSL_BEGIN_ALLOW_THREADS
2430 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002431 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002434 if (PyErr_CheckSignals())
2435 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002436
Victor Stinner14690702015-04-06 22:46:13 +02002437 if (has_timeout)
2438 timeout = deadline - _PyTime_GetMonotonicClock();
2439
Steve Dowere6eb48c2017-09-08 15:16:15 -07002440 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002441 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002442 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002444 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002445 } else if (err == SSL_ERROR_ZERO_RETURN &&
2446 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 {
2448 count = 0;
2449 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002451 else
2452 sockstate = SOCKET_OPERATION_OK;
2453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002454 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002455 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002456 "The read operation timed out");
2457 goto error;
2458 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2459 break;
2460 }
2461 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002462
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002463 if (count <= 0) {
2464 PySSL_SetError(self, count, __FILE__, __LINE__);
2465 goto error;
2466 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002467
2468done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002469 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002470 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002471 _PyBytes_Resize(&dest, count);
2472 return dest;
2473 }
2474 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 return PyLong_FromLong(count);
2476 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002477
2478error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002479 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002480 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002481 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002482 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002483}
2484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002485/*[clinic input]
2486_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002488Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002489[clinic start generated code]*/
2490
2491static PyObject *
2492_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002493/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002494{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002495 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002497 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002498 _PyTime_t timeout, deadline = 0;
2499 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002500
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002501 if (sock != NULL) {
2502 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002503 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002504 _setSSLError("Underlying socket connection gone",
2505 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2506 return NULL;
2507 }
2508 Py_INCREF(sock);
2509
2510 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002511 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002512 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2513 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002514 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002515
Victor Stinner14690702015-04-06 22:46:13 +02002516 timeout = GET_SOCKET_TIMEOUT(sock);
2517 has_timeout = (timeout > 0);
2518 if (has_timeout)
2519 deadline = _PyTime_GetMonotonicClock() + timeout;
2520
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 while (1) {
2522 PySSL_BEGIN_ALLOW_THREADS
2523 /* Disable read-ahead so that unwrap can work correctly.
2524 * Otherwise OpenSSL might read in too much data,
2525 * eating clear text data that happens to be
2526 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002527 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002528 * function is used and the shutdown_seen_zero != 0
2529 * condition is met.
2530 */
2531 if (self->shutdown_seen_zero)
2532 SSL_set_read_ahead(self->ssl, 0);
2533 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002534 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002535 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002537 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2538 if (err > 0)
2539 break;
2540 if (err == 0) {
2541 /* Don't loop endlessly; instead preserve legacy
2542 behaviour of trying SSL_shutdown() only twice.
2543 This looks necessary for OpenSSL < 0.9.8m */
2544 if (++zeros > 1)
2545 break;
2546 /* Shutdown was sent, now try receiving */
2547 self->shutdown_seen_zero = 1;
2548 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002549 }
2550
Victor Stinner14690702015-04-06 22:46:13 +02002551 if (has_timeout)
2552 timeout = deadline - _PyTime_GetMonotonicClock();
2553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002554 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002555 _PySSL_UPDATE_ERRNO(self, err);
2556 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002557 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002558 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002559 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 else
2561 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002564 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002565 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002566 "The read operation timed out");
2567 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002568 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002569 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002570 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 }
2572 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2573 PyErr_SetString(PySSLErrorObject,
2574 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002575 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002576 }
2577 else if (sockstate != SOCKET_OPERATION_OK)
2578 /* Retain the SSL error code */
2579 break;
2580 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002581
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002582 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002583 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002586 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002587 /* It's already INCREF'ed */
2588 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002589 else
2590 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002591
2592error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002593 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002594 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002595}
2596
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002597/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002598_ssl._SSLSocket.get_channel_binding
2599 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002600
Christian Heimes141c5e82018-02-24 21:10:57 +01002601Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002602
Christian Heimes141c5e82018-02-24 21:10:57 +01002603Raise ValueError if the requested `cb_type` is not supported. Return bytes
2604of the data or None if the data is not available (e.g. before the handshake).
2605Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002606[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002607
Antoine Pitroud6494802011-07-21 01:11:30 +02002608static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002609_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2610 const char *cb_type)
2611/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002612{
Antoine Pitroud6494802011-07-21 01:11:30 +02002613 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002614 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002615
Christian Heimes141c5e82018-02-24 21:10:57 +01002616 if (strcmp(cb_type, "tls-unique") == 0) {
2617 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2618 /* if session is resumed XOR we are the client */
2619 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2620 }
2621 else {
2622 /* if a new session XOR we are the server */
2623 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2624 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002625 }
2626 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002627 PyErr_Format(
2628 PyExc_ValueError,
2629 "'%s' channel binding type not implemented",
2630 cb_type
2631 );
2632 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002633 }
2634
2635 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002636 if (len == 0)
2637 Py_RETURN_NONE;
2638
Christian Heimes141c5e82018-02-24 21:10:57 +01002639 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002640}
2641
Christian Heimes99a65702016-09-10 23:44:53 +02002642#ifdef OPENSSL_VERSION_1_1
2643
2644static SSL_SESSION*
2645_ssl_session_dup(SSL_SESSION *session) {
2646 SSL_SESSION *newsession = NULL;
2647 int slen;
2648 unsigned char *senc = NULL, *p;
2649 const unsigned char *const_p;
2650
2651 if (session == NULL) {
2652 PyErr_SetString(PyExc_ValueError, "Invalid session");
2653 goto error;
2654 }
2655
2656 /* get length */
2657 slen = i2d_SSL_SESSION(session, NULL);
2658 if (slen == 0 || slen > 0xFF00) {
2659 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2660 goto error;
2661 }
2662 if ((senc = PyMem_Malloc(slen)) == NULL) {
2663 PyErr_NoMemory();
2664 goto error;
2665 }
2666 p = senc;
2667 if (!i2d_SSL_SESSION(session, &p)) {
2668 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2669 goto error;
2670 }
2671 const_p = senc;
2672 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2673 if (session == NULL) {
2674 goto error;
2675 }
2676 PyMem_Free(senc);
2677 return newsession;
2678 error:
2679 if (senc != NULL) {
2680 PyMem_Free(senc);
2681 }
2682 return NULL;
2683}
2684#endif
2685
2686static PyObject *
2687PySSL_get_session(PySSLSocket *self, void *closure) {
2688 /* get_session can return sessions from a server-side connection,
2689 * it does not check for handshake done or client socket. */
2690 PySSLSession *pysess;
2691 SSL_SESSION *session;
2692
2693#ifdef OPENSSL_VERSION_1_1
2694 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2695 * https://github.com/openssl/openssl/issues/1550 */
2696 session = SSL_get0_session(self->ssl); /* borrowed reference */
2697 if (session == NULL) {
2698 Py_RETURN_NONE;
2699 }
2700 if ((session = _ssl_session_dup(session)) == NULL) {
2701 return NULL;
2702 }
2703#else
2704 session = SSL_get1_session(self->ssl);
2705 if (session == NULL) {
2706 Py_RETURN_NONE;
2707 }
2708#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002709 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002710 if (pysess == NULL) {
2711 SSL_SESSION_free(session);
2712 return NULL;
2713 }
2714
2715 assert(self->ctx);
2716 pysess->ctx = self->ctx;
2717 Py_INCREF(pysess->ctx);
2718 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002719 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002720 return (PyObject *)pysess;
2721}
2722
2723static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2724 void *closure)
2725 {
2726 PySSLSession *pysess;
2727#ifdef OPENSSL_VERSION_1_1
2728 SSL_SESSION *session;
2729#endif
2730 int result;
2731
2732 if (!PySSLSession_Check(value)) {
2733 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2734 return -1;
2735 }
2736 pysess = (PySSLSession *)value;
2737
2738 if (self->ctx->ctx != pysess->ctx->ctx) {
2739 PyErr_SetString(PyExc_ValueError,
2740 "Session refers to a different SSLContext.");
2741 return -1;
2742 }
2743 if (self->socket_type != PY_SSL_CLIENT) {
2744 PyErr_SetString(PyExc_ValueError,
2745 "Cannot set session for server-side SSLSocket.");
2746 return -1;
2747 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002748 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002749 PyErr_SetString(PyExc_ValueError,
2750 "Cannot set session after handshake.");
2751 return -1;
2752 }
2753#ifdef OPENSSL_VERSION_1_1
2754 /* duplicate session */
2755 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2756 return -1;
2757 }
2758 result = SSL_set_session(self->ssl, session);
2759 /* free duplicate, SSL_set_session() bumps ref count */
2760 SSL_SESSION_free(session);
2761#else
2762 result = SSL_set_session(self->ssl, pysess->session);
2763#endif
2764 if (result == 0) {
2765 _setSSLError(NULL, 0, __FILE__, __LINE__);
2766 return -1;
2767 }
2768 return 0;
2769}
2770
2771PyDoc_STRVAR(PySSL_set_session_doc,
2772"_setter_session(session)\n\
2773\
2774Get / set SSLSession.");
2775
2776static PyObject *
2777PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2778 if (SSL_session_reused(self->ssl)) {
2779 Py_RETURN_TRUE;
2780 } else {
2781 Py_RETURN_FALSE;
2782 }
2783}
2784
2785PyDoc_STRVAR(PySSL_get_session_reused_doc,
2786"Was the client session reused during handshake?");
2787
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002788static PyGetSetDef ssl_getsetlist[] = {
2789 {"context", (getter) PySSL_get_context,
2790 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002791 {"server_side", (getter) PySSL_get_server_side, NULL,
2792 PySSL_get_server_side_doc},
2793 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2794 PySSL_get_server_hostname_doc},
2795 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2796 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002797 {"session", (getter) PySSL_get_session,
2798 (setter) PySSL_set_session, PySSL_set_session_doc},
2799 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2800 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002801 {NULL}, /* sentinel */
2802};
2803
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002804static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002805 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2806 _SSL__SSLSOCKET_WRITE_METHODDEF
2807 _SSL__SSLSOCKET_READ_METHODDEF
2808 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002809 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2810 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002811 _SSL__SSLSOCKET_CIPHER_METHODDEF
2812 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2813 _SSL__SSLSOCKET_VERSION_METHODDEF
2814 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2815 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2816 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2817 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002818 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002819};
2820
Antoine Pitrou152efa22010-05-16 18:19:27 +00002821static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002822 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002823 "_ssl._SSLSocket", /*tp_name*/
2824 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002825 0, /*tp_itemsize*/
2826 /* methods */
2827 (destructor)PySSL_dealloc, /*tp_dealloc*/
2828 0, /*tp_print*/
2829 0, /*tp_getattr*/
2830 0, /*tp_setattr*/
2831 0, /*tp_reserved*/
2832 0, /*tp_repr*/
2833 0, /*tp_as_number*/
2834 0, /*tp_as_sequence*/
2835 0, /*tp_as_mapping*/
2836 0, /*tp_hash*/
2837 0, /*tp_call*/
2838 0, /*tp_str*/
2839 0, /*tp_getattro*/
2840 0, /*tp_setattro*/
2841 0, /*tp_as_buffer*/
2842 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2843 0, /*tp_doc*/
2844 0, /*tp_traverse*/
2845 0, /*tp_clear*/
2846 0, /*tp_richcompare*/
2847 0, /*tp_weaklistoffset*/
2848 0, /*tp_iter*/
2849 0, /*tp_iternext*/
2850 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002851 0, /*tp_members*/
2852 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002853};
2854
Antoine Pitrou152efa22010-05-16 18:19:27 +00002855
2856/*
2857 * _SSLContext objects
2858 */
2859
Christian Heimes5fe668c2016-09-12 00:01:11 +02002860static int
2861_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2862{
2863 int mode;
2864 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2865
2866 switch(n) {
2867 case PY_SSL_CERT_NONE:
2868 mode = SSL_VERIFY_NONE;
2869 break;
2870 case PY_SSL_CERT_OPTIONAL:
2871 mode = SSL_VERIFY_PEER;
2872 break;
2873 case PY_SSL_CERT_REQUIRED:
2874 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2875 break;
2876 default:
2877 PyErr_SetString(PyExc_ValueError,
2878 "invalid value for verify_mode");
2879 return -1;
2880 }
2881 /* keep current verify cb */
2882 verify_cb = SSL_CTX_get_verify_callback(ctx);
2883 SSL_CTX_set_verify(ctx, mode, verify_cb);
2884 return 0;
2885}
2886
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002887/*[clinic input]
2888@classmethod
2889_ssl._SSLContext.__new__
2890 protocol as proto_version: int
2891 /
2892[clinic start generated code]*/
2893
Antoine Pitrou152efa22010-05-16 18:19:27 +00002894static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002895_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2896/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002898 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002899 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002900 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002901 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002902 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002903#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002904 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002905#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002906
Antoine Pitrou152efa22010-05-16 18:19:27 +00002907 PySSL_BEGIN_ALLOW_THREADS
2908 if (proto_version == PY_SSL_VERSION_TLS1)
2909 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002910#if HAVE_TLSv1_2
2911 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2912 ctx = SSL_CTX_new(TLSv1_1_method());
2913 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2914 ctx = SSL_CTX_new(TLSv1_2_method());
2915#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002916#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002917 else if (proto_version == PY_SSL_VERSION_SSL3)
2918 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002919#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002920#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002921 else if (proto_version == PY_SSL_VERSION_SSL2)
2922 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002923#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002924 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002925 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002926 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2927 ctx = SSL_CTX_new(TLS_client_method());
2928 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2929 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002930 else
2931 proto_version = -1;
2932 PySSL_END_ALLOW_THREADS
2933
2934 if (proto_version == -1) {
2935 PyErr_SetString(PyExc_ValueError,
2936 "invalid protocol version");
2937 return NULL;
2938 }
2939 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002940 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002941 return NULL;
2942 }
2943
2944 assert(type != NULL && type->tp_alloc != NULL);
2945 self = (PySSLContext *) type->tp_alloc(type, 0);
2946 if (self == NULL) {
2947 SSL_CTX_free(ctx);
2948 return NULL;
2949 }
2950 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002951 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002952 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002953#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002954 self->npn_protocols = NULL;
2955#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002956#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002957 self->alpn_protocols = NULL;
2958#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002959#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002960 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002961#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002962 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002963 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2964 self->check_hostname = 1;
2965 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2966 Py_DECREF(self);
2967 return NULL;
2968 }
2969 } else {
2970 self->check_hostname = 0;
2971 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2972 Py_DECREF(self);
2973 return NULL;
2974 }
2975 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002976 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002977 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2978 if (proto_version != PY_SSL_VERSION_SSL2)
2979 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002980 if (proto_version != PY_SSL_VERSION_SSL3)
2981 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002982 /* Minimal security flags for server and client side context.
2983 * Client sockets ignore server-side parameters. */
2984#ifdef SSL_OP_NO_COMPRESSION
2985 options |= SSL_OP_NO_COMPRESSION;
2986#endif
2987#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2988 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2989#endif
2990#ifdef SSL_OP_SINGLE_DH_USE
2991 options |= SSL_OP_SINGLE_DH_USE;
2992#endif
2993#ifdef SSL_OP_SINGLE_ECDH_USE
2994 options |= SSL_OP_SINGLE_ECDH_USE;
2995#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002996 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002997
Semen Zhydenko1295e112017-10-15 21:28:31 +02002998 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002999 * It's far from perfect but gives users a better head start. */
3000 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003001#if PY_SSL_DEFAULT_CIPHERS == 2
3002 /* stick to OpenSSL's default settings */
3003 result = 1;
3004#else
3005 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3006#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003007 } else {
3008 /* SSLv2 needs MD5 */
3009 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3010 }
3011 if (result == 0) {
3012 Py_DECREF(self);
3013 ERR_clear_error();
3014 PyErr_SetString(PySSLErrorObject,
3015 "No cipher can be selected.");
3016 return NULL;
3017 }
3018
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003019#if defined(SSL_MODE_RELEASE_BUFFERS)
3020 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3021 usage for no cost at all. However, don't do this for OpenSSL versions
3022 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3023 2014-0198. I can't find exactly which beta fixed this CVE, so be
3024 conservative and assume it wasn't fixed until release. We do this check
3025 at runtime to avoid problems from the dynamic linker.
3026 See #25672 for more on this. */
3027 libver = SSLeay();
3028 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3029 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3030 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3031 }
3032#endif
3033
3034
Donald Stufft8ae264c2017-03-02 11:45:29 -05003035#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003036 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3037 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003038 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3039 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003040#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003041 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3042#else
3043 {
3044 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3045 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3046 EC_KEY_free(key);
3047 }
3048#endif
3049#endif
3050
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003051#define SID_CTX "Python"
3052 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3053 sizeof(SID_CTX));
3054#undef SID_CTX
3055
Christian Heimes61d478c2018-01-27 15:51:38 +01003056 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003057#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003058 /* Improve trust chain building when cross-signed intermediate
3059 certificates are present. See https://bugs.python.org/issue23476. */
3060 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003061#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003062 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003063
Antoine Pitrou152efa22010-05-16 18:19:27 +00003064 return (PyObject *)self;
3065}
3066
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003067static int
3068context_traverse(PySSLContext *self, visitproc visit, void *arg)
3069{
3070#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003071 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003072#endif
3073 return 0;
3074}
3075
3076static int
3077context_clear(PySSLContext *self)
3078{
3079#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003080 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003081#endif
3082 return 0;
3083}
3084
Antoine Pitrou152efa22010-05-16 18:19:27 +00003085static void
3086context_dealloc(PySSLContext *self)
3087{
INADA Naokia6296d32017-08-24 14:55:17 +09003088 /* bpo-31095: UnTrack is needed before calling any callbacks */
3089 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003090 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003092#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003093 PyMem_FREE(self->npn_protocols);
3094#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003095#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003096 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003097#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003098 Py_TYPE(self)->tp_free(self);
3099}
3100
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003101/*[clinic input]
3102_ssl._SSLContext.set_ciphers
3103 cipherlist: str
3104 /
3105[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003106
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003107static PyObject *
3108_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3109/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3110{
3111 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003112 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003113 /* Clearing the error queue is necessary on some OpenSSL versions,
3114 otherwise the error will be reported again when another SSL call
3115 is done. */
3116 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003117 PyErr_SetString(PySSLErrorObject,
3118 "No cipher can be selected.");
3119 return NULL;
3120 }
3121 Py_RETURN_NONE;
3122}
3123
Christian Heimes25bfcd52016-09-06 00:04:45 +02003124#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3125/*[clinic input]
3126_ssl._SSLContext.get_ciphers
3127[clinic start generated code]*/
3128
3129static PyObject *
3130_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3131/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3132{
3133 SSL *ssl = NULL;
3134 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003135 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003136 int i=0;
3137 PyObject *result = NULL, *dct;
3138
3139 ssl = SSL_new(self->ctx);
3140 if (ssl == NULL) {
3141 _setSSLError(NULL, 0, __FILE__, __LINE__);
3142 goto exit;
3143 }
3144 sk = SSL_get_ciphers(ssl);
3145
3146 result = PyList_New(sk_SSL_CIPHER_num(sk));
3147 if (result == NULL) {
3148 goto exit;
3149 }
3150
3151 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3152 cipher = sk_SSL_CIPHER_value(sk, i);
3153 dct = cipher_to_dict(cipher);
3154 if (dct == NULL) {
3155 Py_CLEAR(result);
3156 goto exit;
3157 }
3158 PyList_SET_ITEM(result, i, dct);
3159 }
3160
3161 exit:
3162 if (ssl != NULL)
3163 SSL_free(ssl);
3164 return result;
3165
3166}
3167#endif
3168
3169
Christian Heimes29eab552018-02-25 12:31:33 +01003170#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003171static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003172do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3173 const unsigned char *server_protocols, unsigned int server_protocols_len,
3174 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003175{
Benjamin Peterson88615022015-01-23 17:30:26 -05003176 int ret;
3177 if (client_protocols == NULL) {
3178 client_protocols = (unsigned char *)"";
3179 client_protocols_len = 0;
3180 }
3181 if (server_protocols == NULL) {
3182 server_protocols = (unsigned char *)"";
3183 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003184 }
3185
Benjamin Peterson88615022015-01-23 17:30:26 -05003186 ret = SSL_select_next_proto(out, outlen,
3187 server_protocols, server_protocols_len,
3188 client_protocols, client_protocols_len);
3189 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3190 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003191
3192 return SSL_TLSEXT_ERR_OK;
3193}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003194#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003195
Christian Heimes29eab552018-02-25 12:31:33 +01003196#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003197/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3198static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003199_advertiseNPN_cb(SSL *s,
3200 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003201 void *args)
3202{
3203 PySSLContext *ssl_ctx = (PySSLContext *) args;
3204
3205 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003206 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003207 *len = 0;
3208 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003209 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003210 *len = ssl_ctx->npn_protocols_len;
3211 }
3212
3213 return SSL_TLSEXT_ERR_OK;
3214}
3215/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3216static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003217_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003218 unsigned char **out, unsigned char *outlen,
3219 const unsigned char *server, unsigned int server_len,
3220 void *args)
3221{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003222 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003223 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003224 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003225}
3226#endif
3227
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003228/*[clinic input]
3229_ssl._SSLContext._set_npn_protocols
3230 protos: Py_buffer
3231 /
3232[clinic start generated code]*/
3233
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003234static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003235_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3236 Py_buffer *protos)
3237/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003238{
Christian Heimes29eab552018-02-25 12:31:33 +01003239#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240 PyMem_Free(self->npn_protocols);
3241 self->npn_protocols = PyMem_Malloc(protos->len);
3242 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003243 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003244 memcpy(self->npn_protocols, protos->buf, protos->len);
3245 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003246
3247 /* set both server and client callbacks, because the context can
3248 * be used to create both types of sockets */
3249 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3250 _advertiseNPN_cb,
3251 self);
3252 SSL_CTX_set_next_proto_select_cb(self->ctx,
3253 _selectNPN_cb,
3254 self);
3255
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003256 Py_RETURN_NONE;
3257#else
3258 PyErr_SetString(PyExc_NotImplementedError,
3259 "The NPN extension requires OpenSSL 1.0.1 or later.");
3260 return NULL;
3261#endif
3262}
3263
Christian Heimes29eab552018-02-25 12:31:33 +01003264#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003265static int
3266_selectALPN_cb(SSL *s,
3267 const unsigned char **out, unsigned char *outlen,
3268 const unsigned char *client_protocols, unsigned int client_protocols_len,
3269 void *args)
3270{
3271 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003272 return do_protocol_selection(1, (unsigned char **)out, outlen,
3273 ctx->alpn_protocols, ctx->alpn_protocols_len,
3274 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003275}
3276#endif
3277
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003278/*[clinic input]
3279_ssl._SSLContext._set_alpn_protocols
3280 protos: Py_buffer
3281 /
3282[clinic start generated code]*/
3283
Benjamin Petersoncca27322015-01-23 16:35:37 -05003284static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003285_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3286 Py_buffer *protos)
3287/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003288{
Christian Heimes29eab552018-02-25 12:31:33 +01003289#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003290 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003291 PyErr_Format(PyExc_OverflowError,
3292 "protocols longer than %d bytes", UINT_MAX);
3293 return NULL;
3294 }
3295
Benjamin Petersoncca27322015-01-23 16:35:37 -05003296 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003297 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003298 if (!self->alpn_protocols)
3299 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003300 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003301 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003302
3303 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3304 return PyErr_NoMemory();
3305 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3306
Benjamin Petersoncca27322015-01-23 16:35:37 -05003307 Py_RETURN_NONE;
3308#else
3309 PyErr_SetString(PyExc_NotImplementedError,
3310 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3311 return NULL;
3312#endif
3313}
3314
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315static PyObject *
3316get_verify_mode(PySSLContext *self, void *c)
3317{
3318 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3319 case SSL_VERIFY_NONE:
3320 return PyLong_FromLong(PY_SSL_CERT_NONE);
3321 case SSL_VERIFY_PEER:
3322 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3323 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3324 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3325 }
3326 PyErr_SetString(PySSLErrorObject,
3327 "invalid return value from SSL_CTX_get_verify_mode");
3328 return NULL;
3329}
3330
3331static int
3332set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3333{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003334 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003335 if (!PyArg_Parse(arg, "i", &n))
3336 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003337 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003338 PyErr_SetString(PyExc_ValueError,
3339 "Cannot set verify_mode to CERT_NONE when "
3340 "check_hostname is enabled.");
3341 return -1;
3342 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003343 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003344}
3345
3346static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003347get_verify_flags(PySSLContext *self, void *c)
3348{
Christian Heimes598894f2016-09-05 23:19:05 +02003349 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003350 unsigned long flags;
3351
Christian Heimes61d478c2018-01-27 15:51:38 +01003352 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003353 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003354 return PyLong_FromUnsignedLong(flags);
3355}
3356
3357static int
3358set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3359{
Christian Heimes598894f2016-09-05 23:19:05 +02003360 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003361 unsigned long new_flags, flags, set, clear;
3362
3363 if (!PyArg_Parse(arg, "k", &new_flags))
3364 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003365 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003366 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003367 clear = flags & ~new_flags;
3368 set = ~flags & new_flags;
3369 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003370 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003371 _setSSLError(NULL, 0, __FILE__, __LINE__);
3372 return -1;
3373 }
3374 }
3375 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003376 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003377 _setSSLError(NULL, 0, __FILE__, __LINE__);
3378 return -1;
3379 }
3380 }
3381 return 0;
3382}
3383
Christian Heimes698dde12018-02-27 11:54:43 +01003384/* Getter and setter for protocol version */
3385#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3386
3387
3388static int
3389set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3390{
3391 long v;
3392 int result;
3393
3394 if (!PyArg_Parse(arg, "l", &v))
3395 return -1;
3396 if (v > INT_MAX) {
3397 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3398 return -1;
3399 }
3400
3401 switch(self->protocol) {
3402 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3403 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3404 case PY_SSL_VERSION_TLS:
3405 break;
3406 default:
3407 PyErr_SetString(
3408 PyExc_ValueError,
3409 "The context's protocol doesn't support modification of "
3410 "highest and lowest version."
3411 );
3412 return -1;
3413 }
3414
3415 if (what == 0) {
3416 switch(v) {
3417 case PY_PROTO_MINIMUM_SUPPORTED:
3418 v = 0;
3419 break;
3420 case PY_PROTO_MAXIMUM_SUPPORTED:
3421 /* Emulate max for set_min_proto_version */
3422 v = PY_PROTO_MAXIMUM_AVAILABLE;
3423 break;
3424 default:
3425 break;
3426 }
3427 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3428 }
3429 else {
3430 switch(v) {
3431 case PY_PROTO_MAXIMUM_SUPPORTED:
3432 v = 0;
3433 break;
3434 case PY_PROTO_MINIMUM_SUPPORTED:
3435 /* Emulate max for set_min_proto_version */
3436 v = PY_PROTO_MINIMUM_AVAILABLE;
3437 break;
3438 default:
3439 break;
3440 }
3441 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3442 }
3443 if (result == 0) {
3444 PyErr_Format(PyExc_ValueError,
3445 "Unsupported protocol version 0x%x", v);
3446 return -1;
3447 }
3448 return 0;
3449}
3450
3451static PyObject *
3452get_minimum_version(PySSLContext *self, void *c)
3453{
3454 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3455 if (v == 0) {
3456 v = PY_PROTO_MINIMUM_SUPPORTED;
3457 }
3458 return PyLong_FromLong(v);
3459}
3460
3461static int
3462set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3463{
3464 return set_min_max_proto_version(self, arg, 0);
3465}
3466
3467static PyObject *
3468get_maximum_version(PySSLContext *self, void *c)
3469{
3470 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3471 if (v == 0) {
3472 v = PY_PROTO_MAXIMUM_SUPPORTED;
3473 }
3474 return PyLong_FromLong(v);
3475}
3476
3477static int
3478set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3479{
3480 return set_min_max_proto_version(self, arg, 1);
3481}
3482#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3483
Christian Heimes22587792013-11-21 23:56:13 +01003484static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003485get_options(PySSLContext *self, void *c)
3486{
3487 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3488}
3489
3490static int
3491set_options(PySSLContext *self, PyObject *arg, void *c)
3492{
3493 long new_opts, opts, set, clear;
3494 if (!PyArg_Parse(arg, "l", &new_opts))
3495 return -1;
3496 opts = SSL_CTX_get_options(self->ctx);
3497 clear = opts & ~new_opts;
3498 set = ~opts & new_opts;
3499 if (clear) {
3500#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3501 SSL_CTX_clear_options(self->ctx, clear);
3502#else
3503 PyErr_SetString(PyExc_ValueError,
3504 "can't clear options before OpenSSL 0.9.8m");
3505 return -1;
3506#endif
3507 }
3508 if (set)
3509 SSL_CTX_set_options(self->ctx, set);
3510 return 0;
3511}
3512
Christian Heimes1aa9a752013-12-02 02:41:19 +01003513static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003514get_host_flags(PySSLContext *self, void *c)
3515{
3516 return PyLong_FromUnsignedLong(self->hostflags);
3517}
3518
3519static int
3520set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3521{
3522 X509_VERIFY_PARAM *param;
3523 unsigned int new_flags = 0;
3524
3525 if (!PyArg_Parse(arg, "I", &new_flags))
3526 return -1;
3527
3528 param = SSL_CTX_get0_param(self->ctx);
3529 self->hostflags = new_flags;
3530 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3531 return 0;
3532}
3533
3534static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003535get_check_hostname(PySSLContext *self, void *c)
3536{
3537 return PyBool_FromLong(self->check_hostname);
3538}
3539
3540static int
3541set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3542{
3543 int check_hostname;
3544 if (!PyArg_Parse(arg, "p", &check_hostname))
3545 return -1;
3546 if (check_hostname &&
3547 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003548 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3549 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3550 return -1;
3551 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003552 }
3553 self->check_hostname = check_hostname;
3554 return 0;
3555}
3556
Christian Heimes11a14932018-02-24 02:35:08 +01003557static PyObject *
3558get_protocol(PySSLContext *self, void *c) {
3559 return PyLong_FromLong(self->protocol);
3560}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003561
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003562typedef struct {
3563 PyThreadState *thread_state;
3564 PyObject *callable;
3565 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003566 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003567 int error;
3568} _PySSLPasswordInfo;
3569
3570static int
3571_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3572 const char *bad_type_error)
3573{
3574 /* Set the password and size fields of a _PySSLPasswordInfo struct
3575 from a unicode, bytes, or byte array object.
3576 The password field will be dynamically allocated and must be freed
3577 by the caller */
3578 PyObject *password_bytes = NULL;
3579 const char *data = NULL;
3580 Py_ssize_t size;
3581
3582 if (PyUnicode_Check(password)) {
3583 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3584 if (!password_bytes) {
3585 goto error;
3586 }
3587 data = PyBytes_AS_STRING(password_bytes);
3588 size = PyBytes_GET_SIZE(password_bytes);
3589 } else if (PyBytes_Check(password)) {
3590 data = PyBytes_AS_STRING(password);
3591 size = PyBytes_GET_SIZE(password);
3592 } else if (PyByteArray_Check(password)) {
3593 data = PyByteArray_AS_STRING(password);
3594 size = PyByteArray_GET_SIZE(password);
3595 } else {
3596 PyErr_SetString(PyExc_TypeError, bad_type_error);
3597 goto error;
3598 }
3599
Victor Stinner9ee02032013-06-23 15:08:23 +02003600 if (size > (Py_ssize_t)INT_MAX) {
3601 PyErr_Format(PyExc_ValueError,
3602 "password cannot be longer than %d bytes", INT_MAX);
3603 goto error;
3604 }
3605
Victor Stinner11ebff22013-07-07 17:07:52 +02003606 PyMem_Free(pw_info->password);
3607 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003608 if (!pw_info->password) {
3609 PyErr_SetString(PyExc_MemoryError,
3610 "unable to allocate password buffer");
3611 goto error;
3612 }
3613 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003614 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003615
3616 Py_XDECREF(password_bytes);
3617 return 1;
3618
3619error:
3620 Py_XDECREF(password_bytes);
3621 return 0;
3622}
3623
3624static int
3625_password_callback(char *buf, int size, int rwflag, void *userdata)
3626{
3627 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3628 PyObject *fn_ret = NULL;
3629
3630 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3631
3632 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003633 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003634 if (!fn_ret) {
3635 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3636 core python API, so we could use it to add a frame here */
3637 goto error;
3638 }
3639
3640 if (!_pwinfo_set(pw_info, fn_ret,
3641 "password callback must return a string")) {
3642 goto error;
3643 }
3644 Py_CLEAR(fn_ret);
3645 }
3646
3647 if (pw_info->size > size) {
3648 PyErr_Format(PyExc_ValueError,
3649 "password cannot be longer than %d bytes", size);
3650 goto error;
3651 }
3652
3653 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3654 memcpy(buf, pw_info->password, pw_info->size);
3655 return pw_info->size;
3656
3657error:
3658 Py_XDECREF(fn_ret);
3659 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3660 pw_info->error = 1;
3661 return -1;
3662}
3663
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003664/*[clinic input]
3665_ssl._SSLContext.load_cert_chain
3666 certfile: object
3667 keyfile: object = NULL
3668 password: object = NULL
3669
3670[clinic start generated code]*/
3671
Antoine Pitroub5218772010-05-21 09:56:06 +00003672static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003673_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3674 PyObject *keyfile, PyObject *password)
3675/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003676{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003677 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003678 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3679 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003680 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003681 int r;
3682
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003683 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003684 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003685 if (keyfile == Py_None)
3686 keyfile = NULL;
3687 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3688 PyErr_SetString(PyExc_TypeError,
3689 "certfile should be a valid filesystem path");
3690 return NULL;
3691 }
3692 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3693 PyErr_SetString(PyExc_TypeError,
3694 "keyfile should be a valid filesystem path");
3695 goto error;
3696 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003697 if (password && password != Py_None) {
3698 if (PyCallable_Check(password)) {
3699 pw_info.callable = password;
3700 } else if (!_pwinfo_set(&pw_info, password,
3701 "password should be a string or callable")) {
3702 goto error;
3703 }
3704 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3705 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3706 }
3707 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3709 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003710 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003711 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003712 if (pw_info.error) {
3713 ERR_clear_error();
3714 /* the password callback has already set the error information */
3715 }
3716 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003717 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003718 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003719 }
3720 else {
3721 _setSSLError(NULL, 0, __FILE__, __LINE__);
3722 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003723 goto error;
3724 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003725 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003726 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003727 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3728 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003729 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3730 Py_CLEAR(keyfile_bytes);
3731 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003732 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003733 if (pw_info.error) {
3734 ERR_clear_error();
3735 /* the password callback has already set the error information */
3736 }
3737 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003738 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003739 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003740 }
3741 else {
3742 _setSSLError(NULL, 0, __FILE__, __LINE__);
3743 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003744 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003745 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003746 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003747 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003748 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003749 if (r != 1) {
3750 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003751 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003752 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003753 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3754 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003755 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003756 Py_RETURN_NONE;
3757
3758error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003759 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3760 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003761 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003762 Py_XDECREF(keyfile_bytes);
3763 Py_XDECREF(certfile_bytes);
3764 return NULL;
3765}
3766
Christian Heimesefff7062013-11-21 03:35:02 +01003767/* internal helper function, returns -1 on error
3768 */
3769static int
3770_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3771 int filetype)
3772{
3773 BIO *biobuf = NULL;
3774 X509_STORE *store;
3775 int retval = 0, err, loaded = 0;
3776
3777 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3778
3779 if (len <= 0) {
3780 PyErr_SetString(PyExc_ValueError,
3781 "Empty certificate data");
3782 return -1;
3783 } else if (len > INT_MAX) {
3784 PyErr_SetString(PyExc_OverflowError,
3785 "Certificate data is too long.");
3786 return -1;
3787 }
3788
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003789 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003790 if (biobuf == NULL) {
3791 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3792 return -1;
3793 }
3794
3795 store = SSL_CTX_get_cert_store(self->ctx);
3796 assert(store != NULL);
3797
3798 while (1) {
3799 X509 *cert = NULL;
3800 int r;
3801
3802 if (filetype == SSL_FILETYPE_ASN1) {
3803 cert = d2i_X509_bio(biobuf, NULL);
3804 } else {
3805 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003806 SSL_CTX_get_default_passwd_cb(self->ctx),
3807 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3808 );
Christian Heimesefff7062013-11-21 03:35:02 +01003809 }
3810 if (cert == NULL) {
3811 break;
3812 }
3813 r = X509_STORE_add_cert(store, cert);
3814 X509_free(cert);
3815 if (!r) {
3816 err = ERR_peek_last_error();
3817 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3818 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3819 /* cert already in hash table, not an error */
3820 ERR_clear_error();
3821 } else {
3822 break;
3823 }
3824 }
3825 loaded++;
3826 }
3827
3828 err = ERR_peek_last_error();
3829 if ((filetype == SSL_FILETYPE_ASN1) &&
3830 (loaded > 0) &&
3831 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3832 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3833 /* EOF ASN1 file, not an error */
3834 ERR_clear_error();
3835 retval = 0;
3836 } else if ((filetype == SSL_FILETYPE_PEM) &&
3837 (loaded > 0) &&
3838 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3839 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3840 /* EOF PEM file, not an error */
3841 ERR_clear_error();
3842 retval = 0;
3843 } else {
3844 _setSSLError(NULL, 0, __FILE__, __LINE__);
3845 retval = -1;
3846 }
3847
3848 BIO_free(biobuf);
3849 return retval;
3850}
3851
3852
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003853/*[clinic input]
3854_ssl._SSLContext.load_verify_locations
3855 cafile: object = NULL
3856 capath: object = NULL
3857 cadata: object = NULL
3858
3859[clinic start generated code]*/
3860
Antoine Pitrou152efa22010-05-16 18:19:27 +00003861static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003862_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3863 PyObject *cafile,
3864 PyObject *capath,
3865 PyObject *cadata)
3866/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003867{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003868 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3869 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003870 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003871
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003872 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003873 if (cafile == Py_None)
3874 cafile = NULL;
3875 if (capath == Py_None)
3876 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003877 if (cadata == Py_None)
3878 cadata = NULL;
3879
3880 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003881 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003882 "cafile, capath and cadata cannot be all omitted");
3883 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003884 }
3885 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3886 PyErr_SetString(PyExc_TypeError,
3887 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003888 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889 }
3890 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003891 PyErr_SetString(PyExc_TypeError,
3892 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003893 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003894 }
Christian Heimesefff7062013-11-21 03:35:02 +01003895
3896 /* validata cadata type and load cadata */
3897 if (cadata) {
3898 Py_buffer buf;
3899 PyObject *cadata_ascii = NULL;
3900
3901 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3902 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3903 PyBuffer_Release(&buf);
3904 PyErr_SetString(PyExc_TypeError,
3905 "cadata should be a contiguous buffer with "
3906 "a single dimension");
3907 goto error;
3908 }
3909 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3910 PyBuffer_Release(&buf);
3911 if (r == -1) {
3912 goto error;
3913 }
3914 } else {
3915 PyErr_Clear();
3916 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3917 if (cadata_ascii == NULL) {
3918 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003919 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003920 "bytes-like object");
3921 goto error;
3922 }
3923 r = _add_ca_certs(self,
3924 PyBytes_AS_STRING(cadata_ascii),
3925 PyBytes_GET_SIZE(cadata_ascii),
3926 SSL_FILETYPE_PEM);
3927 Py_DECREF(cadata_ascii);
3928 if (r == -1) {
3929 goto error;
3930 }
3931 }
3932 }
3933
3934 /* load cafile or capath */
3935 if (cafile || capath) {
3936 if (cafile)
3937 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3938 if (capath)
3939 capath_buf = PyBytes_AS_STRING(capath_bytes);
3940 PySSL_BEGIN_ALLOW_THREADS
3941 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3942 PySSL_END_ALLOW_THREADS
3943 if (r != 1) {
3944 ok = 0;
3945 if (errno != 0) {
3946 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003947 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003948 }
3949 else {
3950 _setSSLError(NULL, 0, __FILE__, __LINE__);
3951 }
3952 goto error;
3953 }
3954 }
3955 goto end;
3956
3957 error:
3958 ok = 0;
3959 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003960 Py_XDECREF(cafile_bytes);
3961 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003962 if (ok) {
3963 Py_RETURN_NONE;
3964 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003965 return NULL;
3966 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003967}
3968
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003969/*[clinic input]
3970_ssl._SSLContext.load_dh_params
3971 path as filepath: object
3972 /
3973
3974[clinic start generated code]*/
3975
Antoine Pitrou152efa22010-05-16 18:19:27 +00003976static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003977_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3978/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003979{
3980 FILE *f;
3981 DH *dh;
3982
Victor Stinnerdaf45552013-08-28 00:53:59 +02003983 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003984 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003985 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003986
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003987 errno = 0;
3988 PySSL_BEGIN_ALLOW_THREADS
3989 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003990 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003991 PySSL_END_ALLOW_THREADS
3992 if (dh == NULL) {
3993 if (errno != 0) {
3994 ERR_clear_error();
3995 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3996 }
3997 else {
3998 _setSSLError(NULL, 0, __FILE__, __LINE__);
3999 }
4000 return NULL;
4001 }
4002 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4003 _setSSLError(NULL, 0, __FILE__, __LINE__);
4004 DH_free(dh);
4005 Py_RETURN_NONE;
4006}
4007
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004008/*[clinic input]
4009_ssl._SSLContext._wrap_socket
4010 sock: object(subclass_of="PySocketModule.Sock_Type")
4011 server_side: int
4012 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004013 *
4014 owner: object = None
4015 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004016
4017[clinic start generated code]*/
4018
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004019static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004020_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004021 int server_side, PyObject *hostname_obj,
4022 PyObject *owner, PyObject *session)
4023/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024{
Antoine Pitroud5323212010-10-22 18:19:07 +00004025 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004026 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004027
Antoine Pitroud5323212010-10-22 18:19:07 +00004028 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004029 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004030 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004031 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004032 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004033 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004034
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004035 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4036 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004037 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004038 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004039 if (hostname != NULL)
4040 PyMem_Free(hostname);
4041 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004042}
4043
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004044/*[clinic input]
4045_ssl._SSLContext._wrap_bio
4046 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4047 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4048 server_side: int
4049 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004050 *
4051 owner: object = None
4052 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004053
4054[clinic start generated code]*/
4055
Antoine Pitroub0182c82010-10-12 20:09:02 +00004056static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004057_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4058 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004059 PyObject *hostname_obj, PyObject *owner,
4060 PyObject *session)
4061/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004062{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004063 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004064 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004065
4066 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004067 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004068 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004069 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004071 }
4072
4073 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004074 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004075 incoming, outgoing);
4076
4077 PyMem_Free(hostname);
4078 return res;
4079}
4080
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004081/*[clinic input]
4082_ssl._SSLContext.session_stats
4083[clinic start generated code]*/
4084
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004085static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004086_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4087/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004088{
4089 int r;
4090 PyObject *value, *stats = PyDict_New();
4091 if (!stats)
4092 return NULL;
4093
4094#define ADD_STATS(SSL_NAME, KEY_NAME) \
4095 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4096 if (value == NULL) \
4097 goto error; \
4098 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4099 Py_DECREF(value); \
4100 if (r < 0) \
4101 goto error;
4102
4103 ADD_STATS(number, "number");
4104 ADD_STATS(connect, "connect");
4105 ADD_STATS(connect_good, "connect_good");
4106 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4107 ADD_STATS(accept, "accept");
4108 ADD_STATS(accept_good, "accept_good");
4109 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4110 ADD_STATS(accept, "accept");
4111 ADD_STATS(hits, "hits");
4112 ADD_STATS(misses, "misses");
4113 ADD_STATS(timeouts, "timeouts");
4114 ADD_STATS(cache_full, "cache_full");
4115
4116#undef ADD_STATS
4117
4118 return stats;
4119
4120error:
4121 Py_DECREF(stats);
4122 return NULL;
4123}
4124
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125/*[clinic input]
4126_ssl._SSLContext.set_default_verify_paths
4127[clinic start generated code]*/
4128
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004129static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4131/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004132{
4133 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4134 _setSSLError(NULL, 0, __FILE__, __LINE__);
4135 return NULL;
4136 }
4137 Py_RETURN_NONE;
4138}
4139
Antoine Pitrou501da612011-12-21 09:27:41 +01004140#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004141/*[clinic input]
4142_ssl._SSLContext.set_ecdh_curve
4143 name: object
4144 /
4145
4146[clinic start generated code]*/
4147
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004148static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004149_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4150/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004151{
4152 PyObject *name_bytes;
4153 int nid;
4154 EC_KEY *key;
4155
4156 if (!PyUnicode_FSConverter(name, &name_bytes))
4157 return NULL;
4158 assert(PyBytes_Check(name_bytes));
4159 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4160 Py_DECREF(name_bytes);
4161 if (nid == 0) {
4162 PyErr_Format(PyExc_ValueError,
4163 "unknown elliptic curve name %R", name);
4164 return NULL;
4165 }
4166 key = EC_KEY_new_by_curve_name(nid);
4167 if (key == NULL) {
4168 _setSSLError(NULL, 0, __FILE__, __LINE__);
4169 return NULL;
4170 }
4171 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4172 EC_KEY_free(key);
4173 Py_RETURN_NONE;
4174}
Antoine Pitrou501da612011-12-21 09:27:41 +01004175#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004176
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004177#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004178static int
4179_servername_callback(SSL *s, int *al, void *args)
4180{
4181 int ret;
4182 PySSLContext *ssl_ctx = (PySSLContext *) args;
4183 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004184 PyObject *result;
4185 /* The high-level ssl.SSLSocket object */
4186 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004187 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004188 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004189
Christian Heimes11a14932018-02-24 02:35:08 +01004190 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004191 /* remove race condition in this the call back while if removing the
4192 * callback is in progress */
4193 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004194 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004195 }
4196
4197 ssl = SSL_get_app_data(s);
4198 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004199
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004200 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 * SSL connection and that has a .context attribute that can be changed to
4202 * identify the requested hostname. Since the official API is the Python
4203 * level API we want to pass the callback a Python level object rather than
4204 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4205 * SSLObject) that will be passed. Otherwise if there's a socket then that
4206 * will be passed. If both do not exist only then the C-level object is
4207 * passed. */
4208 if (ssl->owner)
4209 ssl_socket = PyWeakref_GetObject(ssl->owner);
4210 else if (ssl->Socket)
4211 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4212 else
4213 ssl_socket = (PyObject *) ssl;
4214
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004215 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004216 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004217 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004218
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004219 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004220 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004221 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004222 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004223 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004224 PyObject *servername_bytes;
4225 PyObject *servername_str;
4226
4227 servername_bytes = PyBytes_FromString(servername);
4228 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004229 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4230 goto error;
4231 }
Christian Heimes11a14932018-02-24 02:35:08 +01004232 /* server_hostname was encoded to an A-label by our caller; put it
4233 * back into a str object, but still as an A-label (bpo-28414)
4234 */
4235 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4236 Py_DECREF(servername_bytes);
4237 if (servername_str == NULL) {
4238 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004239 goto error;
4240 }
Christian Heimes11a14932018-02-24 02:35:08 +01004241 result = PyObject_CallFunctionObjArgs(
4242 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4243 ssl_ctx, NULL);
4244 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004245 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004246 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004247
4248 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004249 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004250 *al = SSL_AD_HANDSHAKE_FAILURE;
4251 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4252 }
4253 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004254 /* Result may be None, a SSLContext or an integer
4255 * None and SSLContext are OK, integer or other values are an error.
4256 */
4257 if (result == Py_None) {
4258 ret = SSL_TLSEXT_ERR_OK;
4259 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004260 *al = (int) PyLong_AsLong(result);
4261 if (PyErr_Occurred()) {
4262 PyErr_WriteUnraisable(result);
4263 *al = SSL_AD_INTERNAL_ERROR;
4264 }
4265 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4266 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004267 Py_DECREF(result);
4268 }
4269
4270 PyGILState_Release(gstate);
4271 return ret;
4272
4273error:
4274 Py_DECREF(ssl_socket);
4275 *al = SSL_AD_INTERNAL_ERROR;
4276 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4277 PyGILState_Release(gstate);
4278 return ret;
4279}
Antoine Pitroua5963382013-03-30 16:39:00 +01004280#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004281
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004282static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004283get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004284{
Christian Heimes11a14932018-02-24 02:35:08 +01004285 PyObject *cb = self->set_sni_cb;
4286 if (cb == NULL) {
4287 Py_RETURN_NONE;
4288 }
4289 Py_INCREF(cb);
4290 return cb;
4291}
4292
4293static int
4294set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4295{
4296 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4297 PyErr_SetString(PyExc_ValueError,
4298 "sni_callback cannot be set on TLS_CLIENT context");
4299 return -1;
4300 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004301#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004302 Py_CLEAR(self->set_sni_cb);
4303 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004304 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4305 }
4306 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004307 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004308 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4309 PyErr_SetString(PyExc_TypeError,
4310 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004311 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004312 }
Christian Heimes11a14932018-02-24 02:35:08 +01004313 Py_INCREF(arg);
4314 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004315 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4316 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4317 }
Christian Heimes11a14932018-02-24 02:35:08 +01004318 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004319#else
4320 PyErr_SetString(PyExc_NotImplementedError,
4321 "The TLS extension servername callback, "
4322 "SSL_CTX_set_tlsext_servername_callback, "
4323 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004324 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004325#endif
4326}
4327
Christian Heimes11a14932018-02-24 02:35:08 +01004328PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4329"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4330\n\
4331If the argument is None then the callback is disabled. The method is called\n\
4332with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4333See RFC 6066 for details of the SNI extension.");
4334
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004335/*[clinic input]
4336_ssl._SSLContext.cert_store_stats
4337
4338Returns quantities of loaded X.509 certificates.
4339
4340X.509 certificates with a CA extension and certificate revocation lists
4341inside the context's cert store.
4342
4343NOTE: Certificates in a capath directory aren't loaded unless they have
4344been used at least once.
4345[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004346
4347static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004348_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4349/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004350{
4351 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004352 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004353 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004354 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004355
4356 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004357 objs = X509_STORE_get0_objects(store);
4358 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4359 obj = sk_X509_OBJECT_value(objs, i);
4360 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004361 case X509_LU_X509:
4362 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004363 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004364 ca++;
4365 }
4366 break;
4367 case X509_LU_CRL:
4368 crl++;
4369 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004370 default:
4371 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4372 * As far as I can tell they are internal states and never
4373 * stored in a cert store */
4374 break;
4375 }
4376 }
4377 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4378 "x509_ca", ca);
4379}
4380
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004381/*[clinic input]
4382_ssl._SSLContext.get_ca_certs
4383 binary_form: bool = False
4384
4385Returns a list of dicts with information of loaded CA certs.
4386
4387If the optional argument is True, returns a DER-encoded copy of the CA
4388certificate.
4389
4390NOTE: Certificates in a capath directory aren't loaded unless they have
4391been used at least once.
4392[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004393
4394static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004395_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4396/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004397{
4398 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004399 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004400 PyObject *ci = NULL, *rlist = NULL;
4401 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004402
4403 if ((rlist = PyList_New(0)) == NULL) {
4404 return NULL;
4405 }
4406
4407 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004408 objs = X509_STORE_get0_objects(store);
4409 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004410 X509_OBJECT *obj;
4411 X509 *cert;
4412
Christian Heimes598894f2016-09-05 23:19:05 +02004413 obj = sk_X509_OBJECT_value(objs, i);
4414 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004415 /* not a x509 cert */
4416 continue;
4417 }
4418 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004419 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004420 if (!X509_check_ca(cert)) {
4421 continue;
4422 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004423 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004424 ci = _certificate_to_der(cert);
4425 } else {
4426 ci = _decode_certificate(cert);
4427 }
4428 if (ci == NULL) {
4429 goto error;
4430 }
4431 if (PyList_Append(rlist, ci) == -1) {
4432 goto error;
4433 }
4434 Py_CLEAR(ci);
4435 }
4436 return rlist;
4437
4438 error:
4439 Py_XDECREF(ci);
4440 Py_XDECREF(rlist);
4441 return NULL;
4442}
4443
4444
Antoine Pitrou152efa22010-05-16 18:19:27 +00004445static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004446 {"check_hostname", (getter) get_check_hostname,
4447 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004448 {"_host_flags", (getter) get_host_flags,
4449 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004450#if SSL_CTRL_GET_MAX_PROTO_VERSION
4451 {"minimum_version", (getter) get_minimum_version,
4452 (setter) set_minimum_version, NULL},
4453 {"maximum_version", (getter) get_maximum_version,
4454 (setter) set_maximum_version, NULL},
4455#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004456 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004457 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004458 {"options", (getter) get_options,
4459 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004460 {"protocol", (getter) get_protocol,
4461 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004462 {"verify_flags", (getter) get_verify_flags,
4463 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004464 {"verify_mode", (getter) get_verify_mode,
4465 (setter) set_verify_mode, NULL},
4466 {NULL}, /* sentinel */
4467};
4468
4469static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004470 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4471 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4472 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4473 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4474 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4475 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4476 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4477 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4478 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4479 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4480 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004481 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4482 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004483 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004484 {NULL, NULL} /* sentinel */
4485};
4486
4487static PyTypeObject PySSLContext_Type = {
4488 PyVarObject_HEAD_INIT(NULL, 0)
4489 "_ssl._SSLContext", /*tp_name*/
4490 sizeof(PySSLContext), /*tp_basicsize*/
4491 0, /*tp_itemsize*/
4492 (destructor)context_dealloc, /*tp_dealloc*/
4493 0, /*tp_print*/
4494 0, /*tp_getattr*/
4495 0, /*tp_setattr*/
4496 0, /*tp_reserved*/
4497 0, /*tp_repr*/
4498 0, /*tp_as_number*/
4499 0, /*tp_as_sequence*/
4500 0, /*tp_as_mapping*/
4501 0, /*tp_hash*/
4502 0, /*tp_call*/
4503 0, /*tp_str*/
4504 0, /*tp_getattro*/
4505 0, /*tp_setattro*/
4506 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004507 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004508 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004509 (traverseproc) context_traverse, /*tp_traverse*/
4510 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004511 0, /*tp_richcompare*/
4512 0, /*tp_weaklistoffset*/
4513 0, /*tp_iter*/
4514 0, /*tp_iternext*/
4515 context_methods, /*tp_methods*/
4516 0, /*tp_members*/
4517 context_getsetlist, /*tp_getset*/
4518 0, /*tp_base*/
4519 0, /*tp_dict*/
4520 0, /*tp_descr_get*/
4521 0, /*tp_descr_set*/
4522 0, /*tp_dictoffset*/
4523 0, /*tp_init*/
4524 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004525 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004526};
4527
4528
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004529/*
4530 * MemoryBIO objects
4531 */
4532
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004533/*[clinic input]
4534@classmethod
4535_ssl.MemoryBIO.__new__
4536
4537[clinic start generated code]*/
4538
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004539static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004540_ssl_MemoryBIO_impl(PyTypeObject *type)
4541/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004542{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004543 BIO *bio;
4544 PySSLMemoryBIO *self;
4545
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004546 bio = BIO_new(BIO_s_mem());
4547 if (bio == NULL) {
4548 PyErr_SetString(PySSLErrorObject,
4549 "failed to allocate BIO");
4550 return NULL;
4551 }
4552 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4553 * just that no data is currently available. The SSL routines should retry
4554 * the read, which we can achieve by calling BIO_set_retry_read(). */
4555 BIO_set_retry_read(bio);
4556 BIO_set_mem_eof_return(bio, -1);
4557
4558 assert(type != NULL && type->tp_alloc != NULL);
4559 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4560 if (self == NULL) {
4561 BIO_free(bio);
4562 return NULL;
4563 }
4564 self->bio = bio;
4565 self->eof_written = 0;
4566
4567 return (PyObject *) self;
4568}
4569
4570static void
4571memory_bio_dealloc(PySSLMemoryBIO *self)
4572{
4573 BIO_free(self->bio);
4574 Py_TYPE(self)->tp_free(self);
4575}
4576
4577static PyObject *
4578memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4579{
Segev Finer5cff6372017-07-27 01:19:17 +03004580 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004581}
4582
4583PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4584"The number of bytes pending in the memory BIO.");
4585
4586static PyObject *
4587memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4588{
4589 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4590 && self->eof_written);
4591}
4592
4593PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4594"Whether the memory BIO is at EOF.");
4595
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004596/*[clinic input]
4597_ssl.MemoryBIO.read
4598 size as len: int = -1
4599 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004600
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004601Read up to size bytes from the memory BIO.
4602
4603If size is not specified, read the entire buffer.
4604If the return value is an empty bytes instance, this means either
4605EOF or that no data is available. Use the "eof" property to
4606distinguish between the two.
4607[clinic start generated code]*/
4608
4609static PyObject *
4610_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4611/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4612{
4613 int avail, nbytes;
4614 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004615
Segev Finer5cff6372017-07-27 01:19:17 +03004616 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004617 if ((len < 0) || (len > avail))
4618 len = avail;
4619
4620 result = PyBytes_FromStringAndSize(NULL, len);
4621 if ((result == NULL) || (len == 0))
4622 return result;
4623
4624 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4625 /* There should never be any short reads but check anyway. */
4626 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4627 Py_DECREF(result);
4628 return NULL;
4629 }
4630
4631 return result;
4632}
4633
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004634/*[clinic input]
4635_ssl.MemoryBIO.write
4636 b: Py_buffer
4637 /
4638
4639Writes the bytes b into the memory BIO.
4640
4641Returns the number of bytes written.
4642[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004643
4644static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004645_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4646/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004648 int nbytes;
4649
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004650 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004651 PyErr_Format(PyExc_OverflowError,
4652 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004653 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004654 }
4655
4656 if (self->eof_written) {
4657 PyErr_SetString(PySSLErrorObject,
4658 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004659 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004660 }
4661
Segev Finer5cff6372017-07-27 01:19:17 +03004662 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004663 if (nbytes < 0) {
4664 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004665 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666 }
4667
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004668 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004669}
4670
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004671/*[clinic input]
4672_ssl.MemoryBIO.write_eof
4673
4674Write an EOF marker to the memory BIO.
4675
4676When all data has been read, the "eof" property will be True.
4677[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004678
4679static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004680_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4681/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004682{
4683 self->eof_written = 1;
4684 /* After an EOF is written, a zero return from read() should be a real EOF
4685 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4686 BIO_clear_retry_flags(self->bio);
4687 BIO_set_mem_eof_return(self->bio, 0);
4688
4689 Py_RETURN_NONE;
4690}
4691
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004692static PyGetSetDef memory_bio_getsetlist[] = {
4693 {"pending", (getter) memory_bio_get_pending, NULL,
4694 PySSL_memory_bio_pending_doc},
4695 {"eof", (getter) memory_bio_get_eof, NULL,
4696 PySSL_memory_bio_eof_doc},
4697 {NULL}, /* sentinel */
4698};
4699
4700static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004701 _SSL_MEMORYBIO_READ_METHODDEF
4702 _SSL_MEMORYBIO_WRITE_METHODDEF
4703 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004704 {NULL, NULL} /* sentinel */
4705};
4706
4707static PyTypeObject PySSLMemoryBIO_Type = {
4708 PyVarObject_HEAD_INIT(NULL, 0)
4709 "_ssl.MemoryBIO", /*tp_name*/
4710 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4711 0, /*tp_itemsize*/
4712 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4713 0, /*tp_print*/
4714 0, /*tp_getattr*/
4715 0, /*tp_setattr*/
4716 0, /*tp_reserved*/
4717 0, /*tp_repr*/
4718 0, /*tp_as_number*/
4719 0, /*tp_as_sequence*/
4720 0, /*tp_as_mapping*/
4721 0, /*tp_hash*/
4722 0, /*tp_call*/
4723 0, /*tp_str*/
4724 0, /*tp_getattro*/
4725 0, /*tp_setattro*/
4726 0, /*tp_as_buffer*/
4727 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4728 0, /*tp_doc*/
4729 0, /*tp_traverse*/
4730 0, /*tp_clear*/
4731 0, /*tp_richcompare*/
4732 0, /*tp_weaklistoffset*/
4733 0, /*tp_iter*/
4734 0, /*tp_iternext*/
4735 memory_bio_methods, /*tp_methods*/
4736 0, /*tp_members*/
4737 memory_bio_getsetlist, /*tp_getset*/
4738 0, /*tp_base*/
4739 0, /*tp_dict*/
4740 0, /*tp_descr_get*/
4741 0, /*tp_descr_set*/
4742 0, /*tp_dictoffset*/
4743 0, /*tp_init*/
4744 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004745 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004746};
4747
Antoine Pitrou152efa22010-05-16 18:19:27 +00004748
Christian Heimes99a65702016-09-10 23:44:53 +02004749/*
4750 * SSL Session object
4751 */
4752
4753static void
4754PySSLSession_dealloc(PySSLSession *self)
4755{
INADA Naokia6296d32017-08-24 14:55:17 +09004756 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004757 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004758 Py_XDECREF(self->ctx);
4759 if (self->session != NULL) {
4760 SSL_SESSION_free(self->session);
4761 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004762 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004763}
4764
4765static PyObject *
4766PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4767{
4768 int result;
4769
4770 if (left == NULL || right == NULL) {
4771 PyErr_BadInternalCall();
4772 return NULL;
4773 }
4774
4775 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4776 Py_RETURN_NOTIMPLEMENTED;
4777 }
4778
4779 if (left == right) {
4780 result = 0;
4781 } else {
4782 const unsigned char *left_id, *right_id;
4783 unsigned int left_len, right_len;
4784 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4785 &left_len);
4786 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4787 &right_len);
4788 if (left_len == right_len) {
4789 result = memcmp(left_id, right_id, left_len);
4790 } else {
4791 result = 1;
4792 }
4793 }
4794
4795 switch (op) {
4796 case Py_EQ:
4797 if (result == 0) {
4798 Py_RETURN_TRUE;
4799 } else {
4800 Py_RETURN_FALSE;
4801 }
4802 break;
4803 case Py_NE:
4804 if (result != 0) {
4805 Py_RETURN_TRUE;
4806 } else {
4807 Py_RETURN_FALSE;
4808 }
4809 break;
4810 case Py_LT:
4811 case Py_LE:
4812 case Py_GT:
4813 case Py_GE:
4814 Py_RETURN_NOTIMPLEMENTED;
4815 break;
4816 default:
4817 PyErr_BadArgument();
4818 return NULL;
4819 }
4820}
4821
4822static int
4823PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4824{
4825 Py_VISIT(self->ctx);
4826 return 0;
4827}
4828
4829static int
4830PySSLSession_clear(PySSLSession *self)
4831{
4832 Py_CLEAR(self->ctx);
4833 return 0;
4834}
4835
4836
4837static PyObject *
4838PySSLSession_get_time(PySSLSession *self, void *closure) {
4839 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4840}
4841
4842PyDoc_STRVAR(PySSLSession_get_time_doc,
4843"Session creation time (seconds since epoch).");
4844
4845
4846static PyObject *
4847PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4848 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4849}
4850
4851PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4852"Session timeout (delta in seconds).");
4853
4854
4855static PyObject *
4856PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4857 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4858 return PyLong_FromUnsignedLong(hint);
4859}
4860
4861PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4862"Ticket life time hint.");
4863
4864
4865static PyObject *
4866PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4867 const unsigned char *id;
4868 unsigned int len;
4869 id = SSL_SESSION_get_id(self->session, &len);
4870 return PyBytes_FromStringAndSize((const char *)id, len);
4871}
4872
4873PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4874"Session id");
4875
4876
4877static PyObject *
4878PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4879 if (SSL_SESSION_has_ticket(self->session)) {
4880 Py_RETURN_TRUE;
4881 } else {
4882 Py_RETURN_FALSE;
4883 }
4884}
4885
4886PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4887"Does the session contain a ticket?");
4888
4889
4890static PyGetSetDef PySSLSession_getsetlist[] = {
4891 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4892 PySSLSession_get_has_ticket_doc},
4893 {"id", (getter) PySSLSession_get_session_id, NULL,
4894 PySSLSession_get_session_id_doc},
4895 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4896 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4897 {"time", (getter) PySSLSession_get_time, NULL,
4898 PySSLSession_get_time_doc},
4899 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4900 PySSLSession_get_timeout_doc},
4901 {NULL}, /* sentinel */
4902};
4903
4904static PyTypeObject PySSLSession_Type = {
4905 PyVarObject_HEAD_INIT(NULL, 0)
4906 "_ssl.Session", /*tp_name*/
4907 sizeof(PySSLSession), /*tp_basicsize*/
4908 0, /*tp_itemsize*/
4909 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4910 0, /*tp_print*/
4911 0, /*tp_getattr*/
4912 0, /*tp_setattr*/
4913 0, /*tp_reserved*/
4914 0, /*tp_repr*/
4915 0, /*tp_as_number*/
4916 0, /*tp_as_sequence*/
4917 0, /*tp_as_mapping*/
4918 0, /*tp_hash*/
4919 0, /*tp_call*/
4920 0, /*tp_str*/
4921 0, /*tp_getattro*/
4922 0, /*tp_setattro*/
4923 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004924 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004925 0, /*tp_doc*/
4926 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4927 (inquiry)PySSLSession_clear, /*tp_clear*/
4928 PySSLSession_richcompare, /*tp_richcompare*/
4929 0, /*tp_weaklistoffset*/
4930 0, /*tp_iter*/
4931 0, /*tp_iternext*/
4932 0, /*tp_methods*/
4933 0, /*tp_members*/
4934 PySSLSession_getsetlist, /*tp_getset*/
4935};
4936
4937
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004938/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004939/*[clinic input]
4940_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004941 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004942 entropy: double
4943 /
4944
4945Mix string into the OpenSSL PRNG state.
4946
4947entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304948string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004949[clinic start generated code]*/
4950
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004951static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004952_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004953/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004954{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004955 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004956 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004957
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004958 buf = (const char *)view->buf;
4959 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004960 do {
4961 written = Py_MIN(len, INT_MAX);
4962 RAND_add(buf, (int)written, entropy);
4963 buf += written;
4964 len -= written;
4965 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004966 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004967}
4968
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004969static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004970PySSL_RAND(int len, int pseudo)
4971{
4972 int ok;
4973 PyObject *bytes;
4974 unsigned long err;
4975 const char *errstr;
4976 PyObject *v;
4977
Victor Stinner1e81a392013-12-19 16:47:04 +01004978 if (len < 0) {
4979 PyErr_SetString(PyExc_ValueError, "num must be positive");
4980 return NULL;
4981 }
4982
Victor Stinner99c8b162011-05-24 12:05:19 +02004983 bytes = PyBytes_FromStringAndSize(NULL, len);
4984 if (bytes == NULL)
4985 return NULL;
4986 if (pseudo) {
4987 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4988 if (ok == 0 || ok == 1)
4989 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4990 }
4991 else {
4992 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4993 if (ok == 1)
4994 return bytes;
4995 }
4996 Py_DECREF(bytes);
4997
4998 err = ERR_get_error();
4999 errstr = ERR_reason_error_string(err);
5000 v = Py_BuildValue("(ks)", err, errstr);
5001 if (v != NULL) {
5002 PyErr_SetObject(PySSLErrorObject, v);
5003 Py_DECREF(v);
5004 }
5005 return NULL;
5006}
5007
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005008/*[clinic input]
5009_ssl.RAND_bytes
5010 n: int
5011 /
5012
5013Generate n cryptographically strong pseudo-random bytes.
5014[clinic start generated code]*/
5015
Victor Stinner99c8b162011-05-24 12:05:19 +02005016static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005017_ssl_RAND_bytes_impl(PyObject *module, int n)
5018/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005019{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005020 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005021}
5022
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005023/*[clinic input]
5024_ssl.RAND_pseudo_bytes
5025 n: int
5026 /
5027
5028Generate n pseudo-random bytes.
5029
5030Return a pair (bytes, is_cryptographic). is_cryptographic is True
5031if the bytes generated are cryptographically strong.
5032[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005033
5034static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005035_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5036/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005037{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005038 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005039}
5040
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005041/*[clinic input]
5042_ssl.RAND_status
5043
5044Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5045
5046It is necessary to seed the PRNG with RAND_add() on some platforms before
5047using the ssl() function.
5048[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005049
5050static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005051_ssl_RAND_status_impl(PyObject *module)
5052/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005053{
Christian Heimes217cfd12007-12-02 14:31:20 +00005054 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005055}
5056
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005057#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005058/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005059/*[clinic input]
5060_ssl.RAND_egd
5061 path: object(converter="PyUnicode_FSConverter")
5062 /
5063
5064Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5065
5066Returns number of bytes read. Raises SSLError if connection to EGD
5067fails or if it does not provide enough data to seed PRNG.
5068[clinic start generated code]*/
5069
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005070static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005071_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5072/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005073{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005074 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005075 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005076 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005077 PyErr_SetString(PySSLErrorObject,
5078 "EGD connection failed or EGD did not return "
5079 "enough data to seed the PRNG");
5080 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005081 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005082 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005083}
Christian Heimesa5d07652016-09-24 10:48:05 +02005084/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005085#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005086
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005087
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005088
5089/*[clinic input]
5090_ssl.get_default_verify_paths
5091
5092Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5093
5094The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5095[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005096
5097static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005098_ssl_get_default_verify_paths_impl(PyObject *module)
5099/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005100{
5101 PyObject *ofile_env = NULL;
5102 PyObject *ofile = NULL;
5103 PyObject *odir_env = NULL;
5104 PyObject *odir = NULL;
5105
Benjamin Petersond113c962015-07-18 10:59:13 -07005106#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005107 const char *tmp = (info); \
5108 target = NULL; \
5109 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5110 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5111 target = PyBytes_FromString(tmp); } \
5112 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005113 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005114
Benjamin Petersond113c962015-07-18 10:59:13 -07005115 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5116 CONVERT(X509_get_default_cert_file(), ofile);
5117 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5118 CONVERT(X509_get_default_cert_dir(), odir);
5119#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005120
Christian Heimes200bb1b2013-06-14 15:14:29 +02005121 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005122
5123 error:
5124 Py_XDECREF(ofile_env);
5125 Py_XDECREF(ofile);
5126 Py_XDECREF(odir_env);
5127 Py_XDECREF(odir);
5128 return NULL;
5129}
5130
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005131static PyObject*
5132asn1obj2py(ASN1_OBJECT *obj)
5133{
5134 int nid;
5135 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005136
5137 nid = OBJ_obj2nid(obj);
5138 if (nid == NID_undef) {
5139 PyErr_Format(PyExc_ValueError, "Unknown object");
5140 return NULL;
5141 }
5142 sn = OBJ_nid2sn(nid);
5143 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005144 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005145}
5146
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005147/*[clinic input]
5148_ssl.txt2obj
5149 txt: str
5150 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005152Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5153
5154By default objects are looked up by OID. With name=True short and
5155long name are also matched.
5156[clinic start generated code]*/
5157
5158static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005159_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5160/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005161{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005162 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005163 ASN1_OBJECT *obj;
5164
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005165 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5166 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005167 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005168 return NULL;
5169 }
5170 result = asn1obj2py(obj);
5171 ASN1_OBJECT_free(obj);
5172 return result;
5173}
5174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005175/*[clinic input]
5176_ssl.nid2obj
5177 nid: int
5178 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005179
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005180Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5181[clinic start generated code]*/
5182
5183static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005184_ssl_nid2obj_impl(PyObject *module, int nid)
5185/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005186{
5187 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005188 ASN1_OBJECT *obj;
5189
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005190 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005191 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005192 return NULL;
5193 }
5194 obj = OBJ_nid2obj(nid);
5195 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005196 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005197 return NULL;
5198 }
5199 result = asn1obj2py(obj);
5200 ASN1_OBJECT_free(obj);
5201 return result;
5202}
5203
Christian Heimes46bebee2013-06-09 19:03:31 +02005204#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005205
5206static PyObject*
5207certEncodingType(DWORD encodingType)
5208{
5209 static PyObject *x509_asn = NULL;
5210 static PyObject *pkcs_7_asn = NULL;
5211
5212 if (x509_asn == NULL) {
5213 x509_asn = PyUnicode_InternFromString("x509_asn");
5214 if (x509_asn == NULL)
5215 return NULL;
5216 }
5217 if (pkcs_7_asn == NULL) {
5218 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5219 if (pkcs_7_asn == NULL)
5220 return NULL;
5221 }
5222 switch(encodingType) {
5223 case X509_ASN_ENCODING:
5224 Py_INCREF(x509_asn);
5225 return x509_asn;
5226 case PKCS_7_ASN_ENCODING:
5227 Py_INCREF(pkcs_7_asn);
5228 return pkcs_7_asn;
5229 default:
5230 return PyLong_FromLong(encodingType);
5231 }
5232}
5233
5234static PyObject*
5235parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5236{
5237 CERT_ENHKEY_USAGE *usage;
5238 DWORD size, error, i;
5239 PyObject *retval;
5240
5241 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5242 error = GetLastError();
5243 if (error == CRYPT_E_NOT_FOUND) {
5244 Py_RETURN_TRUE;
5245 }
5246 return PyErr_SetFromWindowsErr(error);
5247 }
5248
5249 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5250 if (usage == NULL) {
5251 return PyErr_NoMemory();
5252 }
5253
5254 /* Now get the actual enhanced usage property */
5255 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5256 PyMem_Free(usage);
5257 error = GetLastError();
5258 if (error == CRYPT_E_NOT_FOUND) {
5259 Py_RETURN_TRUE;
5260 }
5261 return PyErr_SetFromWindowsErr(error);
5262 }
5263 retval = PySet_New(NULL);
5264 if (retval == NULL) {
5265 goto error;
5266 }
5267 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5268 if (usage->rgpszUsageIdentifier[i]) {
5269 PyObject *oid;
5270 int err;
5271 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5272 if (oid == NULL) {
5273 Py_CLEAR(retval);
5274 goto error;
5275 }
5276 err = PySet_Add(retval, oid);
5277 Py_DECREF(oid);
5278 if (err == -1) {
5279 Py_CLEAR(retval);
5280 goto error;
5281 }
5282 }
5283 }
5284 error:
5285 PyMem_Free(usage);
5286 return retval;
5287}
5288
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005289/*[clinic input]
5290_ssl.enum_certificates
5291 store_name: str
5292
5293Retrieve certificates from Windows' cert store.
5294
5295store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5296more cert storages, too. The function returns a list of (bytes,
5297encoding_type, trust) tuples. The encoding_type flag can be interpreted
5298with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5299a set of OIDs or the boolean True.
5300[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005301
Christian Heimes46bebee2013-06-09 19:03:31 +02005302static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005303_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5304/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005305{
Christian Heimes46bebee2013-06-09 19:03:31 +02005306 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005307 PCCERT_CONTEXT pCertCtx = NULL;
5308 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005309 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005310
Christian Heimes44109d72013-11-22 01:51:30 +01005311 result = PyList_New(0);
5312 if (result == NULL) {
5313 return NULL;
5314 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005315 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5316 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5317 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005318 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005319 Py_DECREF(result);
5320 return PyErr_SetFromWindowsErr(GetLastError());
5321 }
5322
Christian Heimes44109d72013-11-22 01:51:30 +01005323 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5324 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5325 pCertCtx->cbCertEncoded);
5326 if (!cert) {
5327 Py_CLEAR(result);
5328 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005329 }
Christian Heimes44109d72013-11-22 01:51:30 +01005330 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5331 Py_CLEAR(result);
5332 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005333 }
Christian Heimes44109d72013-11-22 01:51:30 +01005334 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5335 if (keyusage == Py_True) {
5336 Py_DECREF(keyusage);
5337 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005338 }
Christian Heimes44109d72013-11-22 01:51:30 +01005339 if (keyusage == NULL) {
5340 Py_CLEAR(result);
5341 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005342 }
Christian Heimes44109d72013-11-22 01:51:30 +01005343 if ((tup = PyTuple_New(3)) == NULL) {
5344 Py_CLEAR(result);
5345 break;
5346 }
5347 PyTuple_SET_ITEM(tup, 0, cert);
5348 cert = NULL;
5349 PyTuple_SET_ITEM(tup, 1, enc);
5350 enc = NULL;
5351 PyTuple_SET_ITEM(tup, 2, keyusage);
5352 keyusage = NULL;
5353 if (PyList_Append(result, tup) < 0) {
5354 Py_CLEAR(result);
5355 break;
5356 }
5357 Py_CLEAR(tup);
5358 }
5359 if (pCertCtx) {
5360 /* loop ended with an error, need to clean up context manually */
5361 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005362 }
5363
5364 /* In error cases cert, enc and tup may not be NULL */
5365 Py_XDECREF(cert);
5366 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005367 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005368 Py_XDECREF(tup);
5369
5370 if (!CertCloseStore(hStore, 0)) {
5371 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005372 Py_XDECREF(result);
5373 return PyErr_SetFromWindowsErr(GetLastError());
5374 }
5375 return result;
5376}
5377
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005378/*[clinic input]
5379_ssl.enum_crls
5380 store_name: str
5381
5382Retrieve CRLs from Windows' cert store.
5383
5384store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5385more cert storages, too. The function returns a list of (bytes,
5386encoding_type) tuples. The encoding_type flag can be interpreted with
5387X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5388[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005389
5390static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005391_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5392/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005393{
Christian Heimes44109d72013-11-22 01:51:30 +01005394 HCERTSTORE hStore = NULL;
5395 PCCRL_CONTEXT pCrlCtx = NULL;
5396 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5397 PyObject *result = NULL;
5398
Christian Heimes44109d72013-11-22 01:51:30 +01005399 result = PyList_New(0);
5400 if (result == NULL) {
5401 return NULL;
5402 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005403 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5404 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5405 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005406 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005407 Py_DECREF(result);
5408 return PyErr_SetFromWindowsErr(GetLastError());
5409 }
Christian Heimes44109d72013-11-22 01:51:30 +01005410
5411 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5412 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5413 pCrlCtx->cbCrlEncoded);
5414 if (!crl) {
5415 Py_CLEAR(result);
5416 break;
5417 }
5418 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5419 Py_CLEAR(result);
5420 break;
5421 }
5422 if ((tup = PyTuple_New(2)) == NULL) {
5423 Py_CLEAR(result);
5424 break;
5425 }
5426 PyTuple_SET_ITEM(tup, 0, crl);
5427 crl = NULL;
5428 PyTuple_SET_ITEM(tup, 1, enc);
5429 enc = NULL;
5430
5431 if (PyList_Append(result, tup) < 0) {
5432 Py_CLEAR(result);
5433 break;
5434 }
5435 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005436 }
Christian Heimes44109d72013-11-22 01:51:30 +01005437 if (pCrlCtx) {
5438 /* loop ended with an error, need to clean up context manually */
5439 CertFreeCRLContext(pCrlCtx);
5440 }
5441
5442 /* In error cases cert, enc and tup may not be NULL */
5443 Py_XDECREF(crl);
5444 Py_XDECREF(enc);
5445 Py_XDECREF(tup);
5446
5447 if (!CertCloseStore(hStore, 0)) {
5448 /* This error case might shadow another exception.*/
5449 Py_XDECREF(result);
5450 return PyErr_SetFromWindowsErr(GetLastError());
5451 }
5452 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005453}
Christian Heimes44109d72013-11-22 01:51:30 +01005454
5455#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005456
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005457/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005458static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005459 _SSL__TEST_DECODE_CERT_METHODDEF
5460 _SSL_RAND_ADD_METHODDEF
5461 _SSL_RAND_BYTES_METHODDEF
5462 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5463 _SSL_RAND_EGD_METHODDEF
5464 _SSL_RAND_STATUS_METHODDEF
5465 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5466 _SSL_ENUM_CERTIFICATES_METHODDEF
5467 _SSL_ENUM_CRLS_METHODDEF
5468 _SSL_TXT2OBJ_METHODDEF
5469 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005470 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005471};
5472
5473
Christian Heimes598894f2016-09-05 23:19:05 +02005474#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005475
5476/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005477 * of the Python C thread library
5478 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5479 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005480
5481static PyThread_type_lock *_ssl_locks = NULL;
5482
Christian Heimes4d98ca92013-08-19 17:36:29 +02005483#if OPENSSL_VERSION_NUMBER >= 0x10000000
5484/* use new CRYPTO_THREADID API. */
5485static void
5486_ssl_threadid_callback(CRYPTO_THREADID *id)
5487{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005488 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005489}
5490#else
5491/* deprecated CRYPTO_set_id_callback() API. */
5492static unsigned long
5493_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005494 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005495}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005496#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005497
Bill Janssen6e027db2007-11-15 22:23:56 +00005498static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005499 (int mode, int n, const char *file, int line) {
5500 /* this function is needed to perform locking on shared data
5501 structures. (Note that OpenSSL uses a number of global data
5502 structures that will be implicitly shared whenever multiple
5503 threads use OpenSSL.) Multi-threaded applications will
5504 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005506 locking_function() must be able to handle up to
5507 CRYPTO_num_locks() different mutex locks. It sets the n-th
5508 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005510 file and line are the file number of the function setting the
5511 lock. They can be useful for debugging.
5512 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005514 if ((_ssl_locks == NULL) ||
5515 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5516 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005518 if (mode & CRYPTO_LOCK) {
5519 PyThread_acquire_lock(_ssl_locks[n], 1);
5520 } else {
5521 PyThread_release_lock(_ssl_locks[n]);
5522 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005523}
5524
5525static int _setup_ssl_threads(void) {
5526
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005527 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005529 if (_ssl_locks == NULL) {
5530 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005531 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5532 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005533 if (_ssl_locks == NULL) {
5534 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005535 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005536 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005537 for (i = 0; i < _ssl_locks_count; i++) {
5538 _ssl_locks[i] = PyThread_allocate_lock();
5539 if (_ssl_locks[i] == NULL) {
5540 unsigned int j;
5541 for (j = 0; j < i; j++) {
5542 PyThread_free_lock(_ssl_locks[j]);
5543 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005544 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005545 return 0;
5546 }
5547 }
5548 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005549#if OPENSSL_VERSION_NUMBER >= 0x10000000
5550 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5551#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005552 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005553#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005554 }
5555 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005556}
5557
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005558#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005559
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005560PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005561"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005562for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005563
Martin v. Löwis1a214512008-06-11 05:26:20 +00005564
5565static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005566 PyModuleDef_HEAD_INIT,
5567 "_ssl",
5568 module_doc,
5569 -1,
5570 PySSL_methods,
5571 NULL,
5572 NULL,
5573 NULL,
5574 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005575};
5576
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005577
5578static void
5579parse_openssl_version(unsigned long libver,
5580 unsigned int *major, unsigned int *minor,
5581 unsigned int *fix, unsigned int *patch,
5582 unsigned int *status)
5583{
5584 *status = libver & 0xF;
5585 libver >>= 4;
5586 *patch = libver & 0xFF;
5587 libver >>= 8;
5588 *fix = libver & 0xFF;
5589 libver >>= 8;
5590 *minor = libver & 0xFF;
5591 libver >>= 8;
5592 *major = libver & 0xFF;
5593}
5594
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005595PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005596PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005597{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005598 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005599 unsigned long libver;
5600 unsigned int major, minor, fix, patch, status;
5601 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005602 struct py_ssl_error_code *errcode;
5603 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005604
Antoine Pitrou152efa22010-05-16 18:19:27 +00005605 if (PyType_Ready(&PySSLContext_Type) < 0)
5606 return NULL;
5607 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005608 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005609 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5610 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005611 if (PyType_Ready(&PySSLSession_Type) < 0)
5612 return NULL;
5613
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005614
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005615 m = PyModule_Create(&_sslmodule);
5616 if (m == NULL)
5617 return NULL;
5618 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005620 /* Load _socket module and its C API */
5621 socket_api = PySocketModule_ImportModuleAndAPI();
5622 if (!socket_api)
5623 return NULL;
5624 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005625
Christian Heimesc941e622017-09-05 15:47:11 +02005626#ifndef OPENSSL_VERSION_1_1
5627 /* Load all algorithms and initialize cpuid */
5628 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005629 /* Init OpenSSL */
5630 SSL_load_error_strings();
5631 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005632#endif
5633
Christian Heimes598894f2016-09-05 23:19:05 +02005634#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005635 /* note that this will start threading if not already started */
5636 if (!_setup_ssl_threads()) {
5637 return NULL;
5638 }
Christian Heimes598894f2016-09-05 23:19:05 +02005639#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5640 /* OpenSSL 1.1.0 builtin thread support is enabled */
5641 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005642#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005644 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005645 sslerror_type_slots[0].pfunc = PyExc_OSError;
5646 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005647 if (PySSLErrorObject == NULL)
5648 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005649
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005650 /* ssl.CertificateError used to be a subclass of ValueError */
5651 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5652 if (bases == NULL)
5653 return NULL;
5654 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5655 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5656 bases, NULL);
5657 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005658 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5659 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5660 PySSLErrorObject, NULL);
5661 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5662 "ssl.SSLWantReadError", SSLWantReadError_doc,
5663 PySSLErrorObject, NULL);
5664 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5665 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5666 PySSLErrorObject, NULL);
5667 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5668 "ssl.SSLSyscallError", SSLSyscallError_doc,
5669 PySSLErrorObject, NULL);
5670 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5671 "ssl.SSLEOFError", SSLEOFError_doc,
5672 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005673 if (PySSLCertVerificationErrorObject == NULL
5674 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005675 || PySSLWantReadErrorObject == NULL
5676 || PySSLWantWriteErrorObject == NULL
5677 || PySSLSyscallErrorObject == NULL
5678 || PySSLEOFErrorObject == NULL)
5679 return NULL;
5680 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005681 || PyDict_SetItemString(d, "SSLCertVerificationError",
5682 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005683 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5684 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5685 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5686 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5687 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005688 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005689 if (PyDict_SetItemString(d, "_SSLContext",
5690 (PyObject *)&PySSLContext_Type) != 0)
5691 return NULL;
5692 if (PyDict_SetItemString(d, "_SSLSocket",
5693 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005694 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005695 if (PyDict_SetItemString(d, "MemoryBIO",
5696 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5697 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005698 if (PyDict_SetItemString(d, "SSLSession",
5699 (PyObject *)&PySSLSession_Type) != 0)
5700 return NULL;
5701
Christian Heimes892d66e2018-01-29 14:10:18 +01005702 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5703 PY_SSL_DEFAULT_CIPHER_STRING);
5704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005705 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5706 PY_SSL_ERROR_ZERO_RETURN);
5707 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5708 PY_SSL_ERROR_WANT_READ);
5709 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5710 PY_SSL_ERROR_WANT_WRITE);
5711 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5712 PY_SSL_ERROR_WANT_X509_LOOKUP);
5713 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5714 PY_SSL_ERROR_SYSCALL);
5715 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5716 PY_SSL_ERROR_SSL);
5717 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5718 PY_SSL_ERROR_WANT_CONNECT);
5719 /* non ssl.h errorcodes */
5720 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5721 PY_SSL_ERROR_EOF);
5722 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5723 PY_SSL_ERROR_INVALID_ERROR_CODE);
5724 /* cert requirements */
5725 PyModule_AddIntConstant(m, "CERT_NONE",
5726 PY_SSL_CERT_NONE);
5727 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5728 PY_SSL_CERT_OPTIONAL);
5729 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5730 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005731 /* CRL verification for verification_flags */
5732 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5733 0);
5734 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5735 X509_V_FLAG_CRL_CHECK);
5736 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5737 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5738 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5739 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005740#ifdef X509_V_FLAG_TRUSTED_FIRST
5741 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5742 X509_V_FLAG_TRUSTED_FIRST);
5743#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005744
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005745 /* Alert Descriptions from ssl.h */
5746 /* note RESERVED constants no longer intended for use have been removed */
5747 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5748
5749#define ADD_AD_CONSTANT(s) \
5750 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5751 SSL_AD_##s)
5752
5753 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5754 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5755 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5756 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5757 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5758 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5759 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5760 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5761 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5762 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5763 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5764 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5765 ADD_AD_CONSTANT(UNKNOWN_CA);
5766 ADD_AD_CONSTANT(ACCESS_DENIED);
5767 ADD_AD_CONSTANT(DECODE_ERROR);
5768 ADD_AD_CONSTANT(DECRYPT_ERROR);
5769 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5770 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5771 ADD_AD_CONSTANT(INTERNAL_ERROR);
5772 ADD_AD_CONSTANT(USER_CANCELLED);
5773 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005774 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005775#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5776 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5777#endif
5778#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5779 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5780#endif
5781#ifdef SSL_AD_UNRECOGNIZED_NAME
5782 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5783#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005784#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5785 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5786#endif
5787#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5788 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5789#endif
5790#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5791 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5792#endif
5793
5794#undef ADD_AD_CONSTANT
5795
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005796 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005797#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005798 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5799 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005800#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005801#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005802 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5803 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005804#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005805 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005806 PY_SSL_VERSION_TLS);
5807 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5808 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005809 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5810 PY_SSL_VERSION_TLS_CLIENT);
5811 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5812 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005813 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5814 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005815#if HAVE_TLSv1_2
5816 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5817 PY_SSL_VERSION_TLS1_1);
5818 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5819 PY_SSL_VERSION_TLS1_2);
5820#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005821
Antoine Pitroub5218772010-05-21 09:56:06 +00005822 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005823 PyModule_AddIntConstant(m, "OP_ALL",
5824 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005825 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5826 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5827 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005828#if HAVE_TLSv1_2
5829 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5830 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5831#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005832#ifdef SSL_OP_NO_TLSv1_3
5833 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5834#else
5835 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5836#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005837 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5838 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005839 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005840 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005841#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005842 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005843#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005844#ifdef SSL_OP_NO_COMPRESSION
5845 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5846 SSL_OP_NO_COMPRESSION);
5847#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005848#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5849 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5850 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5851#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005852
Christian Heimes61d478c2018-01-27 15:51:38 +01005853#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5854 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5855 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5856#endif
5857#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5858 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5859 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5860#endif
5861#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5862 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5863 X509_CHECK_FLAG_NO_WILDCARDS);
5864#endif
5865#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5866 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5867 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5868#endif
5869#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5870 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5871 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5872#endif
5873#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5874 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5875 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5876#endif
5877
Christian Heimes698dde12018-02-27 11:54:43 +01005878 /* protocol versions */
5879 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5880 PY_PROTO_MINIMUM_SUPPORTED);
5881 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5882 PY_PROTO_MAXIMUM_SUPPORTED);
5883 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5884 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5885 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5886 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5887 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005888
Christian Heimes698dde12018-02-27 11:54:43 +01005889#define addbool(m, v, b) \
5890 Py_INCREF((b) ? Py_True : Py_False); \
5891 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5892
5893#if HAVE_SNI
5894 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005895#else
Christian Heimes698dde12018-02-27 11:54:43 +01005896 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005897#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005898
5899 addbool(m, "HAS_TLS_UNIQUE", 1);
5900
5901#ifndef OPENSSL_NO_ECDH
5902 addbool(m, "HAS_ECDH", 1);
5903#else
5904 addbool(m, "HAS_ECDH", 0);
5905#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005906
Christian Heimes29eab552018-02-25 12:31:33 +01005907#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005908 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005909#else
Christian Heimes698dde12018-02-27 11:54:43 +01005910 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005911#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005912
Christian Heimes29eab552018-02-25 12:31:33 +01005913#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005914 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005915#else
Christian Heimes698dde12018-02-27 11:54:43 +01005916 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005917#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005918
5919#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5920 addbool(m, "HAS_SSLv2", 1);
5921#else
5922 addbool(m, "HAS_SSLv2", 0);
5923#endif
5924
5925#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5926 addbool(m, "HAS_SSLv3", 1);
5927#else
5928 addbool(m, "HAS_SSLv3", 0);
5929#endif
5930
5931#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5932 addbool(m, "HAS_TLSv1", 1);
5933#else
5934 addbool(m, "HAS_TLSv1", 0);
5935#endif
5936
5937#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5938 addbool(m, "HAS_TLSv1_1", 1);
5939#else
5940 addbool(m, "HAS_TLSv1_1", 0);
5941#endif
5942
5943#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5944 addbool(m, "HAS_TLSv1_2", 1);
5945#else
5946 addbool(m, "HAS_TLSv1_2", 0);
5947#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005948
Christian Heimescb5b68a2017-09-07 18:07:00 -07005949#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005950 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005951#else
Christian Heimes698dde12018-02-27 11:54:43 +01005952 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005953#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005954
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005955 /* Mappings for error codes */
5956 err_codes_to_names = PyDict_New();
5957 err_names_to_codes = PyDict_New();
5958 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5959 return NULL;
5960 errcode = error_codes;
5961 while (errcode->mnemonic != NULL) {
5962 PyObject *mnemo, *key;
5963 mnemo = PyUnicode_FromString(errcode->mnemonic);
5964 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5965 if (mnemo == NULL || key == NULL)
5966 return NULL;
5967 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5968 return NULL;
5969 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5970 return NULL;
5971 Py_DECREF(key);
5972 Py_DECREF(mnemo);
5973 errcode++;
5974 }
5975 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5976 return NULL;
5977 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5978 return NULL;
5979
5980 lib_codes_to_names = PyDict_New();
5981 if (lib_codes_to_names == NULL)
5982 return NULL;
5983 libcode = library_codes;
5984 while (libcode->library != NULL) {
5985 PyObject *mnemo, *key;
5986 key = PyLong_FromLong(libcode->code);
5987 mnemo = PyUnicode_FromString(libcode->library);
5988 if (key == NULL || mnemo == NULL)
5989 return NULL;
5990 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5991 return NULL;
5992 Py_DECREF(key);
5993 Py_DECREF(mnemo);
5994 libcode++;
5995 }
5996 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5997 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005999 /* OpenSSL version */
6000 /* SSLeay() gives us the version of the library linked against,
6001 which could be different from the headers version.
6002 */
6003 libver = SSLeay();
6004 r = PyLong_FromUnsignedLong(libver);
6005 if (r == NULL)
6006 return NULL;
6007 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6008 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006009 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006010 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6011 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6012 return NULL;
6013 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6014 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6015 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006016
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006017 libver = OPENSSL_VERSION_NUMBER;
6018 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6019 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6020 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6021 return NULL;
6022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006023 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006024}