blob: 2bce4816d26fe78783489d8478da583e3e23c325 [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;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000885
Antoine Pitrou152efa22010-05-16 18:19:27 +0000886 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000887 if (self == NULL)
888 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100892 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700893 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200894 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200895 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700896 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700897 self->ssl_errno = 0;
898 self->c_errno = 0;
899#ifdef MS_WINDOWS
900 self->ws_errno = 0;
901#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200902
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 /* Make sure the SSL error state is initialized */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000905
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000907 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200909 SSL_set_app_data(self->ssl, self);
910 if (sock) {
911 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
912 } else {
913 /* BIOs are reference counted and SSL_set_bio borrows our reference.
914 * To prevent a double free in memory_bio_dealloc() we need to take an
915 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200916 BIO_up_ref(inbio->bio);
917 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200918 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
919 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400920 SSL_set_mode(self->ssl,
921 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000922
Christian Heimes61d478c2018-01-27 15:51:38 +0100923 if (server_hostname != NULL) {
924 if (_ssl_configure_hostname(self, server_hostname) < 0) {
925 Py_DECREF(self);
926 return NULL;
927 }
928 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 /* If the socket is in non-blocking mode or timeout mode, set the BIO
930 * to non-blocking mode (blocking is the default)
931 */
Victor Stinnere2452312015-03-28 03:00:46 +0100932 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
934 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
935 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 PySSL_BEGIN_ALLOW_THREADS
938 if (socket_type == PY_SSL_CLIENT)
939 SSL_set_connect_state(self->ssl);
940 else
941 SSL_set_accept_state(self->ssl);
942 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000943
Antoine Pitroud6494802011-07-21 01:11:30 +0200944 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200945 if (sock != NULL) {
946 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
947 if (self->Socket == NULL) {
948 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200949 return NULL;
950 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100951 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100952 if (owner && owner != Py_None) {
953 if (PySSL_set_owner(self, owner, NULL) == -1) {
954 Py_DECREF(self);
955 return NULL;
956 }
957 }
958 if (session && session != Py_None) {
959 if (PySSL_set_session(self, session, NULL) == -1) {
960 Py_DECREF(self);
961 return NULL;
962 }
963 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000965}
966
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000967/* SSL object methods */
968
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300969/*[clinic input]
970_ssl._SSLSocket.do_handshake
971[clinic start generated code]*/
972
973static PyObject *
974_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
975/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000976{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 int ret;
978 int err;
979 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200980 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200981 _PyTime_t timeout, deadline = 0;
982 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000983
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200984 if (sock) {
985 if (((PyObject*)sock) == Py_None) {
986 _setSSLError("Underlying socket connection gone",
987 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
988 return NULL;
989 }
990 Py_INCREF(sock);
991
992 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100993 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200994 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
995 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000996 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000997
Victor Stinner14690702015-04-06 22:46:13 +0200998 timeout = GET_SOCKET_TIMEOUT(sock);
999 has_timeout = (timeout > 0);
1000 if (has_timeout)
1001 deadline = _PyTime_GetMonotonicClock() + timeout;
1002
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 /* Actually negotiate SSL connection */
1004 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001006 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07001008 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07001010 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001011
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001012 if (PyErr_CheckSignals())
1013 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001014
Victor Stinner14690702015-04-06 22:46:13 +02001015 if (has_timeout)
1016 timeout = deadline - _PyTime_GetMonotonicClock();
1017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001019 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001021 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 } else {
1023 sockstate = SOCKET_OPERATION_OK;
1024 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001025
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001027 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001028 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001029 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1031 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001032 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001033 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1035 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001036 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001037 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1039 break;
1040 }
1041 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001042 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 if (ret < 1)
1044 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001045
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001046 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001047
1048error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001049 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001050 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001051}
1052
Thomas Woutersed03b412007-08-28 21:37:11 +00001053static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001054_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1055{
1056 char buf[X509_NAME_MAXLEN];
1057 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001059 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001060
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001061 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 if (buflen < 0) {
1063 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001064 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001065 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001066 /* initial buffer is too small for oid + terminating null byte */
1067 if (buflen > X509_NAME_MAXLEN - 1) {
1068 /* make OBJ_obj2txt() calculate the required buflen */
1069 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1070 /* allocate len + 1 for terminating NULL byte */
1071 namebuf = PyMem_Malloc(buflen + 1);
1072 if (namebuf == NULL) {
1073 PyErr_NoMemory();
1074 return NULL;
1075 }
1076 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1077 if (buflen < 0) {
1078 _setSSLError(NULL, 0, __FILE__, __LINE__);
1079 goto done;
1080 }
1081 }
1082 if (!buflen && no_name) {
1083 Py_INCREF(Py_None);
1084 name_obj = Py_None;
1085 }
1086 else {
1087 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1088 }
1089
1090 done:
1091 if (buf != namebuf) {
1092 PyMem_Free(namebuf);
1093 }
1094 return name_obj;
1095}
1096
1097static PyObject *
1098_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1099{
1100 Py_ssize_t buflen;
1101 unsigned char *valuebuf = NULL;
1102 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1105 if (buflen < 0) {
1106 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001107 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001109 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001112}
1113
1114static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001115_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001116{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001117 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1118 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1119 PyObject *rdnt;
1120 PyObject *attr = NULL; /* tuple to hold an attribute */
1121 int entry_count = X509_NAME_entry_count(xname);
1122 X509_NAME_ENTRY *entry;
1123 ASN1_OBJECT *name;
1124 ASN1_STRING *value;
1125 int index_counter;
1126 int rdn_level = -1;
1127 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001128
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 dn = PyList_New(0);
1130 if (dn == NULL)
1131 return NULL;
1132 /* now create another tuple to hold the top-level RDN */
1133 rdn = PyList_New(0);
1134 if (rdn == NULL)
1135 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 for (index_counter = 0;
1138 index_counter < entry_count;
1139 index_counter++)
1140 {
1141 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001142
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 /* check to see if we've gotten to a new RDN */
1144 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001145 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 /* yes, new RDN */
1147 /* add old RDN to DN */
1148 rdnt = PyList_AsTuple(rdn);
1149 Py_DECREF(rdn);
1150 if (rdnt == NULL)
1151 goto fail0;
1152 retcode = PyList_Append(dn, rdnt);
1153 Py_DECREF(rdnt);
1154 if (retcode < 0)
1155 goto fail0;
1156 /* create new RDN */
1157 rdn = PyList_New(0);
1158 if (rdn == NULL)
1159 goto fail0;
1160 }
1161 }
Christian Heimes598894f2016-09-05 23:19:05 +02001162 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 /* now add this attribute to the current RDN */
1165 name = X509_NAME_ENTRY_get_object(entry);
1166 value = X509_NAME_ENTRY_get_data(entry);
1167 attr = _create_tuple_for_attribute(name, value);
1168 /*
1169 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1170 entry->set,
1171 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1172 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1173 */
1174 if (attr == NULL)
1175 goto fail1;
1176 retcode = PyList_Append(rdn, attr);
1177 Py_DECREF(attr);
1178 if (retcode < 0)
1179 goto fail1;
1180 }
1181 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001182 if (rdn != NULL) {
1183 if (PyList_GET_SIZE(rdn) > 0) {
1184 rdnt = PyList_AsTuple(rdn);
1185 Py_DECREF(rdn);
1186 if (rdnt == NULL)
1187 goto fail0;
1188 retcode = PyList_Append(dn, rdnt);
1189 Py_DECREF(rdnt);
1190 if (retcode < 0)
1191 goto fail0;
1192 }
1193 else {
1194 Py_DECREF(rdn);
1195 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 /* convert list to tuple */
1199 rdnt = PyList_AsTuple(dn);
1200 Py_DECREF(dn);
1201 if (rdnt == NULL)
1202 return NULL;
1203 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204
1205 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001206 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001207
1208 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 Py_XDECREF(dn);
1210 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211}
1212
1213static PyObject *
1214_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001215
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001216 /* this code follows the procedure outlined in
1217 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1218 function to extract the STACK_OF(GENERAL_NAME),
1219 then iterates through the stack to add the
1220 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001222 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001223 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001224 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 GENERAL_NAMES *names = NULL;
1226 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 BIO *biobuf = NULL;
1228 char buf[2048];
1229 char *vptr;
1230 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001231
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001232 if (certificate == NULL)
1233 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 /* get a memory buffer */
1236 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001237
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001238 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1239 certificate, NID_subject_alt_name, NULL, NULL);
1240 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 if (peer_alt_names == Py_None) {
1242 peer_alt_names = PyList_New(0);
1243 if (peer_alt_names == NULL)
1244 goto fail;
1245 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001247 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001249 int gntype;
1250 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001253 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001254 switch (gntype) {
1255 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 /* we special-case DirName as a tuple of
1257 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001258
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 t = PyTuple_New(2);
1260 if (t == NULL) {
1261 goto fail;
1262 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001264 v = PyUnicode_FromString("DirName");
1265 if (v == NULL) {
1266 Py_DECREF(t);
1267 goto fail;
1268 }
1269 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001271 v = _create_tuple_for_X509_NAME (name->d.dirn);
1272 if (v == NULL) {
1273 Py_DECREF(t);
1274 goto fail;
1275 }
1276 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001277 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001278
Christian Heimes824f7f32013-08-17 00:54:47 +02001279 case GEN_EMAIL:
1280 case GEN_DNS:
1281 case GEN_URI:
1282 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1283 correctly, CVE-2013-4238 */
1284 t = PyTuple_New(2);
1285 if (t == NULL)
1286 goto fail;
1287 switch (gntype) {
1288 case GEN_EMAIL:
1289 v = PyUnicode_FromString("email");
1290 as = name->d.rfc822Name;
1291 break;
1292 case GEN_DNS:
1293 v = PyUnicode_FromString("DNS");
1294 as = name->d.dNSName;
1295 break;
1296 case GEN_URI:
1297 v = PyUnicode_FromString("URI");
1298 as = name->d.uniformResourceIdentifier;
1299 break;
1300 }
1301 if (v == NULL) {
1302 Py_DECREF(t);
1303 goto fail;
1304 }
1305 PyTuple_SET_ITEM(t, 0, v);
1306 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1307 ASN1_STRING_length(as));
1308 if (v == NULL) {
1309 Py_DECREF(t);
1310 goto fail;
1311 }
1312 PyTuple_SET_ITEM(t, 1, v);
1313 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001314
Christian Heimes1c03abd2016-09-06 23:25:35 +02001315 case GEN_RID:
1316 t = PyTuple_New(2);
1317 if (t == NULL)
1318 goto fail;
1319
1320 v = PyUnicode_FromString("Registered ID");
1321 if (v == NULL) {
1322 Py_DECREF(t);
1323 goto fail;
1324 }
1325 PyTuple_SET_ITEM(t, 0, v);
1326
1327 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1328 if (len < 0) {
1329 Py_DECREF(t);
1330 _setSSLError(NULL, 0, __FILE__, __LINE__);
1331 goto fail;
1332 } else if (len >= (int)sizeof(buf)) {
1333 v = PyUnicode_FromString("<INVALID>");
1334 } else {
1335 v = PyUnicode_FromStringAndSize(buf, len);
1336 }
1337 if (v == NULL) {
1338 Py_DECREF(t);
1339 goto fail;
1340 }
1341 PyTuple_SET_ITEM(t, 1, v);
1342 break;
1343
Christian Heimes824f7f32013-08-17 00:54:47 +02001344 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001346 switch (gntype) {
1347 /* check for new general name type */
1348 case GEN_OTHERNAME:
1349 case GEN_X400:
1350 case GEN_EDIPARTY:
1351 case GEN_IPADD:
1352 case GEN_RID:
1353 break;
1354 default:
1355 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1356 "Unknown general name type %d",
1357 gntype) == -1) {
1358 goto fail;
1359 }
1360 break;
1361 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 (void) BIO_reset(biobuf);
1363 GENERAL_NAME_print(biobuf, name);
1364 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1365 if (len < 0) {
1366 _setSSLError(NULL, 0, __FILE__, __LINE__);
1367 goto fail;
1368 }
1369 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001370 if (vptr == NULL) {
1371 PyErr_Format(PyExc_ValueError,
1372 "Invalid value %.200s",
1373 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001375 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 t = PyTuple_New(2);
1377 if (t == NULL)
1378 goto fail;
1379 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1380 if (v == NULL) {
1381 Py_DECREF(t);
1382 goto fail;
1383 }
1384 PyTuple_SET_ITEM(t, 0, v);
1385 v = PyUnicode_FromStringAndSize((vptr + 1),
1386 (len - (vptr - buf + 1)));
1387 if (v == NULL) {
1388 Py_DECREF(t);
1389 goto fail;
1390 }
1391 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001392 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001394
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 if (PyList_Append(peer_alt_names, t) < 0) {
1398 Py_DECREF(t);
1399 goto fail;
1400 }
1401 Py_DECREF(t);
1402 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001403 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001404 }
1405 BIO_free(biobuf);
1406 if (peer_alt_names != Py_None) {
1407 v = PyList_AsTuple(peer_alt_names);
1408 Py_DECREF(peer_alt_names);
1409 return v;
1410 } else {
1411 return peer_alt_names;
1412 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001413
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001414
1415 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 if (biobuf != NULL)
1417 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 if (peer_alt_names != Py_None) {
1420 Py_XDECREF(peer_alt_names);
1421 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424}
1425
1426static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001427_get_aia_uri(X509 *certificate, int nid) {
1428 PyObject *lst = NULL, *ostr = NULL;
1429 int i, result;
1430 AUTHORITY_INFO_ACCESS *info;
1431
1432 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001433 if (info == NULL)
1434 return Py_None;
1435 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1436 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001437 return Py_None;
1438 }
1439
1440 if ((lst = PyList_New(0)) == NULL) {
1441 goto fail;
1442 }
1443
1444 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1445 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1446 ASN1_IA5STRING *uri;
1447
1448 if ((OBJ_obj2nid(ad->method) != nid) ||
1449 (ad->location->type != GEN_URI)) {
1450 continue;
1451 }
1452 uri = ad->location->d.uniformResourceIdentifier;
1453 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1454 uri->length);
1455 if (ostr == NULL) {
1456 goto fail;
1457 }
1458 result = PyList_Append(lst, ostr);
1459 Py_DECREF(ostr);
1460 if (result < 0) {
1461 goto fail;
1462 }
1463 }
1464 AUTHORITY_INFO_ACCESS_free(info);
1465
1466 /* convert to tuple or None */
1467 if (PyList_Size(lst) == 0) {
1468 Py_DECREF(lst);
1469 return Py_None;
1470 } else {
1471 PyObject *tup;
1472 tup = PyList_AsTuple(lst);
1473 Py_DECREF(lst);
1474 return tup;
1475 }
1476
1477 fail:
1478 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001479 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001480 return NULL;
1481}
1482
1483static PyObject *
1484_get_crl_dp(X509 *certificate) {
1485 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001486 int i, j;
1487 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001488
Christian Heimes598894f2016-09-05 23:19:05 +02001489 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001490
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001491 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001492 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001493
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001494 lst = PyList_New(0);
1495 if (lst == NULL)
1496 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001497
1498 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1499 DIST_POINT *dp;
1500 STACK_OF(GENERAL_NAME) *gns;
1501
1502 dp = sk_DIST_POINT_value(dps, i);
1503 gns = dp->distpoint->name.fullname;
1504
1505 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1506 GENERAL_NAME *gn;
1507 ASN1_IA5STRING *uri;
1508 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001509 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001510
1511 gn = sk_GENERAL_NAME_value(gns, j);
1512 if (gn->type != GEN_URI) {
1513 continue;
1514 }
1515 uri = gn->d.uniformResourceIdentifier;
1516 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1517 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001518 if (ouri == NULL)
1519 goto done;
1520
1521 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001522 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001523 if (err < 0)
1524 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001525 }
1526 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001527
1528 /* Convert to tuple. */
1529 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1530
1531 done:
1532 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001533 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001534 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001535}
1536
1537static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001538_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 PyObject *retval = NULL;
1541 BIO *biobuf = NULL;
1542 PyObject *peer;
1543 PyObject *peer_alt_names = NULL;
1544 PyObject *issuer;
1545 PyObject *version;
1546 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001547 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 ASN1_INTEGER *serialNumber;
1549 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001550 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001551 ASN1_TIME *notBefore, *notAfter;
1552 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 retval = PyDict_New();
1555 if (retval == NULL)
1556 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 peer = _create_tuple_for_X509_NAME(
1559 X509_get_subject_name(certificate));
1560 if (peer == NULL)
1561 goto fail0;
1562 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1563 Py_DECREF(peer);
1564 goto fail0;
1565 }
1566 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001567
Antoine Pitroufb046912010-11-09 20:21:19 +00001568 issuer = _create_tuple_for_X509_NAME(
1569 X509_get_issuer_name(certificate));
1570 if (issuer == NULL)
1571 goto fail0;
1572 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001574 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001576 Py_DECREF(issuer);
1577
1578 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001579 if (version == NULL)
1580 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001581 if (PyDict_SetItemString(retval, "version", version) < 0) {
1582 Py_DECREF(version);
1583 goto fail0;
1584 }
1585 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001586
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 /* get a memory buffer */
1588 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001589
Antoine Pitroufb046912010-11-09 20:21:19 +00001590 (void) BIO_reset(biobuf);
1591 serialNumber = X509_get_serialNumber(certificate);
1592 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1593 i2a_ASN1_INTEGER(biobuf, serialNumber);
1594 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1595 if (len < 0) {
1596 _setSSLError(NULL, 0, __FILE__, __LINE__);
1597 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001599 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1600 if (sn_obj == NULL)
1601 goto fail1;
1602 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1603 Py_DECREF(sn_obj);
1604 goto fail1;
1605 }
1606 Py_DECREF(sn_obj);
1607
1608 (void) BIO_reset(biobuf);
1609 notBefore = X509_get_notBefore(certificate);
1610 ASN1_TIME_print(biobuf, notBefore);
1611 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1612 if (len < 0) {
1613 _setSSLError(NULL, 0, __FILE__, __LINE__);
1614 goto fail1;
1615 }
1616 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1617 if (pnotBefore == NULL)
1618 goto fail1;
1619 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1620 Py_DECREF(pnotBefore);
1621 goto fail1;
1622 }
1623 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001624
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 (void) BIO_reset(biobuf);
1626 notAfter = X509_get_notAfter(certificate);
1627 ASN1_TIME_print(biobuf, notAfter);
1628 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1629 if (len < 0) {
1630 _setSSLError(NULL, 0, __FILE__, __LINE__);
1631 goto fail1;
1632 }
1633 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1634 if (pnotAfter == NULL)
1635 goto fail1;
1636 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1637 Py_DECREF(pnotAfter);
1638 goto fail1;
1639 }
1640 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001641
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001642 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 peer_alt_names = _get_peer_alt_names(certificate);
1645 if (peer_alt_names == NULL)
1646 goto fail1;
1647 else if (peer_alt_names != Py_None) {
1648 if (PyDict_SetItemString(retval, "subjectAltName",
1649 peer_alt_names) < 0) {
1650 Py_DECREF(peer_alt_names);
1651 goto fail1;
1652 }
1653 Py_DECREF(peer_alt_names);
1654 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001655
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001656 /* Authority Information Access: OCSP URIs */
1657 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1658 if (obj == NULL) {
1659 goto fail1;
1660 } else if (obj != Py_None) {
1661 result = PyDict_SetItemString(retval, "OCSP", obj);
1662 Py_DECREF(obj);
1663 if (result < 0) {
1664 goto fail1;
1665 }
1666 }
1667
1668 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1669 if (obj == NULL) {
1670 goto fail1;
1671 } else if (obj != Py_None) {
1672 result = PyDict_SetItemString(retval, "caIssuers", obj);
1673 Py_DECREF(obj);
1674 if (result < 0) {
1675 goto fail1;
1676 }
1677 }
1678
1679 /* CDP (CRL distribution points) */
1680 obj = _get_crl_dp(certificate);
1681 if (obj == NULL) {
1682 goto fail1;
1683 } else if (obj != Py_None) {
1684 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1685 Py_DECREF(obj);
1686 if (result < 0) {
1687 goto fail1;
1688 }
1689 }
1690
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001691 BIO_free(biobuf);
1692 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001693
1694 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 if (biobuf != NULL)
1696 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001697 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001698 Py_XDECREF(retval);
1699 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001700}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001701
Christian Heimes9a5395a2013-06-17 15:44:12 +02001702static PyObject *
1703_certificate_to_der(X509 *certificate)
1704{
1705 unsigned char *bytes_buf = NULL;
1706 int len;
1707 PyObject *retval;
1708
1709 bytes_buf = NULL;
1710 len = i2d_X509(certificate, &bytes_buf);
1711 if (len < 0) {
1712 _setSSLError(NULL, 0, __FILE__, __LINE__);
1713 return NULL;
1714 }
1715 /* this is actually an immutable bytes sequence */
1716 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1717 OPENSSL_free(bytes_buf);
1718 return retval;
1719}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001720
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001721/*[clinic input]
1722_ssl._test_decode_cert
1723 path: object(converter="PyUnicode_FSConverter")
1724 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001725
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001726[clinic start generated code]*/
1727
1728static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001729_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1730/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001731{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 X509 *x=NULL;
1734 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1737 PyErr_SetString(PySSLErrorObject,
1738 "Can't malloc memory to read file");
1739 goto fail0;
1740 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001742 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 PyErr_SetString(PySSLErrorObject,
1744 "Can't open file");
1745 goto fail0;
1746 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001747
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1749 if (x == NULL) {
1750 PyErr_SetString(PySSLErrorObject,
1751 "Error decoding PEM-encoded file");
1752 goto fail0;
1753 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001754
Antoine Pitroufb046912010-11-09 20:21:19 +00001755 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001756 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001757
1758 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001759 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 if (cert != NULL) BIO_free(cert);
1761 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001762}
1763
1764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001765/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001766_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001767 der as binary_mode: bool = False
1768 /
1769
1770Returns the certificate for the peer.
1771
1772If no certificate was provided, returns None. If a certificate was
1773provided, but not validated, returns an empty dictionary. Otherwise
1774returns a dict containing information about the peer certificate.
1775
1776If the optional argument is True, returns a DER-encoded copy of the
1777peer certificate, or None if no certificate was provided. This will
1778return the certificate even if it wasn't validated.
1779[clinic start generated code]*/
1780
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001782_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1783/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001784{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001785 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001786 X509 *peer_cert;
1787 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788
Christian Heimes66dc33b2017-05-23 16:02:02 -07001789 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001790 PyErr_SetString(PyExc_ValueError,
1791 "handshake not done yet");
1792 return NULL;
1793 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001794 peer_cert = SSL_get_peer_certificate(self->ssl);
1795 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001796 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001797
Antoine Pitrou721738f2012-08-15 23:20:39 +02001798 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001800 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001802 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001804 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001806 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 X509_free(peer_cert);
1809 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001810}
1811
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001812static PyObject *
1813cipher_to_tuple(const SSL_CIPHER *cipher)
1814{
1815 const char *cipher_name, *cipher_protocol;
1816 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 if (retval == NULL)
1818 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001819
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001820 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001822 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 PyTuple_SET_ITEM(retval, 0, Py_None);
1824 } else {
1825 v = PyUnicode_FromString(cipher_name);
1826 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001827 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 PyTuple_SET_ITEM(retval, 0, v);
1829 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001830
1831 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001832 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001833 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 PyTuple_SET_ITEM(retval, 1, Py_None);
1835 } else {
1836 v = PyUnicode_FromString(cipher_protocol);
1837 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001838 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 PyTuple_SET_ITEM(retval, 1, v);
1840 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001841
1842 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001844 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001848
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001849 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001850 Py_DECREF(retval);
1851 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001852}
1853
Christian Heimes25bfcd52016-09-06 00:04:45 +02001854#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1855static PyObject *
1856cipher_to_dict(const SSL_CIPHER *cipher)
1857{
1858 const char *cipher_name, *cipher_protocol;
1859
1860 unsigned long cipher_id;
1861 int alg_bits, strength_bits, len;
1862 char buf[512] = {0};
1863#if OPENSSL_VERSION_1_1
1864 int aead, nid;
1865 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1866#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001867
1868 /* can be NULL */
1869 cipher_name = SSL_CIPHER_get_name(cipher);
1870 cipher_protocol = SSL_CIPHER_get_version(cipher);
1871 cipher_id = SSL_CIPHER_get_id(cipher);
1872 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001873 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1874 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001875 if (len > 1 && buf[len-1] == '\n')
1876 buf[len-1] = '\0';
1877 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1878
1879#if OPENSSL_VERSION_1_1
1880 aead = SSL_CIPHER_is_aead(cipher);
1881 nid = SSL_CIPHER_get_cipher_nid(cipher);
1882 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1883 nid = SSL_CIPHER_get_digest_nid(cipher);
1884 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1885 nid = SSL_CIPHER_get_kx_nid(cipher);
1886 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1887 nid = SSL_CIPHER_get_auth_nid(cipher);
1888 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1889#endif
1890
Victor Stinner410b9882016-09-12 12:00:23 +02001891 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001892 "{sksssssssisi"
1893#if OPENSSL_VERSION_1_1
1894 "sOssssssss"
1895#endif
1896 "}",
1897 "id", cipher_id,
1898 "name", cipher_name,
1899 "protocol", cipher_protocol,
1900 "description", buf,
1901 "strength_bits", strength_bits,
1902 "alg_bits", alg_bits
1903#if OPENSSL_VERSION_1_1
1904 ,"aead", aead ? Py_True : Py_False,
1905 "symmetric", skcipher,
1906 "digest", digest,
1907 "kea", kx,
1908 "auth", auth
1909#endif
1910 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001911}
1912#endif
1913
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001914/*[clinic input]
1915_ssl._SSLSocket.shared_ciphers
1916[clinic start generated code]*/
1917
1918static PyObject *
1919_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1920/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001921{
1922 STACK_OF(SSL_CIPHER) *ciphers;
1923 int i;
1924 PyObject *res;
1925
Christian Heimes598894f2016-09-05 23:19:05 +02001926 ciphers = SSL_get_ciphers(self->ssl);
1927 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001928 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001929 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1930 if (!res)
1931 return NULL;
1932 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1933 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1934 if (!tup) {
1935 Py_DECREF(res);
1936 return NULL;
1937 }
1938 PyList_SET_ITEM(res, i, tup);
1939 }
1940 return res;
1941}
1942
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001943/*[clinic input]
1944_ssl._SSLSocket.cipher
1945[clinic start generated code]*/
1946
1947static PyObject *
1948_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1949/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001950{
1951 const SSL_CIPHER *current;
1952
1953 if (self->ssl == NULL)
1954 Py_RETURN_NONE;
1955 current = SSL_get_current_cipher(self->ssl);
1956 if (current == NULL)
1957 Py_RETURN_NONE;
1958 return cipher_to_tuple(current);
1959}
1960
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001961/*[clinic input]
1962_ssl._SSLSocket.version
1963[clinic start generated code]*/
1964
1965static PyObject *
1966_ssl__SSLSocket_version_impl(PySSLSocket *self)
1967/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001968{
1969 const char *version;
1970
1971 if (self->ssl == NULL)
1972 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001973 if (!SSL_is_init_finished(self->ssl)) {
1974 /* handshake not finished */
1975 Py_RETURN_NONE;
1976 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001977 version = SSL_get_version(self->ssl);
1978 if (!strcmp(version, "unknown"))
1979 Py_RETURN_NONE;
1980 return PyUnicode_FromString(version);
1981}
1982
Christian Heimes29eab552018-02-25 12:31:33 +01001983#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001984/*[clinic input]
1985_ssl._SSLSocket.selected_npn_protocol
1986[clinic start generated code]*/
1987
1988static PyObject *
1989_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1990/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1991{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001992 const unsigned char *out;
1993 unsigned int outlen;
1994
Victor Stinner4569cd52013-06-23 14:58:43 +02001995 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001996 &out, &outlen);
1997
1998 if (out == NULL)
1999 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002000 return PyUnicode_FromStringAndSize((char *)out, outlen);
2001}
2002#endif
2003
Christian Heimes29eab552018-02-25 12:31:33 +01002004#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002005/*[clinic input]
2006_ssl._SSLSocket.selected_alpn_protocol
2007[clinic start generated code]*/
2008
2009static PyObject *
2010_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2011/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2012{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002013 const unsigned char *out;
2014 unsigned int outlen;
2015
2016 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2017
2018 if (out == NULL)
2019 Py_RETURN_NONE;
2020 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002021}
2022#endif
2023
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002024/*[clinic input]
2025_ssl._SSLSocket.compression
2026[clinic start generated code]*/
2027
2028static PyObject *
2029_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2030/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2031{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002032#ifdef OPENSSL_NO_COMP
2033 Py_RETURN_NONE;
2034#else
2035 const COMP_METHOD *comp_method;
2036 const char *short_name;
2037
2038 if (self->ssl == NULL)
2039 Py_RETURN_NONE;
2040 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002041 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002042 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002043 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002044 if (short_name == NULL)
2045 Py_RETURN_NONE;
2046 return PyUnicode_DecodeFSDefault(short_name);
2047#endif
2048}
2049
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002050static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2051 Py_INCREF(self->ctx);
2052 return self->ctx;
2053}
2054
2055static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2056 void *closure) {
2057
2058 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002059#if !HAVE_SNI
2060 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2061 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002062 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002063#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002064 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002065 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002066 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002067#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002068 } else {
Ned Deily4531ec72018-06-11 20:26:28 -04002069 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002070 return -1;
2071 }
2072
2073 return 0;
2074}
2075
2076PyDoc_STRVAR(PySSL_set_context_doc,
2077"_setter_context(ctx)\n\
2078\
2079This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002080used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002081on the SSLContext to change the certificate information associated with the\n\
2082SSLSocket before the cryptographic exchange handshake messages\n");
2083
2084
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002085static PyObject *
2086PySSL_get_server_side(PySSLSocket *self, void *c)
2087{
2088 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2089}
2090
2091PyDoc_STRVAR(PySSL_get_server_side_doc,
2092"Whether this is a server-side socket.");
2093
2094static PyObject *
2095PySSL_get_server_hostname(PySSLSocket *self, void *c)
2096{
2097 if (self->server_hostname == NULL)
2098 Py_RETURN_NONE;
2099 Py_INCREF(self->server_hostname);
2100 return self->server_hostname;
2101}
2102
2103PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2104"The currently set server hostname (for SNI).");
2105
2106static PyObject *
2107PySSL_get_owner(PySSLSocket *self, void *c)
2108{
2109 PyObject *owner;
2110
2111 if (self->owner == NULL)
2112 Py_RETURN_NONE;
2113
2114 owner = PyWeakref_GetObject(self->owner);
2115 Py_INCREF(owner);
2116 return owner;
2117}
2118
2119static int
2120PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2121{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002122 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002123 if (self->owner == NULL)
2124 return -1;
2125 return 0;
2126}
2127
2128PyDoc_STRVAR(PySSL_get_owner_doc,
2129"The Python-level owner of this object.\
2130Passed as \"self\" in servername callback.");
2131
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002132
Antoine Pitrou152efa22010-05-16 18:19:27 +00002133static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002134{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 if (self->ssl)
2136 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002138 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002139 Py_XDECREF(self->server_hostname);
2140 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002141 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002142}
2143
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002144/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002145 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002146 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002147 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002148
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002149static int
Victor Stinner14690702015-04-06 22:46:13 +02002150PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002151{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002152 int rc;
2153#ifdef HAVE_POLL
2154 struct pollfd pollfd;
2155 _PyTime_t ms;
2156#else
2157 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 fd_set fds;
2159 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002160#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002163 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002165 else if (timeout < 0) {
2166 if (s->sock_timeout > 0)
2167 return SOCKET_HAS_TIMED_OUT;
2168 else
2169 return SOCKET_IS_BLOCKING;
2170 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002173 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002174 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 /* Prefer poll, if available, since you can poll() any fd
2177 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002178#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002179 pollfd.fd = s->sock_fd;
2180 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002181
Victor Stinner14690702015-04-06 22:46:13 +02002182 /* timeout is in seconds, poll() uses milliseconds */
2183 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002184 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002185
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002186 PySSL_BEGIN_ALLOW_THREADS
2187 rc = poll(&pollfd, 1, (int)ms);
2188 PySSL_END_ALLOW_THREADS
2189#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002191 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002193
Victor Stinner14690702015-04-06 22:46:13 +02002194 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002195
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 FD_ZERO(&fds);
2197 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002198
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002199 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002201 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002202 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002203 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002205 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002207#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2210 (when we are able to write or when there's something to read) */
2211 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002212}
2213
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002214/*[clinic input]
2215_ssl._SSLSocket.write
2216 b: Py_buffer
2217 /
2218
2219Writes the bytes-like object b into the SSL object.
2220
2221Returns the number of bytes written.
2222[clinic start generated code]*/
2223
2224static PyObject *
2225_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2226/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002227{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 int len;
2229 int sockstate;
2230 int err;
2231 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002232 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002233 _PyTime_t timeout, deadline = 0;
2234 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002235
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002236 if (sock != NULL) {
2237 if (((PyObject*)sock) == Py_None) {
2238 _setSSLError("Underlying socket connection gone",
2239 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2240 return NULL;
2241 }
2242 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 }
2244
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002245 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002246 PyErr_Format(PyExc_OverflowError,
2247 "string longer than %d bytes", INT_MAX);
2248 goto error;
2249 }
2250
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002251 if (sock != NULL) {
2252 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002253 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002254 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2255 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2256 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002257
Victor Stinner14690702015-04-06 22:46:13 +02002258 timeout = GET_SOCKET_TIMEOUT(sock);
2259 has_timeout = (timeout > 0);
2260 if (has_timeout)
2261 deadline = _PyTime_GetMonotonicClock() + timeout;
2262
2263 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002264 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002265 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 "The write operation timed out");
2267 goto error;
2268 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2269 PyErr_SetString(PySSLErrorObject,
2270 "Underlying socket has been closed.");
2271 goto error;
2272 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2273 PyErr_SetString(PySSLErrorObject,
2274 "Underlying socket too large for select().");
2275 goto error;
2276 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002280 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002281 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002283 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002284
2285 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002287
Victor Stinner14690702015-04-06 22:46:13 +02002288 if (has_timeout)
2289 timeout = deadline - _PyTime_GetMonotonicClock();
2290
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002292 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002294 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 } else {
2296 sockstate = SOCKET_OPERATION_OK;
2297 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002298
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002300 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 "The write operation timed out");
2302 goto error;
2303 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2304 PyErr_SetString(PySSLErrorObject,
2305 "Underlying socket has been closed.");
2306 goto error;
2307 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2308 break;
2309 }
2310 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002311
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002312 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313 if (len > 0)
2314 return PyLong_FromLong(len);
2315 else
2316 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002317
2318error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002319 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002321}
2322
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002323/*[clinic input]
2324_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002325
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002326Returns the number of already decrypted bytes available for read, pending on the connection.
2327[clinic start generated code]*/
2328
2329static PyObject *
2330_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2331/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002332{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 PySSL_BEGIN_ALLOW_THREADS
2336 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002337 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 PySSL_END_ALLOW_THREADS
2339 if (count < 0)
2340 return PySSL_SetError(self, count, __FILE__, __LINE__);
2341 else
2342 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002343}
2344
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002345/*[clinic input]
2346_ssl._SSLSocket.read
2347 size as len: int
2348 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002349 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002350 ]
2351 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002352
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002353Read up to size bytes from the SSL socket.
2354[clinic start generated code]*/
2355
2356static PyObject *
2357_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2358 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002359/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002360{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002362 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002363 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 int sockstate;
2365 int err;
2366 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002367 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002368 _PyTime_t timeout, deadline = 0;
2369 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002370
Martin Panter5503d472016-03-27 05:35:19 +00002371 if (!group_right_1 && len < 0) {
2372 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2373 return NULL;
2374 }
2375
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002376 if (sock != NULL) {
2377 if (((PyObject*)sock) == Py_None) {
2378 _setSSLError("Underlying socket connection gone",
2379 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2380 return NULL;
2381 }
2382 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002383 }
2384
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002385 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002386 dest = PyBytes_FromStringAndSize(NULL, len);
2387 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002388 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002389 if (len == 0) {
2390 Py_XDECREF(sock);
2391 return dest;
2392 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002393 mem = PyBytes_AS_STRING(dest);
2394 }
2395 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002396 mem = buffer->buf;
2397 if (len <= 0 || len > buffer->len) {
2398 len = (int) buffer->len;
2399 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002400 PyErr_SetString(PyExc_OverflowError,
2401 "maximum length can't fit in a C 'int'");
2402 goto error;
2403 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002404 if (len == 0) {
2405 count = 0;
2406 goto done;
2407 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002408 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002409 }
2410
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002411 if (sock != NULL) {
2412 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002413 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002414 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2415 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2416 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417
Victor Stinner14690702015-04-06 22:46:13 +02002418 timeout = GET_SOCKET_TIMEOUT(sock);
2419 has_timeout = (timeout > 0);
2420 if (has_timeout)
2421 deadline = _PyTime_GetMonotonicClock() + timeout;
2422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 PySSL_BEGIN_ALLOW_THREADS
2425 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002426 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002428
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002429 if (PyErr_CheckSignals())
2430 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002431
Victor Stinner14690702015-04-06 22:46:13 +02002432 if (has_timeout)
2433 timeout = deadline - _PyTime_GetMonotonicClock();
2434
Steve Dowere6eb48c2017-09-08 15:16:15 -07002435 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002437 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002439 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002440 } else if (err == SSL_ERROR_ZERO_RETURN &&
2441 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 {
2443 count = 0;
2444 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002446 else
2447 sockstate = SOCKET_OPERATION_OK;
2448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002450 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 "The read operation timed out");
2452 goto error;
2453 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2454 break;
2455 }
2456 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002457
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002458 if (count <= 0) {
2459 PySSL_SetError(self, count, __FILE__, __LINE__);
2460 goto error;
2461 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002462
2463done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002464 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002465 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002466 _PyBytes_Resize(&dest, count);
2467 return dest;
2468 }
2469 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002470 return PyLong_FromLong(count);
2471 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002472
2473error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002474 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002475 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002476 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002478}
2479
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002480/*[clinic input]
2481_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002483Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002484[clinic start generated code]*/
2485
2486static PyObject *
2487_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002488/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002489{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002490 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002491 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002492 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002493 _PyTime_t timeout, deadline = 0;
2494 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002495
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002496 if (sock != NULL) {
2497 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002498 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002499 _setSSLError("Underlying socket connection gone",
2500 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2501 return NULL;
2502 }
2503 Py_INCREF(sock);
2504
2505 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002506 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002507 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2508 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510
Victor Stinner14690702015-04-06 22:46:13 +02002511 timeout = GET_SOCKET_TIMEOUT(sock);
2512 has_timeout = (timeout > 0);
2513 if (has_timeout)
2514 deadline = _PyTime_GetMonotonicClock() + timeout;
2515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002516 while (1) {
2517 PySSL_BEGIN_ALLOW_THREADS
2518 /* Disable read-ahead so that unwrap can work correctly.
2519 * Otherwise OpenSSL might read in too much data,
2520 * eating clear text data that happens to be
2521 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002522 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002523 * function is used and the shutdown_seen_zero != 0
2524 * condition is met.
2525 */
2526 if (self->shutdown_seen_zero)
2527 SSL_set_read_ahead(self->ssl, 0);
2528 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002529 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002530 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2533 if (err > 0)
2534 break;
2535 if (err == 0) {
2536 /* Don't loop endlessly; instead preserve legacy
2537 behaviour of trying SSL_shutdown() only twice.
2538 This looks necessary for OpenSSL < 0.9.8m */
2539 if (++zeros > 1)
2540 break;
2541 /* Shutdown was sent, now try receiving */
2542 self->shutdown_seen_zero = 1;
2543 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002544 }
2545
Victor Stinner14690702015-04-06 22:46:13 +02002546 if (has_timeout)
2547 timeout = deadline - _PyTime_GetMonotonicClock();
2548
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002549 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002550 _PySSL_UPDATE_ERRNO(self, err);
2551 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002552 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002553 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002554 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002555 else
2556 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002559 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002560 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002561 "The read operation timed out");
2562 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002563 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002564 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002565 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002566 }
2567 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2568 PyErr_SetString(PySSLErrorObject,
2569 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002570 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002571 }
2572 else if (sockstate != SOCKET_OPERATION_OK)
2573 /* Retain the SSL error code */
2574 break;
2575 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002576
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002577 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002578 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002579 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002581 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002582 /* It's already INCREF'ed */
2583 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002584 else
2585 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002586
2587error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002588 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002589 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002590}
2591
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002592/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002593_ssl._SSLSocket.get_channel_binding
2594 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002595
Christian Heimes141c5e82018-02-24 21:10:57 +01002596Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002597
Christian Heimes141c5e82018-02-24 21:10:57 +01002598Raise ValueError if the requested `cb_type` is not supported. Return bytes
2599of the data or None if the data is not available (e.g. before the handshake).
2600Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002601[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002602
Antoine Pitroud6494802011-07-21 01:11:30 +02002603static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002604_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2605 const char *cb_type)
2606/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002607{
Antoine Pitroud6494802011-07-21 01:11:30 +02002608 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002609 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002610
Christian Heimes141c5e82018-02-24 21:10:57 +01002611 if (strcmp(cb_type, "tls-unique") == 0) {
2612 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2613 /* if session is resumed XOR we are the client */
2614 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2615 }
2616 else {
2617 /* if a new session XOR we are the server */
2618 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2619 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002620 }
2621 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002622 PyErr_Format(
2623 PyExc_ValueError,
2624 "'%s' channel binding type not implemented",
2625 cb_type
2626 );
2627 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002628 }
2629
2630 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002631 if (len == 0)
2632 Py_RETURN_NONE;
2633
Christian Heimes141c5e82018-02-24 21:10:57 +01002634 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002635}
2636
Christian Heimes99a65702016-09-10 23:44:53 +02002637#ifdef OPENSSL_VERSION_1_1
2638
2639static SSL_SESSION*
2640_ssl_session_dup(SSL_SESSION *session) {
2641 SSL_SESSION *newsession = NULL;
2642 int slen;
2643 unsigned char *senc = NULL, *p;
2644 const unsigned char *const_p;
2645
2646 if (session == NULL) {
2647 PyErr_SetString(PyExc_ValueError, "Invalid session");
2648 goto error;
2649 }
2650
2651 /* get length */
2652 slen = i2d_SSL_SESSION(session, NULL);
2653 if (slen == 0 || slen > 0xFF00) {
2654 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2655 goto error;
2656 }
2657 if ((senc = PyMem_Malloc(slen)) == NULL) {
2658 PyErr_NoMemory();
2659 goto error;
2660 }
2661 p = senc;
2662 if (!i2d_SSL_SESSION(session, &p)) {
2663 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2664 goto error;
2665 }
2666 const_p = senc;
2667 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2668 if (session == NULL) {
2669 goto error;
2670 }
2671 PyMem_Free(senc);
2672 return newsession;
2673 error:
2674 if (senc != NULL) {
2675 PyMem_Free(senc);
2676 }
2677 return NULL;
2678}
2679#endif
2680
2681static PyObject *
2682PySSL_get_session(PySSLSocket *self, void *closure) {
2683 /* get_session can return sessions from a server-side connection,
2684 * it does not check for handshake done or client socket. */
2685 PySSLSession *pysess;
2686 SSL_SESSION *session;
2687
2688#ifdef OPENSSL_VERSION_1_1
2689 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2690 * https://github.com/openssl/openssl/issues/1550 */
2691 session = SSL_get0_session(self->ssl); /* borrowed reference */
2692 if (session == NULL) {
2693 Py_RETURN_NONE;
2694 }
2695 if ((session = _ssl_session_dup(session)) == NULL) {
2696 return NULL;
2697 }
2698#else
2699 session = SSL_get1_session(self->ssl);
2700 if (session == NULL) {
2701 Py_RETURN_NONE;
2702 }
2703#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002704 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002705 if (pysess == NULL) {
2706 SSL_SESSION_free(session);
2707 return NULL;
2708 }
2709
2710 assert(self->ctx);
2711 pysess->ctx = self->ctx;
2712 Py_INCREF(pysess->ctx);
2713 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002714 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002715 return (PyObject *)pysess;
2716}
2717
2718static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2719 void *closure)
2720 {
2721 PySSLSession *pysess;
2722#ifdef OPENSSL_VERSION_1_1
2723 SSL_SESSION *session;
2724#endif
2725 int result;
2726
2727 if (!PySSLSession_Check(value)) {
Ned Deily4531ec72018-06-11 20:26:28 -04002728 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
Christian Heimes99a65702016-09-10 23:44:53 +02002729 return -1;
2730 }
2731 pysess = (PySSLSession *)value;
2732
2733 if (self->ctx->ctx != pysess->ctx->ctx) {
2734 PyErr_SetString(PyExc_ValueError,
2735 "Session refers to a different SSLContext.");
2736 return -1;
2737 }
2738 if (self->socket_type != PY_SSL_CLIENT) {
2739 PyErr_SetString(PyExc_ValueError,
2740 "Cannot set session for server-side SSLSocket.");
2741 return -1;
2742 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002743 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002744 PyErr_SetString(PyExc_ValueError,
2745 "Cannot set session after handshake.");
2746 return -1;
2747 }
2748#ifdef OPENSSL_VERSION_1_1
2749 /* duplicate session */
2750 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2751 return -1;
2752 }
2753 result = SSL_set_session(self->ssl, session);
2754 /* free duplicate, SSL_set_session() bumps ref count */
2755 SSL_SESSION_free(session);
2756#else
2757 result = SSL_set_session(self->ssl, pysess->session);
2758#endif
2759 if (result == 0) {
2760 _setSSLError(NULL, 0, __FILE__, __LINE__);
2761 return -1;
2762 }
2763 return 0;
2764}
2765
2766PyDoc_STRVAR(PySSL_set_session_doc,
2767"_setter_session(session)\n\
2768\
2769Get / set SSLSession.");
2770
2771static PyObject *
2772PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2773 if (SSL_session_reused(self->ssl)) {
2774 Py_RETURN_TRUE;
2775 } else {
2776 Py_RETURN_FALSE;
2777 }
2778}
2779
2780PyDoc_STRVAR(PySSL_get_session_reused_doc,
2781"Was the client session reused during handshake?");
2782
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002783static PyGetSetDef ssl_getsetlist[] = {
2784 {"context", (getter) PySSL_get_context,
2785 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002786 {"server_side", (getter) PySSL_get_server_side, NULL,
2787 PySSL_get_server_side_doc},
2788 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2789 PySSL_get_server_hostname_doc},
2790 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2791 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002792 {"session", (getter) PySSL_get_session,
2793 (setter) PySSL_set_session, PySSL_set_session_doc},
2794 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2795 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002796 {NULL}, /* sentinel */
2797};
2798
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002799static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002800 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2801 _SSL__SSLSOCKET_WRITE_METHODDEF
2802 _SSL__SSLSOCKET_READ_METHODDEF
2803 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002804 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2805 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002806 _SSL__SSLSOCKET_CIPHER_METHODDEF
2807 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2808 _SSL__SSLSOCKET_VERSION_METHODDEF
2809 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2810 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2811 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2812 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002813 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002814};
2815
Antoine Pitrou152efa22010-05-16 18:19:27 +00002816static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002817 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002818 "_ssl._SSLSocket", /*tp_name*/
2819 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002820 0, /*tp_itemsize*/
2821 /* methods */
2822 (destructor)PySSL_dealloc, /*tp_dealloc*/
2823 0, /*tp_print*/
2824 0, /*tp_getattr*/
2825 0, /*tp_setattr*/
2826 0, /*tp_reserved*/
2827 0, /*tp_repr*/
2828 0, /*tp_as_number*/
2829 0, /*tp_as_sequence*/
2830 0, /*tp_as_mapping*/
2831 0, /*tp_hash*/
2832 0, /*tp_call*/
2833 0, /*tp_str*/
2834 0, /*tp_getattro*/
2835 0, /*tp_setattro*/
2836 0, /*tp_as_buffer*/
2837 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2838 0, /*tp_doc*/
2839 0, /*tp_traverse*/
2840 0, /*tp_clear*/
2841 0, /*tp_richcompare*/
2842 0, /*tp_weaklistoffset*/
2843 0, /*tp_iter*/
2844 0, /*tp_iternext*/
2845 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002846 0, /*tp_members*/
2847 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002848};
2849
Antoine Pitrou152efa22010-05-16 18:19:27 +00002850
2851/*
2852 * _SSLContext objects
2853 */
2854
Christian Heimes5fe668c2016-09-12 00:01:11 +02002855static int
2856_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2857{
2858 int mode;
2859 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2860
2861 switch(n) {
2862 case PY_SSL_CERT_NONE:
2863 mode = SSL_VERIFY_NONE;
2864 break;
2865 case PY_SSL_CERT_OPTIONAL:
2866 mode = SSL_VERIFY_PEER;
2867 break;
2868 case PY_SSL_CERT_REQUIRED:
2869 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2870 break;
2871 default:
2872 PyErr_SetString(PyExc_ValueError,
2873 "invalid value for verify_mode");
2874 return -1;
2875 }
2876 /* keep current verify cb */
2877 verify_cb = SSL_CTX_get_verify_callback(ctx);
2878 SSL_CTX_set_verify(ctx, mode, verify_cb);
2879 return 0;
2880}
2881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002882/*[clinic input]
2883@classmethod
2884_ssl._SSLContext.__new__
2885 protocol as proto_version: int
2886 /
2887[clinic start generated code]*/
2888
Antoine Pitrou152efa22010-05-16 18:19:27 +00002889static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002890_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2891/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002892{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002893 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002894 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002895 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002896 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002897 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002898#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002899 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002900#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002901
Antoine Pitrou152efa22010-05-16 18:19:27 +00002902 PySSL_BEGIN_ALLOW_THREADS
2903 if (proto_version == PY_SSL_VERSION_TLS1)
2904 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002905#if HAVE_TLSv1_2
2906 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2907 ctx = SSL_CTX_new(TLSv1_1_method());
2908 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2909 ctx = SSL_CTX_new(TLSv1_2_method());
2910#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002911#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002912 else if (proto_version == PY_SSL_VERSION_SSL3)
2913 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002914#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002915#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002916 else if (proto_version == PY_SSL_VERSION_SSL2)
2917 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002918#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002919 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002920 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002921 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2922 ctx = SSL_CTX_new(TLS_client_method());
2923 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2924 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002925 else
2926 proto_version = -1;
2927 PySSL_END_ALLOW_THREADS
2928
2929 if (proto_version == -1) {
2930 PyErr_SetString(PyExc_ValueError,
2931 "invalid protocol version");
2932 return NULL;
2933 }
2934 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002935 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002936 return NULL;
2937 }
2938
2939 assert(type != NULL && type->tp_alloc != NULL);
2940 self = (PySSLContext *) type->tp_alloc(type, 0);
2941 if (self == NULL) {
2942 SSL_CTX_free(ctx);
2943 return NULL;
2944 }
2945 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002946 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002947 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002948#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002949 self->npn_protocols = NULL;
2950#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002951#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002952 self->alpn_protocols = NULL;
2953#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002954#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002955 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002956#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002957 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002958 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2959 self->check_hostname = 1;
2960 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2961 Py_DECREF(self);
2962 return NULL;
2963 }
2964 } else {
2965 self->check_hostname = 0;
2966 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2967 Py_DECREF(self);
2968 return NULL;
2969 }
2970 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002971 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002972 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2973 if (proto_version != PY_SSL_VERSION_SSL2)
2974 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002975 if (proto_version != PY_SSL_VERSION_SSL3)
2976 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002977 /* Minimal security flags for server and client side context.
2978 * Client sockets ignore server-side parameters. */
2979#ifdef SSL_OP_NO_COMPRESSION
2980 options |= SSL_OP_NO_COMPRESSION;
2981#endif
2982#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2983 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2984#endif
2985#ifdef SSL_OP_SINGLE_DH_USE
2986 options |= SSL_OP_SINGLE_DH_USE;
2987#endif
2988#ifdef SSL_OP_SINGLE_ECDH_USE
2989 options |= SSL_OP_SINGLE_ECDH_USE;
2990#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002991 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002992
Semen Zhydenko1295e112017-10-15 21:28:31 +02002993 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002994 * It's far from perfect but gives users a better head start. */
2995 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002996#if PY_SSL_DEFAULT_CIPHERS == 2
2997 /* stick to OpenSSL's default settings */
2998 result = 1;
2999#else
3000 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3001#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003002 } else {
3003 /* SSLv2 needs MD5 */
3004 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3005 }
3006 if (result == 0) {
3007 Py_DECREF(self);
3008 ERR_clear_error();
3009 PyErr_SetString(PySSLErrorObject,
3010 "No cipher can be selected.");
3011 return NULL;
3012 }
3013
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003014#if defined(SSL_MODE_RELEASE_BUFFERS)
3015 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3016 usage for no cost at all. However, don't do this for OpenSSL versions
3017 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3018 2014-0198. I can't find exactly which beta fixed this CVE, so be
3019 conservative and assume it wasn't fixed until release. We do this check
3020 at runtime to avoid problems from the dynamic linker.
3021 See #25672 for more on this. */
3022 libver = SSLeay();
3023 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3024 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3025 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3026 }
3027#endif
3028
3029
Donald Stufft8ae264c2017-03-02 11:45:29 -05003030#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003031 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3032 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003033 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3034 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003035#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003036 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3037#else
3038 {
3039 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3040 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3041 EC_KEY_free(key);
3042 }
3043#endif
3044#endif
3045
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003046#define SID_CTX "Python"
3047 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3048 sizeof(SID_CTX));
3049#undef SID_CTX
3050
Christian Heimes61d478c2018-01-27 15:51:38 +01003051 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003052#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003053 /* Improve trust chain building when cross-signed intermediate
3054 certificates are present. See https://bugs.python.org/issue23476. */
3055 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003056#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003057 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003058
Antoine Pitrou152efa22010-05-16 18:19:27 +00003059 return (PyObject *)self;
3060}
3061
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003062static int
3063context_traverse(PySSLContext *self, visitproc visit, void *arg)
3064{
3065#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003066 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003067#endif
3068 return 0;
3069}
3070
3071static int
3072context_clear(PySSLContext *self)
3073{
3074#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003075 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003076#endif
3077 return 0;
3078}
3079
Antoine Pitrou152efa22010-05-16 18:19:27 +00003080static void
3081context_dealloc(PySSLContext *self)
3082{
INADA Naokia6296d32017-08-24 14:55:17 +09003083 /* bpo-31095: UnTrack is needed before calling any callbacks */
3084 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003085 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003086 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003087#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003088 PyMem_FREE(self->npn_protocols);
3089#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003090#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003091 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003092#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003093 Py_TYPE(self)->tp_free(self);
3094}
3095
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003096/*[clinic input]
3097_ssl._SSLContext.set_ciphers
3098 cipherlist: str
3099 /
3100[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003101
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003102static PyObject *
3103_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3104/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3105{
3106 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003107 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003108 /* Clearing the error queue is necessary on some OpenSSL versions,
3109 otherwise the error will be reported again when another SSL call
3110 is done. */
3111 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003112 PyErr_SetString(PySSLErrorObject,
3113 "No cipher can be selected.");
3114 return NULL;
3115 }
3116 Py_RETURN_NONE;
3117}
3118
Christian Heimes25bfcd52016-09-06 00:04:45 +02003119#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3120/*[clinic input]
3121_ssl._SSLContext.get_ciphers
3122[clinic start generated code]*/
3123
3124static PyObject *
3125_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3126/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3127{
3128 SSL *ssl = NULL;
3129 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003130 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003131 int i=0;
3132 PyObject *result = NULL, *dct;
3133
3134 ssl = SSL_new(self->ctx);
3135 if (ssl == NULL) {
3136 _setSSLError(NULL, 0, __FILE__, __LINE__);
3137 goto exit;
3138 }
3139 sk = SSL_get_ciphers(ssl);
3140
3141 result = PyList_New(sk_SSL_CIPHER_num(sk));
3142 if (result == NULL) {
3143 goto exit;
3144 }
3145
3146 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3147 cipher = sk_SSL_CIPHER_value(sk, i);
3148 dct = cipher_to_dict(cipher);
3149 if (dct == NULL) {
3150 Py_CLEAR(result);
3151 goto exit;
3152 }
3153 PyList_SET_ITEM(result, i, dct);
3154 }
3155
3156 exit:
3157 if (ssl != NULL)
3158 SSL_free(ssl);
3159 return result;
3160
3161}
3162#endif
3163
3164
Christian Heimes29eab552018-02-25 12:31:33 +01003165#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003166static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003167do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3168 const unsigned char *server_protocols, unsigned int server_protocols_len,
3169 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003170{
Benjamin Peterson88615022015-01-23 17:30:26 -05003171 int ret;
3172 if (client_protocols == NULL) {
3173 client_protocols = (unsigned char *)"";
3174 client_protocols_len = 0;
3175 }
3176 if (server_protocols == NULL) {
3177 server_protocols = (unsigned char *)"";
3178 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003179 }
3180
Benjamin Peterson88615022015-01-23 17:30:26 -05003181 ret = SSL_select_next_proto(out, outlen,
3182 server_protocols, server_protocols_len,
3183 client_protocols, client_protocols_len);
3184 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3185 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003186
3187 return SSL_TLSEXT_ERR_OK;
3188}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003189#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003190
Christian Heimes29eab552018-02-25 12:31:33 +01003191#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003192/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3193static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003194_advertiseNPN_cb(SSL *s,
3195 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003196 void *args)
3197{
3198 PySSLContext *ssl_ctx = (PySSLContext *) args;
3199
3200 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003201 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003202 *len = 0;
3203 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003204 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003205 *len = ssl_ctx->npn_protocols_len;
3206 }
3207
3208 return SSL_TLSEXT_ERR_OK;
3209}
3210/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3211static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003212_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003213 unsigned char **out, unsigned char *outlen,
3214 const unsigned char *server, unsigned int server_len,
3215 void *args)
3216{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003217 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003218 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003219 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003220}
3221#endif
3222
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003223/*[clinic input]
3224_ssl._SSLContext._set_npn_protocols
3225 protos: Py_buffer
3226 /
3227[clinic start generated code]*/
3228
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003229static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003230_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3231 Py_buffer *protos)
3232/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003233{
Christian Heimes29eab552018-02-25 12:31:33 +01003234#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003235 PyMem_Free(self->npn_protocols);
3236 self->npn_protocols = PyMem_Malloc(protos->len);
3237 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003238 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003239 memcpy(self->npn_protocols, protos->buf, protos->len);
3240 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003241
3242 /* set both server and client callbacks, because the context can
3243 * be used to create both types of sockets */
3244 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3245 _advertiseNPN_cb,
3246 self);
3247 SSL_CTX_set_next_proto_select_cb(self->ctx,
3248 _selectNPN_cb,
3249 self);
3250
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003251 Py_RETURN_NONE;
3252#else
3253 PyErr_SetString(PyExc_NotImplementedError,
3254 "The NPN extension requires OpenSSL 1.0.1 or later.");
3255 return NULL;
3256#endif
3257}
3258
Christian Heimes29eab552018-02-25 12:31:33 +01003259#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003260static int
3261_selectALPN_cb(SSL *s,
3262 const unsigned char **out, unsigned char *outlen,
3263 const unsigned char *client_protocols, unsigned int client_protocols_len,
3264 void *args)
3265{
3266 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003267 return do_protocol_selection(1, (unsigned char **)out, outlen,
3268 ctx->alpn_protocols, ctx->alpn_protocols_len,
3269 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003270}
3271#endif
3272
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003273/*[clinic input]
3274_ssl._SSLContext._set_alpn_protocols
3275 protos: Py_buffer
3276 /
3277[clinic start generated code]*/
3278
Benjamin Petersoncca27322015-01-23 16:35:37 -05003279static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003280_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3281 Py_buffer *protos)
3282/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003283{
Christian Heimes29eab552018-02-25 12:31:33 +01003284#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003285 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003286 PyErr_Format(PyExc_OverflowError,
3287 "protocols longer than %d bytes", UINT_MAX);
3288 return NULL;
3289 }
3290
Benjamin Petersoncca27322015-01-23 16:35:37 -05003291 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003292 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003293 if (!self->alpn_protocols)
3294 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003295 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003296 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003297
3298 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3299 return PyErr_NoMemory();
3300 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3301
Benjamin Petersoncca27322015-01-23 16:35:37 -05003302 Py_RETURN_NONE;
3303#else
3304 PyErr_SetString(PyExc_NotImplementedError,
3305 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3306 return NULL;
3307#endif
3308}
3309
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310static PyObject *
3311get_verify_mode(PySSLContext *self, void *c)
3312{
3313 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3314 case SSL_VERIFY_NONE:
3315 return PyLong_FromLong(PY_SSL_CERT_NONE);
3316 case SSL_VERIFY_PEER:
3317 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3318 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3319 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3320 }
3321 PyErr_SetString(PySSLErrorObject,
3322 "invalid return value from SSL_CTX_get_verify_mode");
3323 return NULL;
3324}
3325
3326static int
3327set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3328{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003329 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003330 if (!PyArg_Parse(arg, "i", &n))
3331 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003332 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003333 PyErr_SetString(PyExc_ValueError,
3334 "Cannot set verify_mode to CERT_NONE when "
3335 "check_hostname is enabled.");
3336 return -1;
3337 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003338 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003339}
3340
3341static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003342get_verify_flags(PySSLContext *self, void *c)
3343{
Christian Heimes598894f2016-09-05 23:19:05 +02003344 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003345 unsigned long flags;
3346
Christian Heimes61d478c2018-01-27 15:51:38 +01003347 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003348 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003349 return PyLong_FromUnsignedLong(flags);
3350}
3351
3352static int
3353set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3354{
Christian Heimes598894f2016-09-05 23:19:05 +02003355 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003356 unsigned long new_flags, flags, set, clear;
3357
3358 if (!PyArg_Parse(arg, "k", &new_flags))
3359 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003360 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003361 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003362 clear = flags & ~new_flags;
3363 set = ~flags & new_flags;
3364 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003365 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003366 _setSSLError(NULL, 0, __FILE__, __LINE__);
3367 return -1;
3368 }
3369 }
3370 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003371 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003372 _setSSLError(NULL, 0, __FILE__, __LINE__);
3373 return -1;
3374 }
3375 }
3376 return 0;
3377}
3378
Christian Heimes698dde12018-02-27 11:54:43 +01003379/* Getter and setter for protocol version */
3380#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3381
3382
3383static int
3384set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3385{
3386 long v;
3387 int result;
3388
3389 if (!PyArg_Parse(arg, "l", &v))
3390 return -1;
3391 if (v > INT_MAX) {
3392 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3393 return -1;
3394 }
3395
3396 switch(self->protocol) {
3397 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3398 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3399 case PY_SSL_VERSION_TLS:
3400 break;
3401 default:
3402 PyErr_SetString(
3403 PyExc_ValueError,
3404 "The context's protocol doesn't support modification of "
3405 "highest and lowest version."
3406 );
3407 return -1;
3408 }
3409
3410 if (what == 0) {
3411 switch(v) {
3412 case PY_PROTO_MINIMUM_SUPPORTED:
3413 v = 0;
3414 break;
3415 case PY_PROTO_MAXIMUM_SUPPORTED:
3416 /* Emulate max for set_min_proto_version */
3417 v = PY_PROTO_MAXIMUM_AVAILABLE;
3418 break;
3419 default:
3420 break;
3421 }
3422 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3423 }
3424 else {
3425 switch(v) {
3426 case PY_PROTO_MAXIMUM_SUPPORTED:
3427 v = 0;
3428 break;
3429 case PY_PROTO_MINIMUM_SUPPORTED:
3430 /* Emulate max for set_min_proto_version */
3431 v = PY_PROTO_MINIMUM_AVAILABLE;
3432 break;
3433 default:
3434 break;
3435 }
3436 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3437 }
3438 if (result == 0) {
3439 PyErr_Format(PyExc_ValueError,
3440 "Unsupported protocol version 0x%x", v);
3441 return -1;
3442 }
3443 return 0;
3444}
3445
3446static PyObject *
3447get_minimum_version(PySSLContext *self, void *c)
3448{
3449 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3450 if (v == 0) {
3451 v = PY_PROTO_MINIMUM_SUPPORTED;
3452 }
3453 return PyLong_FromLong(v);
3454}
3455
3456static int
3457set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3458{
3459 return set_min_max_proto_version(self, arg, 0);
3460}
3461
3462static PyObject *
3463get_maximum_version(PySSLContext *self, void *c)
3464{
3465 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3466 if (v == 0) {
3467 v = PY_PROTO_MAXIMUM_SUPPORTED;
3468 }
3469 return PyLong_FromLong(v);
3470}
3471
3472static int
3473set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3474{
3475 return set_min_max_proto_version(self, arg, 1);
3476}
3477#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3478
Christian Heimes22587792013-11-21 23:56:13 +01003479static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003480get_options(PySSLContext *self, void *c)
3481{
3482 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3483}
3484
3485static int
3486set_options(PySSLContext *self, PyObject *arg, void *c)
3487{
3488 long new_opts, opts, set, clear;
3489 if (!PyArg_Parse(arg, "l", &new_opts))
3490 return -1;
3491 opts = SSL_CTX_get_options(self->ctx);
3492 clear = opts & ~new_opts;
3493 set = ~opts & new_opts;
3494 if (clear) {
3495#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3496 SSL_CTX_clear_options(self->ctx, clear);
3497#else
3498 PyErr_SetString(PyExc_ValueError,
3499 "can't clear options before OpenSSL 0.9.8m");
3500 return -1;
3501#endif
3502 }
3503 if (set)
3504 SSL_CTX_set_options(self->ctx, set);
3505 return 0;
3506}
3507
Christian Heimes1aa9a752013-12-02 02:41:19 +01003508static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003509get_host_flags(PySSLContext *self, void *c)
3510{
3511 return PyLong_FromUnsignedLong(self->hostflags);
3512}
3513
3514static int
3515set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3516{
3517 X509_VERIFY_PARAM *param;
3518 unsigned int new_flags = 0;
3519
3520 if (!PyArg_Parse(arg, "I", &new_flags))
3521 return -1;
3522
3523 param = SSL_CTX_get0_param(self->ctx);
3524 self->hostflags = new_flags;
3525 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3526 return 0;
3527}
3528
3529static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003530get_check_hostname(PySSLContext *self, void *c)
3531{
3532 return PyBool_FromLong(self->check_hostname);
3533}
3534
3535static int
3536set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3537{
3538 int check_hostname;
3539 if (!PyArg_Parse(arg, "p", &check_hostname))
3540 return -1;
3541 if (check_hostname &&
3542 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003543 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3544 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3545 return -1;
3546 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003547 }
3548 self->check_hostname = check_hostname;
3549 return 0;
3550}
3551
Christian Heimes11a14932018-02-24 02:35:08 +01003552static PyObject *
3553get_protocol(PySSLContext *self, void *c) {
3554 return PyLong_FromLong(self->protocol);
3555}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003556
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003557typedef struct {
3558 PyThreadState *thread_state;
3559 PyObject *callable;
3560 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003561 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003562 int error;
3563} _PySSLPasswordInfo;
3564
3565static int
3566_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3567 const char *bad_type_error)
3568{
3569 /* Set the password and size fields of a _PySSLPasswordInfo struct
3570 from a unicode, bytes, or byte array object.
3571 The password field will be dynamically allocated and must be freed
3572 by the caller */
3573 PyObject *password_bytes = NULL;
3574 const char *data = NULL;
3575 Py_ssize_t size;
3576
3577 if (PyUnicode_Check(password)) {
3578 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3579 if (!password_bytes) {
3580 goto error;
3581 }
3582 data = PyBytes_AS_STRING(password_bytes);
3583 size = PyBytes_GET_SIZE(password_bytes);
3584 } else if (PyBytes_Check(password)) {
3585 data = PyBytes_AS_STRING(password);
3586 size = PyBytes_GET_SIZE(password);
3587 } else if (PyByteArray_Check(password)) {
3588 data = PyByteArray_AS_STRING(password);
3589 size = PyByteArray_GET_SIZE(password);
3590 } else {
3591 PyErr_SetString(PyExc_TypeError, bad_type_error);
3592 goto error;
3593 }
3594
Victor Stinner9ee02032013-06-23 15:08:23 +02003595 if (size > (Py_ssize_t)INT_MAX) {
3596 PyErr_Format(PyExc_ValueError,
3597 "password cannot be longer than %d bytes", INT_MAX);
3598 goto error;
3599 }
3600
Victor Stinner11ebff22013-07-07 17:07:52 +02003601 PyMem_Free(pw_info->password);
3602 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003603 if (!pw_info->password) {
3604 PyErr_SetString(PyExc_MemoryError,
3605 "unable to allocate password buffer");
3606 goto error;
3607 }
3608 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003609 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003610
3611 Py_XDECREF(password_bytes);
3612 return 1;
3613
3614error:
3615 Py_XDECREF(password_bytes);
3616 return 0;
3617}
3618
3619static int
3620_password_callback(char *buf, int size, int rwflag, void *userdata)
3621{
3622 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3623 PyObject *fn_ret = NULL;
3624
3625 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3626
3627 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003628 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003629 if (!fn_ret) {
3630 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3631 core python API, so we could use it to add a frame here */
3632 goto error;
3633 }
3634
3635 if (!_pwinfo_set(pw_info, fn_ret,
3636 "password callback must return a string")) {
3637 goto error;
3638 }
3639 Py_CLEAR(fn_ret);
3640 }
3641
3642 if (pw_info->size > size) {
3643 PyErr_Format(PyExc_ValueError,
3644 "password cannot be longer than %d bytes", size);
3645 goto error;
3646 }
3647
3648 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3649 memcpy(buf, pw_info->password, pw_info->size);
3650 return pw_info->size;
3651
3652error:
3653 Py_XDECREF(fn_ret);
3654 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3655 pw_info->error = 1;
3656 return -1;
3657}
3658
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003659/*[clinic input]
3660_ssl._SSLContext.load_cert_chain
3661 certfile: object
3662 keyfile: object = NULL
3663 password: object = NULL
3664
3665[clinic start generated code]*/
3666
Antoine Pitroub5218772010-05-21 09:56:06 +00003667static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003668_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3669 PyObject *keyfile, PyObject *password)
3670/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003671{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003672 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003673 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3674 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003675 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003676 int r;
3677
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003678 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003679 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003680 if (keyfile == Py_None)
3681 keyfile = NULL;
3682 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3683 PyErr_SetString(PyExc_TypeError,
3684 "certfile should be a valid filesystem path");
3685 return NULL;
3686 }
3687 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3688 PyErr_SetString(PyExc_TypeError,
3689 "keyfile should be a valid filesystem path");
3690 goto error;
3691 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003692 if (password && password != Py_None) {
3693 if (PyCallable_Check(password)) {
3694 pw_info.callable = password;
3695 } else if (!_pwinfo_set(&pw_info, password,
3696 "password should be a string or callable")) {
3697 goto error;
3698 }
3699 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3700 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3701 }
3702 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003703 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3704 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003705 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003706 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003707 if (pw_info.error) {
3708 ERR_clear_error();
3709 /* the password callback has already set the error information */
3710 }
3711 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003712 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003713 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003714 }
3715 else {
3716 _setSSLError(NULL, 0, __FILE__, __LINE__);
3717 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003718 goto error;
3719 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003720 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003721 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003722 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3723 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003724 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3725 Py_CLEAR(keyfile_bytes);
3726 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003727 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003728 if (pw_info.error) {
3729 ERR_clear_error();
3730 /* the password callback has already set the error information */
3731 }
3732 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003733 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003734 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003735 }
3736 else {
3737 _setSSLError(NULL, 0, __FILE__, __LINE__);
3738 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003739 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003740 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003741 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003742 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003743 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003744 if (r != 1) {
3745 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003746 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003747 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003748 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3749 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003750 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003751 Py_RETURN_NONE;
3752
3753error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003754 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3755 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003756 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003757 Py_XDECREF(keyfile_bytes);
3758 Py_XDECREF(certfile_bytes);
3759 return NULL;
3760}
3761
Christian Heimesefff7062013-11-21 03:35:02 +01003762/* internal helper function, returns -1 on error
3763 */
3764static int
3765_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3766 int filetype)
3767{
3768 BIO *biobuf = NULL;
3769 X509_STORE *store;
3770 int retval = 0, err, loaded = 0;
3771
3772 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3773
3774 if (len <= 0) {
3775 PyErr_SetString(PyExc_ValueError,
3776 "Empty certificate data");
3777 return -1;
3778 } else if (len > INT_MAX) {
3779 PyErr_SetString(PyExc_OverflowError,
3780 "Certificate data is too long.");
3781 return -1;
3782 }
3783
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003784 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003785 if (biobuf == NULL) {
3786 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3787 return -1;
3788 }
3789
3790 store = SSL_CTX_get_cert_store(self->ctx);
3791 assert(store != NULL);
3792
3793 while (1) {
3794 X509 *cert = NULL;
3795 int r;
3796
3797 if (filetype == SSL_FILETYPE_ASN1) {
3798 cert = d2i_X509_bio(biobuf, NULL);
3799 } else {
3800 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003801 SSL_CTX_get_default_passwd_cb(self->ctx),
3802 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3803 );
Christian Heimesefff7062013-11-21 03:35:02 +01003804 }
3805 if (cert == NULL) {
3806 break;
3807 }
3808 r = X509_STORE_add_cert(store, cert);
3809 X509_free(cert);
3810 if (!r) {
3811 err = ERR_peek_last_error();
3812 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3813 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3814 /* cert already in hash table, not an error */
3815 ERR_clear_error();
3816 } else {
3817 break;
3818 }
3819 }
3820 loaded++;
3821 }
3822
3823 err = ERR_peek_last_error();
3824 if ((filetype == SSL_FILETYPE_ASN1) &&
3825 (loaded > 0) &&
3826 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3827 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3828 /* EOF ASN1 file, not an error */
3829 ERR_clear_error();
3830 retval = 0;
3831 } else if ((filetype == SSL_FILETYPE_PEM) &&
3832 (loaded > 0) &&
3833 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3834 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3835 /* EOF PEM file, not an error */
3836 ERR_clear_error();
3837 retval = 0;
3838 } else {
3839 _setSSLError(NULL, 0, __FILE__, __LINE__);
3840 retval = -1;
3841 }
3842
3843 BIO_free(biobuf);
3844 return retval;
3845}
3846
3847
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003848/*[clinic input]
3849_ssl._SSLContext.load_verify_locations
3850 cafile: object = NULL
3851 capath: object = NULL
3852 cadata: object = NULL
3853
3854[clinic start generated code]*/
3855
Antoine Pitrou152efa22010-05-16 18:19:27 +00003856static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003857_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3858 PyObject *cafile,
3859 PyObject *capath,
3860 PyObject *cadata)
3861/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003862{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003863 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3864 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003865 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003866
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003867 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003868 if (cafile == Py_None)
3869 cafile = NULL;
3870 if (capath == Py_None)
3871 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003872 if (cadata == Py_None)
3873 cadata = NULL;
3874
3875 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003876 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003877 "cafile, capath and cadata cannot be all omitted");
3878 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003879 }
3880 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3881 PyErr_SetString(PyExc_TypeError,
3882 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003883 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003884 }
3885 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003886 PyErr_SetString(PyExc_TypeError,
3887 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003888 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003889 }
Christian Heimesefff7062013-11-21 03:35:02 +01003890
3891 /* validata cadata type and load cadata */
3892 if (cadata) {
3893 Py_buffer buf;
3894 PyObject *cadata_ascii = NULL;
3895
3896 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3897 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3898 PyBuffer_Release(&buf);
3899 PyErr_SetString(PyExc_TypeError,
3900 "cadata should be a contiguous buffer with "
3901 "a single dimension");
3902 goto error;
3903 }
3904 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3905 PyBuffer_Release(&buf);
3906 if (r == -1) {
3907 goto error;
3908 }
3909 } else {
3910 PyErr_Clear();
3911 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3912 if (cadata_ascii == NULL) {
3913 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003914 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003915 "bytes-like object");
3916 goto error;
3917 }
3918 r = _add_ca_certs(self,
3919 PyBytes_AS_STRING(cadata_ascii),
3920 PyBytes_GET_SIZE(cadata_ascii),
3921 SSL_FILETYPE_PEM);
3922 Py_DECREF(cadata_ascii);
3923 if (r == -1) {
3924 goto error;
3925 }
3926 }
3927 }
3928
3929 /* load cafile or capath */
3930 if (cafile || capath) {
3931 if (cafile)
3932 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3933 if (capath)
3934 capath_buf = PyBytes_AS_STRING(capath_bytes);
3935 PySSL_BEGIN_ALLOW_THREADS
3936 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3937 PySSL_END_ALLOW_THREADS
3938 if (r != 1) {
3939 ok = 0;
3940 if (errno != 0) {
3941 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003942 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003943 }
3944 else {
3945 _setSSLError(NULL, 0, __FILE__, __LINE__);
3946 }
3947 goto error;
3948 }
3949 }
3950 goto end;
3951
3952 error:
3953 ok = 0;
3954 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003955 Py_XDECREF(cafile_bytes);
3956 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003957 if (ok) {
3958 Py_RETURN_NONE;
3959 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003960 return NULL;
3961 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003962}
3963
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003964/*[clinic input]
3965_ssl._SSLContext.load_dh_params
3966 path as filepath: object
3967 /
3968
3969[clinic start generated code]*/
3970
Antoine Pitrou152efa22010-05-16 18:19:27 +00003971static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003972_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3973/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003974{
3975 FILE *f;
3976 DH *dh;
3977
Victor Stinnerdaf45552013-08-28 00:53:59 +02003978 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003979 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003980 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003981
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003982 errno = 0;
3983 PySSL_BEGIN_ALLOW_THREADS
3984 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003985 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003986 PySSL_END_ALLOW_THREADS
3987 if (dh == NULL) {
3988 if (errno != 0) {
3989 ERR_clear_error();
3990 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3991 }
3992 else {
3993 _setSSLError(NULL, 0, __FILE__, __LINE__);
3994 }
3995 return NULL;
3996 }
3997 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3998 _setSSLError(NULL, 0, __FILE__, __LINE__);
3999 DH_free(dh);
4000 Py_RETURN_NONE;
4001}
4002
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004003/*[clinic input]
4004_ssl._SSLContext._wrap_socket
4005 sock: object(subclass_of="PySocketModule.Sock_Type")
4006 server_side: int
4007 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004008 *
4009 owner: object = None
4010 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004011
4012[clinic start generated code]*/
4013
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004014static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004015_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004016 int server_side, PyObject *hostname_obj,
4017 PyObject *owner, PyObject *session)
4018/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004019{
Antoine Pitroud5323212010-10-22 18:19:07 +00004020 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004021 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004022
Antoine Pitroud5323212010-10-22 18:19:07 +00004023 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004024 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004025 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004026 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004027 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004028 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004029
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004030 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4031 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004032 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004033 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004034 if (hostname != NULL)
4035 PyMem_Free(hostname);
4036 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004037}
4038
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004039/*[clinic input]
4040_ssl._SSLContext._wrap_bio
4041 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4042 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4043 server_side: int
4044 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004045 *
4046 owner: object = None
4047 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004048
4049[clinic start generated code]*/
4050
Antoine Pitroub0182c82010-10-12 20:09:02 +00004051static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004052_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4053 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004054 PyObject *hostname_obj, PyObject *owner,
4055 PyObject *session)
4056/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004057{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004058 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004059 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004060
4061 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004062 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004063 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004064 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004065 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004066 }
4067
4068 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004069 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070 incoming, outgoing);
4071
4072 PyMem_Free(hostname);
4073 return res;
4074}
4075
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076/*[clinic input]
4077_ssl._SSLContext.session_stats
4078[clinic start generated code]*/
4079
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004080static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004081_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4082/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004083{
4084 int r;
4085 PyObject *value, *stats = PyDict_New();
4086 if (!stats)
4087 return NULL;
4088
4089#define ADD_STATS(SSL_NAME, KEY_NAME) \
4090 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4091 if (value == NULL) \
4092 goto error; \
4093 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4094 Py_DECREF(value); \
4095 if (r < 0) \
4096 goto error;
4097
4098 ADD_STATS(number, "number");
4099 ADD_STATS(connect, "connect");
4100 ADD_STATS(connect_good, "connect_good");
4101 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4102 ADD_STATS(accept, "accept");
4103 ADD_STATS(accept_good, "accept_good");
4104 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4105 ADD_STATS(accept, "accept");
4106 ADD_STATS(hits, "hits");
4107 ADD_STATS(misses, "misses");
4108 ADD_STATS(timeouts, "timeouts");
4109 ADD_STATS(cache_full, "cache_full");
4110
4111#undef ADD_STATS
4112
4113 return stats;
4114
4115error:
4116 Py_DECREF(stats);
4117 return NULL;
4118}
4119
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004120/*[clinic input]
4121_ssl._SSLContext.set_default_verify_paths
4122[clinic start generated code]*/
4123
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004124static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4126/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004127{
4128 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4129 _setSSLError(NULL, 0, __FILE__, __LINE__);
4130 return NULL;
4131 }
4132 Py_RETURN_NONE;
4133}
4134
Antoine Pitrou501da612011-12-21 09:27:41 +01004135#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004136/*[clinic input]
4137_ssl._SSLContext.set_ecdh_curve
4138 name: object
4139 /
4140
4141[clinic start generated code]*/
4142
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004143static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004144_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4145/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004146{
4147 PyObject *name_bytes;
4148 int nid;
4149 EC_KEY *key;
4150
4151 if (!PyUnicode_FSConverter(name, &name_bytes))
4152 return NULL;
4153 assert(PyBytes_Check(name_bytes));
4154 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4155 Py_DECREF(name_bytes);
4156 if (nid == 0) {
4157 PyErr_Format(PyExc_ValueError,
4158 "unknown elliptic curve name %R", name);
4159 return NULL;
4160 }
4161 key = EC_KEY_new_by_curve_name(nid);
4162 if (key == NULL) {
4163 _setSSLError(NULL, 0, __FILE__, __LINE__);
4164 return NULL;
4165 }
4166 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4167 EC_KEY_free(key);
4168 Py_RETURN_NONE;
4169}
Antoine Pitrou501da612011-12-21 09:27:41 +01004170#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004171
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004172#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004173static int
4174_servername_callback(SSL *s, int *al, void *args)
4175{
4176 int ret;
4177 PySSLContext *ssl_ctx = (PySSLContext *) args;
4178 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004179 PyObject *result;
4180 /* The high-level ssl.SSLSocket object */
4181 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004182 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004183 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004184
Christian Heimes11a14932018-02-24 02:35:08 +01004185 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004186 /* remove race condition in this the call back while if removing the
4187 * callback is in progress */
4188 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004189 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004190 }
4191
4192 ssl = SSL_get_app_data(s);
4193 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004194
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004195 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004196 * SSL connection and that has a .context attribute that can be changed to
4197 * identify the requested hostname. Since the official API is the Python
4198 * level API we want to pass the callback a Python level object rather than
4199 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4200 * SSLObject) that will be passed. Otherwise if there's a socket then that
4201 * will be passed. If both do not exist only then the C-level object is
4202 * passed. */
4203 if (ssl->owner)
4204 ssl_socket = PyWeakref_GetObject(ssl->owner);
4205 else if (ssl->Socket)
4206 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4207 else
4208 ssl_socket = (PyObject *) ssl;
4209
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004210 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004211 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004212 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004213
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004214 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004215 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004216 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004217 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004218 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004219 PyObject *servername_bytes;
4220 PyObject *servername_str;
4221
4222 servername_bytes = PyBytes_FromString(servername);
4223 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004224 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4225 goto error;
4226 }
Christian Heimes11a14932018-02-24 02:35:08 +01004227 /* server_hostname was encoded to an A-label by our caller; put it
4228 * back into a str object, but still as an A-label (bpo-28414)
4229 */
4230 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4231 Py_DECREF(servername_bytes);
4232 if (servername_str == NULL) {
4233 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004234 goto error;
4235 }
Christian Heimes11a14932018-02-24 02:35:08 +01004236 result = PyObject_CallFunctionObjArgs(
4237 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4238 ssl_ctx, NULL);
4239 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004240 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004241 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004242
4243 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004244 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004245 *al = SSL_AD_HANDSHAKE_FAILURE;
4246 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4247 }
4248 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004249 /* Result may be None, a SSLContext or an integer
4250 * None and SSLContext are OK, integer or other values are an error.
4251 */
4252 if (result == Py_None) {
4253 ret = SSL_TLSEXT_ERR_OK;
4254 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004255 *al = (int) PyLong_AsLong(result);
4256 if (PyErr_Occurred()) {
4257 PyErr_WriteUnraisable(result);
4258 *al = SSL_AD_INTERNAL_ERROR;
4259 }
4260 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4261 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004262 Py_DECREF(result);
4263 }
4264
4265 PyGILState_Release(gstate);
4266 return ret;
4267
4268error:
4269 Py_DECREF(ssl_socket);
4270 *al = SSL_AD_INTERNAL_ERROR;
4271 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4272 PyGILState_Release(gstate);
4273 return ret;
4274}
Antoine Pitroua5963382013-03-30 16:39:00 +01004275#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004276
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004277static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004278get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004279{
Christian Heimes11a14932018-02-24 02:35:08 +01004280 PyObject *cb = self->set_sni_cb;
4281 if (cb == NULL) {
4282 Py_RETURN_NONE;
4283 }
4284 Py_INCREF(cb);
4285 return cb;
4286}
4287
4288static int
4289set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4290{
4291 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4292 PyErr_SetString(PyExc_ValueError,
4293 "sni_callback cannot be set on TLS_CLIENT context");
4294 return -1;
4295 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004296#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004297 Py_CLEAR(self->set_sni_cb);
4298 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004299 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4300 }
4301 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004302 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004303 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4304 PyErr_SetString(PyExc_TypeError,
4305 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004306 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004307 }
Christian Heimes11a14932018-02-24 02:35:08 +01004308 Py_INCREF(arg);
4309 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004310 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4311 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4312 }
Christian Heimes11a14932018-02-24 02:35:08 +01004313 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004314#else
4315 PyErr_SetString(PyExc_NotImplementedError,
4316 "The TLS extension servername callback, "
4317 "SSL_CTX_set_tlsext_servername_callback, "
4318 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004319 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004320#endif
4321}
4322
Christian Heimes11a14932018-02-24 02:35:08 +01004323PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4324"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4325\n\
4326If the argument is None then the callback is disabled. The method is called\n\
4327with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4328See RFC 6066 for details of the SNI extension.");
4329
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004330/*[clinic input]
4331_ssl._SSLContext.cert_store_stats
4332
4333Returns quantities of loaded X.509 certificates.
4334
4335X.509 certificates with a CA extension and certificate revocation lists
4336inside the context's cert store.
4337
4338NOTE: Certificates in a capath directory aren't loaded unless they have
4339been used at least once.
4340[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004341
4342static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004343_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4344/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004345{
4346 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004347 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004348 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004349 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004350
4351 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004352 objs = X509_STORE_get0_objects(store);
4353 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4354 obj = sk_X509_OBJECT_value(objs, i);
4355 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004356 case X509_LU_X509:
4357 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004358 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004359 ca++;
4360 }
4361 break;
4362 case X509_LU_CRL:
4363 crl++;
4364 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004365 default:
4366 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4367 * As far as I can tell they are internal states and never
4368 * stored in a cert store */
4369 break;
4370 }
4371 }
4372 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4373 "x509_ca", ca);
4374}
4375
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004376/*[clinic input]
4377_ssl._SSLContext.get_ca_certs
4378 binary_form: bool = False
4379
4380Returns a list of dicts with information of loaded CA certs.
4381
4382If the optional argument is True, returns a DER-encoded copy of the CA
4383certificate.
4384
4385NOTE: Certificates in a capath directory aren't loaded unless they have
4386been used at least once.
4387[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004388
4389static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004390_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4391/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004392{
4393 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004394 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004395 PyObject *ci = NULL, *rlist = NULL;
4396 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004397
4398 if ((rlist = PyList_New(0)) == NULL) {
4399 return NULL;
4400 }
4401
4402 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004403 objs = X509_STORE_get0_objects(store);
4404 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004405 X509_OBJECT *obj;
4406 X509 *cert;
4407
Christian Heimes598894f2016-09-05 23:19:05 +02004408 obj = sk_X509_OBJECT_value(objs, i);
4409 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004410 /* not a x509 cert */
4411 continue;
4412 }
4413 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004414 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004415 if (!X509_check_ca(cert)) {
4416 continue;
4417 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004418 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004419 ci = _certificate_to_der(cert);
4420 } else {
4421 ci = _decode_certificate(cert);
4422 }
4423 if (ci == NULL) {
4424 goto error;
4425 }
4426 if (PyList_Append(rlist, ci) == -1) {
4427 goto error;
4428 }
4429 Py_CLEAR(ci);
4430 }
4431 return rlist;
4432
4433 error:
4434 Py_XDECREF(ci);
4435 Py_XDECREF(rlist);
4436 return NULL;
4437}
4438
4439
Antoine Pitrou152efa22010-05-16 18:19:27 +00004440static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004441 {"check_hostname", (getter) get_check_hostname,
4442 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004443 {"_host_flags", (getter) get_host_flags,
4444 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004445#if SSL_CTRL_GET_MAX_PROTO_VERSION
4446 {"minimum_version", (getter) get_minimum_version,
4447 (setter) set_minimum_version, NULL},
4448 {"maximum_version", (getter) get_maximum_version,
4449 (setter) set_maximum_version, NULL},
4450#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004451 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004452 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004453 {"options", (getter) get_options,
4454 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004455 {"protocol", (getter) get_protocol,
4456 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004457 {"verify_flags", (getter) get_verify_flags,
4458 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004459 {"verify_mode", (getter) get_verify_mode,
4460 (setter) set_verify_mode, NULL},
4461 {NULL}, /* sentinel */
4462};
4463
4464static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004465 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4466 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4467 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4468 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4469 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4470 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4471 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4472 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4473 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4474 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4475 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004476 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4477 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004478 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004479 {NULL, NULL} /* sentinel */
4480};
4481
4482static PyTypeObject PySSLContext_Type = {
4483 PyVarObject_HEAD_INIT(NULL, 0)
4484 "_ssl._SSLContext", /*tp_name*/
4485 sizeof(PySSLContext), /*tp_basicsize*/
4486 0, /*tp_itemsize*/
4487 (destructor)context_dealloc, /*tp_dealloc*/
4488 0, /*tp_print*/
4489 0, /*tp_getattr*/
4490 0, /*tp_setattr*/
4491 0, /*tp_reserved*/
4492 0, /*tp_repr*/
4493 0, /*tp_as_number*/
4494 0, /*tp_as_sequence*/
4495 0, /*tp_as_mapping*/
4496 0, /*tp_hash*/
4497 0, /*tp_call*/
4498 0, /*tp_str*/
4499 0, /*tp_getattro*/
4500 0, /*tp_setattro*/
4501 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004502 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004503 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004504 (traverseproc) context_traverse, /*tp_traverse*/
4505 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004506 0, /*tp_richcompare*/
4507 0, /*tp_weaklistoffset*/
4508 0, /*tp_iter*/
4509 0, /*tp_iternext*/
4510 context_methods, /*tp_methods*/
4511 0, /*tp_members*/
4512 context_getsetlist, /*tp_getset*/
4513 0, /*tp_base*/
4514 0, /*tp_dict*/
4515 0, /*tp_descr_get*/
4516 0, /*tp_descr_set*/
4517 0, /*tp_dictoffset*/
4518 0, /*tp_init*/
4519 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004520 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004521};
4522
4523
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004524/*
4525 * MemoryBIO objects
4526 */
4527
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004528/*[clinic input]
4529@classmethod
4530_ssl.MemoryBIO.__new__
4531
4532[clinic start generated code]*/
4533
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004534static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004535_ssl_MemoryBIO_impl(PyTypeObject *type)
4536/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004537{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004538 BIO *bio;
4539 PySSLMemoryBIO *self;
4540
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004541 bio = BIO_new(BIO_s_mem());
4542 if (bio == NULL) {
4543 PyErr_SetString(PySSLErrorObject,
4544 "failed to allocate BIO");
4545 return NULL;
4546 }
4547 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4548 * just that no data is currently available. The SSL routines should retry
4549 * the read, which we can achieve by calling BIO_set_retry_read(). */
4550 BIO_set_retry_read(bio);
4551 BIO_set_mem_eof_return(bio, -1);
4552
4553 assert(type != NULL && type->tp_alloc != NULL);
4554 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4555 if (self == NULL) {
4556 BIO_free(bio);
4557 return NULL;
4558 }
4559 self->bio = bio;
4560 self->eof_written = 0;
4561
4562 return (PyObject *) self;
4563}
4564
4565static void
4566memory_bio_dealloc(PySSLMemoryBIO *self)
4567{
4568 BIO_free(self->bio);
4569 Py_TYPE(self)->tp_free(self);
4570}
4571
4572static PyObject *
4573memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4574{
Segev Finer5cff6372017-07-27 01:19:17 +03004575 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004576}
4577
4578PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4579"The number of bytes pending in the memory BIO.");
4580
4581static PyObject *
4582memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4583{
4584 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4585 && self->eof_written);
4586}
4587
4588PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4589"Whether the memory BIO is at EOF.");
4590
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004591/*[clinic input]
4592_ssl.MemoryBIO.read
4593 size as len: int = -1
4594 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004595
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004596Read up to size bytes from the memory BIO.
4597
4598If size is not specified, read the entire buffer.
4599If the return value is an empty bytes instance, this means either
4600EOF or that no data is available. Use the "eof" property to
4601distinguish between the two.
4602[clinic start generated code]*/
4603
4604static PyObject *
4605_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4606/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4607{
4608 int avail, nbytes;
4609 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004610
Segev Finer5cff6372017-07-27 01:19:17 +03004611 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004612 if ((len < 0) || (len > avail))
4613 len = avail;
4614
4615 result = PyBytes_FromStringAndSize(NULL, len);
4616 if ((result == NULL) || (len == 0))
4617 return result;
4618
4619 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4620 /* There should never be any short reads but check anyway. */
4621 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4622 Py_DECREF(result);
4623 return NULL;
4624 }
4625
4626 return result;
4627}
4628
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004629/*[clinic input]
4630_ssl.MemoryBIO.write
4631 b: Py_buffer
4632 /
4633
4634Writes the bytes b into the memory BIO.
4635
4636Returns the number of bytes written.
4637[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004638
4639static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004640_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4641/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004642{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004643 int nbytes;
4644
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004645 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004646 PyErr_Format(PyExc_OverflowError,
4647 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004648 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004649 }
4650
4651 if (self->eof_written) {
4652 PyErr_SetString(PySSLErrorObject,
4653 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004654 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004655 }
4656
Segev Finer5cff6372017-07-27 01:19:17 +03004657 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004658 if (nbytes < 0) {
4659 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004660 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004661 }
4662
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004663 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004664}
4665
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004666/*[clinic input]
4667_ssl.MemoryBIO.write_eof
4668
4669Write an EOF marker to the memory BIO.
4670
4671When all data has been read, the "eof" property will be True.
4672[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004673
4674static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004675_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4676/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004677{
4678 self->eof_written = 1;
4679 /* After an EOF is written, a zero return from read() should be a real EOF
4680 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4681 BIO_clear_retry_flags(self->bio);
4682 BIO_set_mem_eof_return(self->bio, 0);
4683
4684 Py_RETURN_NONE;
4685}
4686
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004687static PyGetSetDef memory_bio_getsetlist[] = {
4688 {"pending", (getter) memory_bio_get_pending, NULL,
4689 PySSL_memory_bio_pending_doc},
4690 {"eof", (getter) memory_bio_get_eof, NULL,
4691 PySSL_memory_bio_eof_doc},
4692 {NULL}, /* sentinel */
4693};
4694
4695static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004696 _SSL_MEMORYBIO_READ_METHODDEF
4697 _SSL_MEMORYBIO_WRITE_METHODDEF
4698 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004699 {NULL, NULL} /* sentinel */
4700};
4701
4702static PyTypeObject PySSLMemoryBIO_Type = {
4703 PyVarObject_HEAD_INIT(NULL, 0)
4704 "_ssl.MemoryBIO", /*tp_name*/
4705 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4706 0, /*tp_itemsize*/
4707 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4708 0, /*tp_print*/
4709 0, /*tp_getattr*/
4710 0, /*tp_setattr*/
4711 0, /*tp_reserved*/
4712 0, /*tp_repr*/
4713 0, /*tp_as_number*/
4714 0, /*tp_as_sequence*/
4715 0, /*tp_as_mapping*/
4716 0, /*tp_hash*/
4717 0, /*tp_call*/
4718 0, /*tp_str*/
4719 0, /*tp_getattro*/
4720 0, /*tp_setattro*/
4721 0, /*tp_as_buffer*/
4722 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4723 0, /*tp_doc*/
4724 0, /*tp_traverse*/
4725 0, /*tp_clear*/
4726 0, /*tp_richcompare*/
4727 0, /*tp_weaklistoffset*/
4728 0, /*tp_iter*/
4729 0, /*tp_iternext*/
4730 memory_bio_methods, /*tp_methods*/
4731 0, /*tp_members*/
4732 memory_bio_getsetlist, /*tp_getset*/
4733 0, /*tp_base*/
4734 0, /*tp_dict*/
4735 0, /*tp_descr_get*/
4736 0, /*tp_descr_set*/
4737 0, /*tp_dictoffset*/
4738 0, /*tp_init*/
4739 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004740 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004741};
4742
Antoine Pitrou152efa22010-05-16 18:19:27 +00004743
Christian Heimes99a65702016-09-10 23:44:53 +02004744/*
4745 * SSL Session object
4746 */
4747
4748static void
4749PySSLSession_dealloc(PySSLSession *self)
4750{
INADA Naokia6296d32017-08-24 14:55:17 +09004751 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004752 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004753 Py_XDECREF(self->ctx);
4754 if (self->session != NULL) {
4755 SSL_SESSION_free(self->session);
4756 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004757 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004758}
4759
4760static PyObject *
4761PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4762{
4763 int result;
4764
4765 if (left == NULL || right == NULL) {
4766 PyErr_BadInternalCall();
4767 return NULL;
4768 }
4769
4770 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4771 Py_RETURN_NOTIMPLEMENTED;
4772 }
4773
4774 if (left == right) {
4775 result = 0;
4776 } else {
4777 const unsigned char *left_id, *right_id;
4778 unsigned int left_len, right_len;
4779 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4780 &left_len);
4781 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4782 &right_len);
4783 if (left_len == right_len) {
4784 result = memcmp(left_id, right_id, left_len);
4785 } else {
4786 result = 1;
4787 }
4788 }
4789
4790 switch (op) {
4791 case Py_EQ:
4792 if (result == 0) {
4793 Py_RETURN_TRUE;
4794 } else {
4795 Py_RETURN_FALSE;
4796 }
4797 break;
4798 case Py_NE:
4799 if (result != 0) {
4800 Py_RETURN_TRUE;
4801 } else {
4802 Py_RETURN_FALSE;
4803 }
4804 break;
4805 case Py_LT:
4806 case Py_LE:
4807 case Py_GT:
4808 case Py_GE:
4809 Py_RETURN_NOTIMPLEMENTED;
4810 break;
4811 default:
4812 PyErr_BadArgument();
4813 return NULL;
4814 }
4815}
4816
4817static int
4818PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4819{
4820 Py_VISIT(self->ctx);
4821 return 0;
4822}
4823
4824static int
4825PySSLSession_clear(PySSLSession *self)
4826{
4827 Py_CLEAR(self->ctx);
4828 return 0;
4829}
4830
4831
4832static PyObject *
4833PySSLSession_get_time(PySSLSession *self, void *closure) {
4834 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4835}
4836
4837PyDoc_STRVAR(PySSLSession_get_time_doc,
4838"Session creation time (seconds since epoch).");
4839
4840
4841static PyObject *
4842PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4843 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4844}
4845
4846PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4847"Session timeout (delta in seconds).");
4848
4849
4850static PyObject *
4851PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4852 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4853 return PyLong_FromUnsignedLong(hint);
4854}
4855
4856PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4857"Ticket life time hint.");
4858
4859
4860static PyObject *
4861PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4862 const unsigned char *id;
4863 unsigned int len;
4864 id = SSL_SESSION_get_id(self->session, &len);
4865 return PyBytes_FromStringAndSize((const char *)id, len);
4866}
4867
4868PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4869"Session id");
4870
4871
4872static PyObject *
4873PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4874 if (SSL_SESSION_has_ticket(self->session)) {
4875 Py_RETURN_TRUE;
4876 } else {
4877 Py_RETURN_FALSE;
4878 }
4879}
4880
4881PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4882"Does the session contain a ticket?");
4883
4884
4885static PyGetSetDef PySSLSession_getsetlist[] = {
4886 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4887 PySSLSession_get_has_ticket_doc},
4888 {"id", (getter) PySSLSession_get_session_id, NULL,
4889 PySSLSession_get_session_id_doc},
4890 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4891 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4892 {"time", (getter) PySSLSession_get_time, NULL,
4893 PySSLSession_get_time_doc},
4894 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4895 PySSLSession_get_timeout_doc},
4896 {NULL}, /* sentinel */
4897};
4898
4899static PyTypeObject PySSLSession_Type = {
4900 PyVarObject_HEAD_INIT(NULL, 0)
4901 "_ssl.Session", /*tp_name*/
4902 sizeof(PySSLSession), /*tp_basicsize*/
4903 0, /*tp_itemsize*/
4904 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4905 0, /*tp_print*/
4906 0, /*tp_getattr*/
4907 0, /*tp_setattr*/
4908 0, /*tp_reserved*/
4909 0, /*tp_repr*/
4910 0, /*tp_as_number*/
4911 0, /*tp_as_sequence*/
4912 0, /*tp_as_mapping*/
4913 0, /*tp_hash*/
4914 0, /*tp_call*/
4915 0, /*tp_str*/
4916 0, /*tp_getattro*/
4917 0, /*tp_setattro*/
4918 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004919 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004920 0, /*tp_doc*/
4921 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4922 (inquiry)PySSLSession_clear, /*tp_clear*/
4923 PySSLSession_richcompare, /*tp_richcompare*/
4924 0, /*tp_weaklistoffset*/
4925 0, /*tp_iter*/
4926 0, /*tp_iternext*/
4927 0, /*tp_methods*/
4928 0, /*tp_members*/
4929 PySSLSession_getsetlist, /*tp_getset*/
4930};
4931
4932
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004933/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004934/*[clinic input]
4935_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004936 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004937 entropy: double
4938 /
4939
4940Mix string into the OpenSSL PRNG state.
4941
4942entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304943string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004944[clinic start generated code]*/
4945
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004946static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004947_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004948/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004949{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004950 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004951 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004952
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004953 buf = (const char *)view->buf;
4954 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004955 do {
4956 written = Py_MIN(len, INT_MAX);
4957 RAND_add(buf, (int)written, entropy);
4958 buf += written;
4959 len -= written;
4960 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004961 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004962}
4963
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004964static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004965PySSL_RAND(int len, int pseudo)
4966{
4967 int ok;
4968 PyObject *bytes;
4969 unsigned long err;
4970 const char *errstr;
4971 PyObject *v;
4972
Victor Stinner1e81a392013-12-19 16:47:04 +01004973 if (len < 0) {
4974 PyErr_SetString(PyExc_ValueError, "num must be positive");
4975 return NULL;
4976 }
4977
Victor Stinner99c8b162011-05-24 12:05:19 +02004978 bytes = PyBytes_FromStringAndSize(NULL, len);
4979 if (bytes == NULL)
4980 return NULL;
4981 if (pseudo) {
4982 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4983 if (ok == 0 || ok == 1)
4984 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4985 }
4986 else {
4987 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4988 if (ok == 1)
4989 return bytes;
4990 }
4991 Py_DECREF(bytes);
4992
4993 err = ERR_get_error();
4994 errstr = ERR_reason_error_string(err);
4995 v = Py_BuildValue("(ks)", err, errstr);
4996 if (v != NULL) {
4997 PyErr_SetObject(PySSLErrorObject, v);
4998 Py_DECREF(v);
4999 }
5000 return NULL;
5001}
5002
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005003/*[clinic input]
5004_ssl.RAND_bytes
5005 n: int
5006 /
5007
5008Generate n cryptographically strong pseudo-random bytes.
5009[clinic start generated code]*/
5010
Victor Stinner99c8b162011-05-24 12:05:19 +02005011static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005012_ssl_RAND_bytes_impl(PyObject *module, int n)
5013/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005014{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005015 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005016}
5017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005018/*[clinic input]
5019_ssl.RAND_pseudo_bytes
5020 n: int
5021 /
5022
5023Generate n pseudo-random bytes.
5024
5025Return a pair (bytes, is_cryptographic). is_cryptographic is True
5026if the bytes generated are cryptographically strong.
5027[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005028
5029static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005030_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5031/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005032{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005033 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005034}
5035
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005036/*[clinic input]
5037_ssl.RAND_status
5038
5039Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5040
5041It is necessary to seed the PRNG with RAND_add() on some platforms before
5042using the ssl() function.
5043[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005044
5045static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005046_ssl_RAND_status_impl(PyObject *module)
5047/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005048{
Christian Heimes217cfd12007-12-02 14:31:20 +00005049 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005050}
5051
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005052#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005053/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005054/*[clinic input]
5055_ssl.RAND_egd
5056 path: object(converter="PyUnicode_FSConverter")
5057 /
5058
5059Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5060
5061Returns number of bytes read. Raises SSLError if connection to EGD
5062fails or if it does not provide enough data to seed PRNG.
5063[clinic start generated code]*/
5064
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005065static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005066_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5067/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005068{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005069 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005070 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005071 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005072 PyErr_SetString(PySSLErrorObject,
5073 "EGD connection failed or EGD did not return "
5074 "enough data to seed the PRNG");
5075 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005076 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005077 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005078}
Christian Heimesa5d07652016-09-24 10:48:05 +02005079/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005080#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005081
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005082
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005083
5084/*[clinic input]
5085_ssl.get_default_verify_paths
5086
5087Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5088
5089The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5090[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005091
5092static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005093_ssl_get_default_verify_paths_impl(PyObject *module)
5094/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005095{
5096 PyObject *ofile_env = NULL;
5097 PyObject *ofile = NULL;
5098 PyObject *odir_env = NULL;
5099 PyObject *odir = NULL;
5100
Benjamin Petersond113c962015-07-18 10:59:13 -07005101#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005102 const char *tmp = (info); \
5103 target = NULL; \
5104 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5105 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5106 target = PyBytes_FromString(tmp); } \
5107 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005108 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005109
Benjamin Petersond113c962015-07-18 10:59:13 -07005110 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5111 CONVERT(X509_get_default_cert_file(), ofile);
5112 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5113 CONVERT(X509_get_default_cert_dir(), odir);
5114#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005115
Christian Heimes200bb1b2013-06-14 15:14:29 +02005116 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005117
5118 error:
5119 Py_XDECREF(ofile_env);
5120 Py_XDECREF(ofile);
5121 Py_XDECREF(odir_env);
5122 Py_XDECREF(odir);
5123 return NULL;
5124}
5125
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005126static PyObject*
5127asn1obj2py(ASN1_OBJECT *obj)
5128{
5129 int nid;
5130 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005131
5132 nid = OBJ_obj2nid(obj);
5133 if (nid == NID_undef) {
5134 PyErr_Format(PyExc_ValueError, "Unknown object");
5135 return NULL;
5136 }
5137 sn = OBJ_nid2sn(nid);
5138 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005139 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005140}
5141
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005142/*[clinic input]
5143_ssl.txt2obj
5144 txt: str
5145 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005146
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005147Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5148
5149By default objects are looked up by OID. With name=True short and
5150long name are also matched.
5151[clinic start generated code]*/
5152
5153static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005154_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5155/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005156{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005157 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005158 ASN1_OBJECT *obj;
5159
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005160 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5161 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005162 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005163 return NULL;
5164 }
5165 result = asn1obj2py(obj);
5166 ASN1_OBJECT_free(obj);
5167 return result;
5168}
5169
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005170/*[clinic input]
5171_ssl.nid2obj
5172 nid: int
5173 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005175Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5176[clinic start generated code]*/
5177
5178static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005179_ssl_nid2obj_impl(PyObject *module, int nid)
5180/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005181{
5182 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005183 ASN1_OBJECT *obj;
5184
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005185 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005186 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005187 return NULL;
5188 }
5189 obj = OBJ_nid2obj(nid);
5190 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005191 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005192 return NULL;
5193 }
5194 result = asn1obj2py(obj);
5195 ASN1_OBJECT_free(obj);
5196 return result;
5197}
5198
Christian Heimes46bebee2013-06-09 19:03:31 +02005199#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005200
5201static PyObject*
5202certEncodingType(DWORD encodingType)
5203{
5204 static PyObject *x509_asn = NULL;
5205 static PyObject *pkcs_7_asn = NULL;
5206
5207 if (x509_asn == NULL) {
5208 x509_asn = PyUnicode_InternFromString("x509_asn");
5209 if (x509_asn == NULL)
5210 return NULL;
5211 }
5212 if (pkcs_7_asn == NULL) {
5213 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5214 if (pkcs_7_asn == NULL)
5215 return NULL;
5216 }
5217 switch(encodingType) {
5218 case X509_ASN_ENCODING:
5219 Py_INCREF(x509_asn);
5220 return x509_asn;
5221 case PKCS_7_ASN_ENCODING:
5222 Py_INCREF(pkcs_7_asn);
5223 return pkcs_7_asn;
5224 default:
5225 return PyLong_FromLong(encodingType);
5226 }
5227}
5228
5229static PyObject*
5230parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5231{
5232 CERT_ENHKEY_USAGE *usage;
5233 DWORD size, error, i;
5234 PyObject *retval;
5235
5236 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5237 error = GetLastError();
5238 if (error == CRYPT_E_NOT_FOUND) {
5239 Py_RETURN_TRUE;
5240 }
5241 return PyErr_SetFromWindowsErr(error);
5242 }
5243
5244 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5245 if (usage == NULL) {
5246 return PyErr_NoMemory();
5247 }
5248
5249 /* Now get the actual enhanced usage property */
5250 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5251 PyMem_Free(usage);
5252 error = GetLastError();
5253 if (error == CRYPT_E_NOT_FOUND) {
5254 Py_RETURN_TRUE;
5255 }
5256 return PyErr_SetFromWindowsErr(error);
5257 }
5258 retval = PySet_New(NULL);
5259 if (retval == NULL) {
5260 goto error;
5261 }
5262 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5263 if (usage->rgpszUsageIdentifier[i]) {
5264 PyObject *oid;
5265 int err;
5266 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5267 if (oid == NULL) {
5268 Py_CLEAR(retval);
5269 goto error;
5270 }
5271 err = PySet_Add(retval, oid);
5272 Py_DECREF(oid);
5273 if (err == -1) {
5274 Py_CLEAR(retval);
5275 goto error;
5276 }
5277 }
5278 }
5279 error:
5280 PyMem_Free(usage);
5281 return retval;
5282}
5283
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005284/*[clinic input]
5285_ssl.enum_certificates
5286 store_name: str
5287
5288Retrieve certificates from Windows' cert store.
5289
5290store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5291more cert storages, too. The function returns a list of (bytes,
5292encoding_type, trust) tuples. The encoding_type flag can be interpreted
5293with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5294a set of OIDs or the boolean True.
5295[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005296
Christian Heimes46bebee2013-06-09 19:03:31 +02005297static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005298_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5299/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005300{
Christian Heimes46bebee2013-06-09 19:03:31 +02005301 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005302 PCCERT_CONTEXT pCertCtx = NULL;
5303 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005304 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005305
Christian Heimes44109d72013-11-22 01:51:30 +01005306 result = PyList_New(0);
5307 if (result == NULL) {
5308 return NULL;
5309 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005310 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5311 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5312 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005313 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005314 Py_DECREF(result);
5315 return PyErr_SetFromWindowsErr(GetLastError());
5316 }
5317
Christian Heimes44109d72013-11-22 01:51:30 +01005318 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5319 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5320 pCertCtx->cbCertEncoded);
5321 if (!cert) {
5322 Py_CLEAR(result);
5323 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005324 }
Christian Heimes44109d72013-11-22 01:51:30 +01005325 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5326 Py_CLEAR(result);
5327 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005328 }
Christian Heimes44109d72013-11-22 01:51:30 +01005329 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5330 if (keyusage == Py_True) {
5331 Py_DECREF(keyusage);
5332 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005333 }
Christian Heimes44109d72013-11-22 01:51:30 +01005334 if (keyusage == NULL) {
5335 Py_CLEAR(result);
5336 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005337 }
Christian Heimes44109d72013-11-22 01:51:30 +01005338 if ((tup = PyTuple_New(3)) == NULL) {
5339 Py_CLEAR(result);
5340 break;
5341 }
5342 PyTuple_SET_ITEM(tup, 0, cert);
5343 cert = NULL;
5344 PyTuple_SET_ITEM(tup, 1, enc);
5345 enc = NULL;
5346 PyTuple_SET_ITEM(tup, 2, keyusage);
5347 keyusage = NULL;
5348 if (PyList_Append(result, tup) < 0) {
5349 Py_CLEAR(result);
5350 break;
5351 }
5352 Py_CLEAR(tup);
5353 }
5354 if (pCertCtx) {
5355 /* loop ended with an error, need to clean up context manually */
5356 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005357 }
5358
5359 /* In error cases cert, enc and tup may not be NULL */
5360 Py_XDECREF(cert);
5361 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005362 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005363 Py_XDECREF(tup);
5364
5365 if (!CertCloseStore(hStore, 0)) {
5366 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005367 Py_XDECREF(result);
5368 return PyErr_SetFromWindowsErr(GetLastError());
5369 }
5370 return result;
5371}
5372
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005373/*[clinic input]
5374_ssl.enum_crls
5375 store_name: str
5376
5377Retrieve CRLs from Windows' cert store.
5378
5379store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5380more cert storages, too. The function returns a list of (bytes,
5381encoding_type) tuples. The encoding_type flag can be interpreted with
5382X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5383[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005384
5385static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005386_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5387/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005388{
Christian Heimes44109d72013-11-22 01:51:30 +01005389 HCERTSTORE hStore = NULL;
5390 PCCRL_CONTEXT pCrlCtx = NULL;
5391 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5392 PyObject *result = NULL;
5393
Christian Heimes44109d72013-11-22 01:51:30 +01005394 result = PyList_New(0);
5395 if (result == NULL) {
5396 return NULL;
5397 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005398 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5399 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5400 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005401 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005402 Py_DECREF(result);
5403 return PyErr_SetFromWindowsErr(GetLastError());
5404 }
Christian Heimes44109d72013-11-22 01:51:30 +01005405
5406 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5407 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5408 pCrlCtx->cbCrlEncoded);
5409 if (!crl) {
5410 Py_CLEAR(result);
5411 break;
5412 }
5413 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5414 Py_CLEAR(result);
5415 break;
5416 }
5417 if ((tup = PyTuple_New(2)) == NULL) {
5418 Py_CLEAR(result);
5419 break;
5420 }
5421 PyTuple_SET_ITEM(tup, 0, crl);
5422 crl = NULL;
5423 PyTuple_SET_ITEM(tup, 1, enc);
5424 enc = NULL;
5425
5426 if (PyList_Append(result, tup) < 0) {
5427 Py_CLEAR(result);
5428 break;
5429 }
5430 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005431 }
Christian Heimes44109d72013-11-22 01:51:30 +01005432 if (pCrlCtx) {
5433 /* loop ended with an error, need to clean up context manually */
5434 CertFreeCRLContext(pCrlCtx);
5435 }
5436
5437 /* In error cases cert, enc and tup may not be NULL */
5438 Py_XDECREF(crl);
5439 Py_XDECREF(enc);
5440 Py_XDECREF(tup);
5441
5442 if (!CertCloseStore(hStore, 0)) {
5443 /* This error case might shadow another exception.*/
5444 Py_XDECREF(result);
5445 return PyErr_SetFromWindowsErr(GetLastError());
5446 }
5447 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005448}
Christian Heimes44109d72013-11-22 01:51:30 +01005449
5450#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005451
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005452/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005453static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005454 _SSL__TEST_DECODE_CERT_METHODDEF
5455 _SSL_RAND_ADD_METHODDEF
5456 _SSL_RAND_BYTES_METHODDEF
5457 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5458 _SSL_RAND_EGD_METHODDEF
5459 _SSL_RAND_STATUS_METHODDEF
5460 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5461 _SSL_ENUM_CERTIFICATES_METHODDEF
5462 _SSL_ENUM_CRLS_METHODDEF
5463 _SSL_TXT2OBJ_METHODDEF
5464 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005465 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005466};
5467
5468
Christian Heimes598894f2016-09-05 23:19:05 +02005469#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005470
5471/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005472 * of the Python C thread library
5473 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5474 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005475
5476static PyThread_type_lock *_ssl_locks = NULL;
5477
Christian Heimes4d98ca92013-08-19 17:36:29 +02005478#if OPENSSL_VERSION_NUMBER >= 0x10000000
5479/* use new CRYPTO_THREADID API. */
5480static void
5481_ssl_threadid_callback(CRYPTO_THREADID *id)
5482{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005483 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005484}
5485#else
5486/* deprecated CRYPTO_set_id_callback() API. */
5487static unsigned long
5488_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005489 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005490}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005491#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005492
Bill Janssen6e027db2007-11-15 22:23:56 +00005493static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005494 (int mode, int n, const char *file, int line) {
5495 /* this function is needed to perform locking on shared data
5496 structures. (Note that OpenSSL uses a number of global data
5497 structures that will be implicitly shared whenever multiple
5498 threads use OpenSSL.) Multi-threaded applications will
5499 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005501 locking_function() must be able to handle up to
5502 CRYPTO_num_locks() different mutex locks. It sets the n-th
5503 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005505 file and line are the file number of the function setting the
5506 lock. They can be useful for debugging.
5507 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005509 if ((_ssl_locks == NULL) ||
5510 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5511 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005513 if (mode & CRYPTO_LOCK) {
5514 PyThread_acquire_lock(_ssl_locks[n], 1);
5515 } else {
5516 PyThread_release_lock(_ssl_locks[n]);
5517 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005518}
5519
5520static int _setup_ssl_threads(void) {
5521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005522 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005524 if (_ssl_locks == NULL) {
5525 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005526 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5527 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005528 if (_ssl_locks == NULL) {
5529 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005530 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005531 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005532 for (i = 0; i < _ssl_locks_count; i++) {
5533 _ssl_locks[i] = PyThread_allocate_lock();
5534 if (_ssl_locks[i] == NULL) {
5535 unsigned int j;
5536 for (j = 0; j < i; j++) {
5537 PyThread_free_lock(_ssl_locks[j]);
5538 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005539 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005540 return 0;
5541 }
5542 }
5543 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005544#if OPENSSL_VERSION_NUMBER >= 0x10000000
5545 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5546#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005547 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005548#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005549 }
5550 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005551}
5552
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005553#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005554
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005555PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005556"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005557for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005558
Martin v. Löwis1a214512008-06-11 05:26:20 +00005559
5560static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005561 PyModuleDef_HEAD_INIT,
5562 "_ssl",
5563 module_doc,
5564 -1,
5565 PySSL_methods,
5566 NULL,
5567 NULL,
5568 NULL,
5569 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005570};
5571
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005572
5573static void
5574parse_openssl_version(unsigned long libver,
5575 unsigned int *major, unsigned int *minor,
5576 unsigned int *fix, unsigned int *patch,
5577 unsigned int *status)
5578{
5579 *status = libver & 0xF;
5580 libver >>= 4;
5581 *patch = libver & 0xFF;
5582 libver >>= 8;
5583 *fix = libver & 0xFF;
5584 libver >>= 8;
5585 *minor = libver & 0xFF;
5586 libver >>= 8;
5587 *major = libver & 0xFF;
5588}
5589
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005590PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005591PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005592{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005593 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005594 unsigned long libver;
5595 unsigned int major, minor, fix, patch, status;
5596 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005597 struct py_ssl_error_code *errcode;
5598 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005599
Antoine Pitrou152efa22010-05-16 18:19:27 +00005600 if (PyType_Ready(&PySSLContext_Type) < 0)
5601 return NULL;
5602 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005603 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005604 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5605 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005606 if (PyType_Ready(&PySSLSession_Type) < 0)
5607 return NULL;
5608
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005609
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005610 m = PyModule_Create(&_sslmodule);
5611 if (m == NULL)
5612 return NULL;
5613 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005614
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005615 /* Load _socket module and its C API */
5616 socket_api = PySocketModule_ImportModuleAndAPI();
5617 if (!socket_api)
5618 return NULL;
5619 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005620
Christian Heimesc941e622017-09-05 15:47:11 +02005621#ifndef OPENSSL_VERSION_1_1
5622 /* Load all algorithms and initialize cpuid */
5623 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005624 /* Init OpenSSL */
5625 SSL_load_error_strings();
5626 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005627#endif
5628
Christian Heimes598894f2016-09-05 23:19:05 +02005629#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005630 /* note that this will start threading if not already started */
5631 if (!_setup_ssl_threads()) {
5632 return NULL;
5633 }
Christian Heimes598894f2016-09-05 23:19:05 +02005634#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5635 /* OpenSSL 1.1.0 builtin thread support is enabled */
5636 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005637#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005639 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005640 sslerror_type_slots[0].pfunc = PyExc_OSError;
5641 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005642 if (PySSLErrorObject == NULL)
5643 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005644
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005645 /* ssl.CertificateError used to be a subclass of ValueError */
5646 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5647 if (bases == NULL)
5648 return NULL;
5649 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5650 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5651 bases, NULL);
5652 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005653 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5654 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5655 PySSLErrorObject, NULL);
5656 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5657 "ssl.SSLWantReadError", SSLWantReadError_doc,
5658 PySSLErrorObject, NULL);
5659 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5660 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5661 PySSLErrorObject, NULL);
5662 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5663 "ssl.SSLSyscallError", SSLSyscallError_doc,
5664 PySSLErrorObject, NULL);
5665 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5666 "ssl.SSLEOFError", SSLEOFError_doc,
5667 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005668 if (PySSLCertVerificationErrorObject == NULL
5669 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005670 || PySSLWantReadErrorObject == NULL
5671 || PySSLWantWriteErrorObject == NULL
5672 || PySSLSyscallErrorObject == NULL
5673 || PySSLEOFErrorObject == NULL)
5674 return NULL;
5675 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005676 || PyDict_SetItemString(d, "SSLCertVerificationError",
5677 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005678 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5679 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5680 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5681 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5682 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005683 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005684 if (PyDict_SetItemString(d, "_SSLContext",
5685 (PyObject *)&PySSLContext_Type) != 0)
5686 return NULL;
5687 if (PyDict_SetItemString(d, "_SSLSocket",
5688 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005689 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005690 if (PyDict_SetItemString(d, "MemoryBIO",
5691 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5692 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005693 if (PyDict_SetItemString(d, "SSLSession",
5694 (PyObject *)&PySSLSession_Type) != 0)
5695 return NULL;
5696
Christian Heimes892d66e2018-01-29 14:10:18 +01005697 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5698 PY_SSL_DEFAULT_CIPHER_STRING);
5699
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005700 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5701 PY_SSL_ERROR_ZERO_RETURN);
5702 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5703 PY_SSL_ERROR_WANT_READ);
5704 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5705 PY_SSL_ERROR_WANT_WRITE);
5706 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5707 PY_SSL_ERROR_WANT_X509_LOOKUP);
5708 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5709 PY_SSL_ERROR_SYSCALL);
5710 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5711 PY_SSL_ERROR_SSL);
5712 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5713 PY_SSL_ERROR_WANT_CONNECT);
5714 /* non ssl.h errorcodes */
5715 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5716 PY_SSL_ERROR_EOF);
5717 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5718 PY_SSL_ERROR_INVALID_ERROR_CODE);
5719 /* cert requirements */
5720 PyModule_AddIntConstant(m, "CERT_NONE",
5721 PY_SSL_CERT_NONE);
5722 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5723 PY_SSL_CERT_OPTIONAL);
5724 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5725 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005726 /* CRL verification for verification_flags */
5727 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5728 0);
5729 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5730 X509_V_FLAG_CRL_CHECK);
5731 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5732 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5733 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5734 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005735#ifdef X509_V_FLAG_TRUSTED_FIRST
5736 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5737 X509_V_FLAG_TRUSTED_FIRST);
5738#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005739
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005740 /* Alert Descriptions from ssl.h */
5741 /* note RESERVED constants no longer intended for use have been removed */
5742 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5743
5744#define ADD_AD_CONSTANT(s) \
5745 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5746 SSL_AD_##s)
5747
5748 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5749 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5750 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5751 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5752 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5753 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5754 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5755 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5756 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5757 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5758 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5759 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5760 ADD_AD_CONSTANT(UNKNOWN_CA);
5761 ADD_AD_CONSTANT(ACCESS_DENIED);
5762 ADD_AD_CONSTANT(DECODE_ERROR);
5763 ADD_AD_CONSTANT(DECRYPT_ERROR);
5764 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5765 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5766 ADD_AD_CONSTANT(INTERNAL_ERROR);
5767 ADD_AD_CONSTANT(USER_CANCELLED);
5768 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005769 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005770#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5771 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5772#endif
5773#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5774 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5775#endif
5776#ifdef SSL_AD_UNRECOGNIZED_NAME
5777 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5778#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005779#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5780 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5781#endif
5782#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5783 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5784#endif
5785#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5786 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5787#endif
5788
5789#undef ADD_AD_CONSTANT
5790
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005791 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005792#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005793 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5794 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005795#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005796#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005797 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5798 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005799#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005800 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005801 PY_SSL_VERSION_TLS);
5802 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5803 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005804 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5805 PY_SSL_VERSION_TLS_CLIENT);
5806 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5807 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005808 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5809 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005810#if HAVE_TLSv1_2
5811 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5812 PY_SSL_VERSION_TLS1_1);
5813 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5814 PY_SSL_VERSION_TLS1_2);
5815#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005816
Antoine Pitroub5218772010-05-21 09:56:06 +00005817 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005818 PyModule_AddIntConstant(m, "OP_ALL",
5819 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005820 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5821 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5822 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005823#if HAVE_TLSv1_2
5824 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5825 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5826#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005827#ifdef SSL_OP_NO_TLSv1_3
5828 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5829#else
5830 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5831#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005832 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5833 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005834 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005835 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005836#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005837 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005838#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005839#ifdef SSL_OP_NO_COMPRESSION
5840 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5841 SSL_OP_NO_COMPRESSION);
5842#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005843#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5844 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5845 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5846#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005847#ifdef SSL_OP_NO_RENEGOTIATION
5848 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5849 SSL_OP_NO_RENEGOTIATION);
5850#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005851
Christian Heimes61d478c2018-01-27 15:51:38 +01005852#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5853 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5854 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5855#endif
5856#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5857 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5858 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5859#endif
5860#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5861 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5862 X509_CHECK_FLAG_NO_WILDCARDS);
5863#endif
5864#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5865 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5866 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5867#endif
5868#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5869 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5870 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5871#endif
5872#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5873 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5874 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5875#endif
5876
Christian Heimes698dde12018-02-27 11:54:43 +01005877 /* protocol versions */
5878 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5879 PY_PROTO_MINIMUM_SUPPORTED);
5880 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5881 PY_PROTO_MAXIMUM_SUPPORTED);
5882 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5883 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5884 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5885 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5886 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005887
Christian Heimes698dde12018-02-27 11:54:43 +01005888#define addbool(m, v, b) \
5889 Py_INCREF((b) ? Py_True : Py_False); \
5890 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5891
5892#if HAVE_SNI
5893 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005894#else
Christian Heimes698dde12018-02-27 11:54:43 +01005895 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005896#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005897
5898 addbool(m, "HAS_TLS_UNIQUE", 1);
5899
5900#ifndef OPENSSL_NO_ECDH
5901 addbool(m, "HAS_ECDH", 1);
5902#else
5903 addbool(m, "HAS_ECDH", 0);
5904#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005905
Christian Heimes29eab552018-02-25 12:31:33 +01005906#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005907 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005908#else
Christian Heimes698dde12018-02-27 11:54:43 +01005909 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005910#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005911
Christian Heimes29eab552018-02-25 12:31:33 +01005912#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005913 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005914#else
Christian Heimes698dde12018-02-27 11:54:43 +01005915 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005916#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005917
5918#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5919 addbool(m, "HAS_SSLv2", 1);
5920#else
5921 addbool(m, "HAS_SSLv2", 0);
5922#endif
5923
5924#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5925 addbool(m, "HAS_SSLv3", 1);
5926#else
5927 addbool(m, "HAS_SSLv3", 0);
5928#endif
5929
5930#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5931 addbool(m, "HAS_TLSv1", 1);
5932#else
5933 addbool(m, "HAS_TLSv1", 0);
5934#endif
5935
5936#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5937 addbool(m, "HAS_TLSv1_1", 1);
5938#else
5939 addbool(m, "HAS_TLSv1_1", 0);
5940#endif
5941
5942#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5943 addbool(m, "HAS_TLSv1_2", 1);
5944#else
5945 addbool(m, "HAS_TLSv1_2", 0);
5946#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005947
Christian Heimescb5b68a2017-09-07 18:07:00 -07005948#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005949 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005950#else
Christian Heimes698dde12018-02-27 11:54:43 +01005951 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005952#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005953
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005954 /* Mappings for error codes */
5955 err_codes_to_names = PyDict_New();
5956 err_names_to_codes = PyDict_New();
5957 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5958 return NULL;
5959 errcode = error_codes;
5960 while (errcode->mnemonic != NULL) {
5961 PyObject *mnemo, *key;
5962 mnemo = PyUnicode_FromString(errcode->mnemonic);
5963 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5964 if (mnemo == NULL || key == NULL)
5965 return NULL;
5966 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5967 return NULL;
5968 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5969 return NULL;
5970 Py_DECREF(key);
5971 Py_DECREF(mnemo);
5972 errcode++;
5973 }
5974 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5975 return NULL;
5976 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5977 return NULL;
5978
5979 lib_codes_to_names = PyDict_New();
5980 if (lib_codes_to_names == NULL)
5981 return NULL;
5982 libcode = library_codes;
5983 while (libcode->library != NULL) {
5984 PyObject *mnemo, *key;
5985 key = PyLong_FromLong(libcode->code);
5986 mnemo = PyUnicode_FromString(libcode->library);
5987 if (key == NULL || mnemo == NULL)
5988 return NULL;
5989 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5990 return NULL;
5991 Py_DECREF(key);
5992 Py_DECREF(mnemo);
5993 libcode++;
5994 }
5995 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5996 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005998 /* OpenSSL version */
5999 /* SSLeay() gives us the version of the library linked against,
6000 which could be different from the headers version.
6001 */
6002 libver = SSLeay();
6003 r = PyLong_FromUnsignedLong(libver);
6004 if (r == NULL)
6005 return NULL;
6006 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6007 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006008 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006009 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6010 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6011 return NULL;
6012 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6013 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6014 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006015
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006016 libver = OPENSSL_VERSION_NUMBER;
6017 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6018 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6019 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6020 return NULL;
6021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006022 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006023}