blob: bf379f01a1d2bf5d418848bf0f432279cb8c7b59 [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 */
904 (void) ERR_get_state();
905 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000906
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000907 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000908 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000909 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200910 SSL_set_app_data(self->ssl, self);
911 if (sock) {
912 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
913 } else {
914 /* BIOs are reference counted and SSL_set_bio borrows our reference.
915 * To prevent a double free in memory_bio_dealloc() we need to take an
916 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200917 BIO_up_ref(inbio->bio);
918 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200919 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
920 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400921 SSL_set_mode(self->ssl,
922 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000923
Christian Heimes61d478c2018-01-27 15:51:38 +0100924 if (server_hostname != NULL) {
925 if (_ssl_configure_hostname(self, server_hostname) < 0) {
926 Py_DECREF(self);
927 return NULL;
928 }
929 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 /* If the socket is in non-blocking mode or timeout mode, set the BIO
931 * to non-blocking mode (blocking is the default)
932 */
Victor Stinnere2452312015-03-28 03:00:46 +0100933 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
935 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
936 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000937
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 PySSL_BEGIN_ALLOW_THREADS
939 if (socket_type == PY_SSL_CLIENT)
940 SSL_set_connect_state(self->ssl);
941 else
942 SSL_set_accept_state(self->ssl);
943 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000944
Antoine Pitroud6494802011-07-21 01:11:30 +0200945 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200946 if (sock != NULL) {
947 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
948 if (self->Socket == NULL) {
949 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200950 return NULL;
951 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100952 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100953 if (owner && owner != Py_None) {
954 if (PySSL_set_owner(self, owner, NULL) == -1) {
955 Py_DECREF(self);
956 return NULL;
957 }
958 }
959 if (session && session != Py_None) {
960 if (PySSL_set_session(self, session, NULL) == -1) {
961 Py_DECREF(self);
962 return NULL;
963 }
964 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000966}
967
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000968/* SSL object methods */
969
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300970/*[clinic input]
971_ssl._SSLSocket.do_handshake
972[clinic start generated code]*/
973
974static PyObject *
975_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
976/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000977{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000978 int ret;
979 int err;
980 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200981 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200982 _PyTime_t timeout, deadline = 0;
983 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000984
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200985 if (sock) {
986 if (((PyObject*)sock) == Py_None) {
987 _setSSLError("Underlying socket connection gone",
988 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
989 return NULL;
990 }
991 Py_INCREF(sock);
992
993 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100994 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200995 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
996 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000998
Victor Stinner14690702015-04-06 22:46:13 +0200999 timeout = GET_SOCKET_TIMEOUT(sock);
1000 has_timeout = (timeout > 0);
1001 if (has_timeout)
1002 deadline = _PyTime_GetMonotonicClock() + timeout;
1003
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 /* Actually negotiate SSL connection */
1005 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001007 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07001009 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001010 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07001011 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001012
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001013 if (PyErr_CheckSignals())
1014 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001015
Victor Stinner14690702015-04-06 22:46:13 +02001016 if (has_timeout)
1017 timeout = deadline - _PyTime_GetMonotonicClock();
1018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001020 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001022 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 } else {
1024 sockstate = SOCKET_OPERATION_OK;
1025 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001026
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001028 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001029 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001030 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1032 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001033 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001034 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001035 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1036 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001037 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001038 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1040 break;
1041 }
1042 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001043 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 if (ret < 1)
1045 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001046
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001047 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001048
1049error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001050 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001051 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001052}
1053
Thomas Woutersed03b412007-08-28 21:37:11 +00001054static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001055_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1056{
1057 char buf[X509_NAME_MAXLEN];
1058 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001060 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001061
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001062 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 if (buflen < 0) {
1064 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001065 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001067 /* initial buffer is too small for oid + terminating null byte */
1068 if (buflen > X509_NAME_MAXLEN - 1) {
1069 /* make OBJ_obj2txt() calculate the required buflen */
1070 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1071 /* allocate len + 1 for terminating NULL byte */
1072 namebuf = PyMem_Malloc(buflen + 1);
1073 if (namebuf == NULL) {
1074 PyErr_NoMemory();
1075 return NULL;
1076 }
1077 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1078 if (buflen < 0) {
1079 _setSSLError(NULL, 0, __FILE__, __LINE__);
1080 goto done;
1081 }
1082 }
1083 if (!buflen && no_name) {
1084 Py_INCREF(Py_None);
1085 name_obj = Py_None;
1086 }
1087 else {
1088 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1089 }
1090
1091 done:
1092 if (buf != namebuf) {
1093 PyMem_Free(namebuf);
1094 }
1095 return name_obj;
1096}
1097
1098static PyObject *
1099_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1100{
1101 Py_ssize_t buflen;
1102 unsigned char *valuebuf = NULL;
1103 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001104
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1106 if (buflen < 0) {
1107 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001108 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001109 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001110 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001113}
1114
1115static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001116_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001117{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1119 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1120 PyObject *rdnt;
1121 PyObject *attr = NULL; /* tuple to hold an attribute */
1122 int entry_count = X509_NAME_entry_count(xname);
1123 X509_NAME_ENTRY *entry;
1124 ASN1_OBJECT *name;
1125 ASN1_STRING *value;
1126 int index_counter;
1127 int rdn_level = -1;
1128 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001129
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 dn = PyList_New(0);
1131 if (dn == NULL)
1132 return NULL;
1133 /* now create another tuple to hold the top-level RDN */
1134 rdn = PyList_New(0);
1135 if (rdn == NULL)
1136 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 for (index_counter = 0;
1139 index_counter < entry_count;
1140 index_counter++)
1141 {
1142 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 /* check to see if we've gotten to a new RDN */
1145 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001146 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 /* yes, new RDN */
1148 /* add old RDN to DN */
1149 rdnt = PyList_AsTuple(rdn);
1150 Py_DECREF(rdn);
1151 if (rdnt == NULL)
1152 goto fail0;
1153 retcode = PyList_Append(dn, rdnt);
1154 Py_DECREF(rdnt);
1155 if (retcode < 0)
1156 goto fail0;
1157 /* create new RDN */
1158 rdn = PyList_New(0);
1159 if (rdn == NULL)
1160 goto fail0;
1161 }
1162 }
Christian Heimes598894f2016-09-05 23:19:05 +02001163 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 /* now add this attribute to the current RDN */
1166 name = X509_NAME_ENTRY_get_object(entry);
1167 value = X509_NAME_ENTRY_get_data(entry);
1168 attr = _create_tuple_for_attribute(name, value);
1169 /*
1170 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1171 entry->set,
1172 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1173 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1174 */
1175 if (attr == NULL)
1176 goto fail1;
1177 retcode = PyList_Append(rdn, attr);
1178 Py_DECREF(attr);
1179 if (retcode < 0)
1180 goto fail1;
1181 }
1182 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001183 if (rdn != NULL) {
1184 if (PyList_GET_SIZE(rdn) > 0) {
1185 rdnt = PyList_AsTuple(rdn);
1186 Py_DECREF(rdn);
1187 if (rdnt == NULL)
1188 goto fail0;
1189 retcode = PyList_Append(dn, rdnt);
1190 Py_DECREF(rdnt);
1191 if (retcode < 0)
1192 goto fail0;
1193 }
1194 else {
1195 Py_DECREF(rdn);
1196 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001199 /* convert list to tuple */
1200 rdnt = PyList_AsTuple(dn);
1201 Py_DECREF(dn);
1202 if (rdnt == NULL)
1203 return NULL;
1204 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205
1206 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001207 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
1209 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 Py_XDECREF(dn);
1211 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001212}
1213
1214static PyObject *
1215_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 /* this code follows the procedure outlined in
1218 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1219 function to extract the STACK_OF(GENERAL_NAME),
1220 then iterates through the stack to add the
1221 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001222
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001223 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001225 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 GENERAL_NAMES *names = NULL;
1227 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001228 BIO *biobuf = NULL;
1229 char buf[2048];
1230 char *vptr;
1231 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001232
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001233 if (certificate == NULL)
1234 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 /* get a memory buffer */
1237 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001239 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1240 certificate, NID_subject_alt_name, NULL, NULL);
1241 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 if (peer_alt_names == Py_None) {
1243 peer_alt_names = PyList_New(0);
1244 if (peer_alt_names == NULL)
1245 goto fail;
1246 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001248 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001250 int gntype;
1251 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001254 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001255 switch (gntype) {
1256 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001257 /* we special-case DirName as a tuple of
1258 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001259
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 t = PyTuple_New(2);
1261 if (t == NULL) {
1262 goto fail;
1263 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 v = PyUnicode_FromString("DirName");
1266 if (v == NULL) {
1267 Py_DECREF(t);
1268 goto fail;
1269 }
1270 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 v = _create_tuple_for_X509_NAME (name->d.dirn);
1273 if (v == NULL) {
1274 Py_DECREF(t);
1275 goto fail;
1276 }
1277 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001278 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001279
Christian Heimes824f7f32013-08-17 00:54:47 +02001280 case GEN_EMAIL:
1281 case GEN_DNS:
1282 case GEN_URI:
1283 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1284 correctly, CVE-2013-4238 */
1285 t = PyTuple_New(2);
1286 if (t == NULL)
1287 goto fail;
1288 switch (gntype) {
1289 case GEN_EMAIL:
1290 v = PyUnicode_FromString("email");
1291 as = name->d.rfc822Name;
1292 break;
1293 case GEN_DNS:
1294 v = PyUnicode_FromString("DNS");
1295 as = name->d.dNSName;
1296 break;
1297 case GEN_URI:
1298 v = PyUnicode_FromString("URI");
1299 as = name->d.uniformResourceIdentifier;
1300 break;
1301 }
1302 if (v == NULL) {
1303 Py_DECREF(t);
1304 goto fail;
1305 }
1306 PyTuple_SET_ITEM(t, 0, v);
1307 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1308 ASN1_STRING_length(as));
1309 if (v == NULL) {
1310 Py_DECREF(t);
1311 goto fail;
1312 }
1313 PyTuple_SET_ITEM(t, 1, v);
1314 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001315
Christian Heimes1c03abd2016-09-06 23:25:35 +02001316 case GEN_RID:
1317 t = PyTuple_New(2);
1318 if (t == NULL)
1319 goto fail;
1320
1321 v = PyUnicode_FromString("Registered ID");
1322 if (v == NULL) {
1323 Py_DECREF(t);
1324 goto fail;
1325 }
1326 PyTuple_SET_ITEM(t, 0, v);
1327
1328 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1329 if (len < 0) {
1330 Py_DECREF(t);
1331 _setSSLError(NULL, 0, __FILE__, __LINE__);
1332 goto fail;
1333 } else if (len >= (int)sizeof(buf)) {
1334 v = PyUnicode_FromString("<INVALID>");
1335 } else {
1336 v = PyUnicode_FromStringAndSize(buf, len);
1337 }
1338 if (v == NULL) {
1339 Py_DECREF(t);
1340 goto fail;
1341 }
1342 PyTuple_SET_ITEM(t, 1, v);
1343 break;
1344
Christian Heimes824f7f32013-08-17 00:54:47 +02001345 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001347 switch (gntype) {
1348 /* check for new general name type */
1349 case GEN_OTHERNAME:
1350 case GEN_X400:
1351 case GEN_EDIPARTY:
1352 case GEN_IPADD:
1353 case GEN_RID:
1354 break;
1355 default:
1356 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1357 "Unknown general name type %d",
1358 gntype) == -1) {
1359 goto fail;
1360 }
1361 break;
1362 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 (void) BIO_reset(biobuf);
1364 GENERAL_NAME_print(biobuf, name);
1365 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1366 if (len < 0) {
1367 _setSSLError(NULL, 0, __FILE__, __LINE__);
1368 goto fail;
1369 }
1370 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001371 if (vptr == NULL) {
1372 PyErr_Format(PyExc_ValueError,
1373 "Invalid value %.200s",
1374 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001376 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001377 t = PyTuple_New(2);
1378 if (t == NULL)
1379 goto fail;
1380 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1381 if (v == NULL) {
1382 Py_DECREF(t);
1383 goto fail;
1384 }
1385 PyTuple_SET_ITEM(t, 0, v);
1386 v = PyUnicode_FromStringAndSize((vptr + 1),
1387 (len - (vptr - buf + 1)));
1388 if (v == NULL) {
1389 Py_DECREF(t);
1390 goto fail;
1391 }
1392 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001393 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001394 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001396 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001397
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 if (PyList_Append(peer_alt_names, t) < 0) {
1399 Py_DECREF(t);
1400 goto fail;
1401 }
1402 Py_DECREF(t);
1403 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001404 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001405 }
1406 BIO_free(biobuf);
1407 if (peer_alt_names != Py_None) {
1408 v = PyList_AsTuple(peer_alt_names);
1409 Py_DECREF(peer_alt_names);
1410 return v;
1411 } else {
1412 return peer_alt_names;
1413 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001414
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001415
1416 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 if (biobuf != NULL)
1418 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001419
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 if (peer_alt_names != Py_None) {
1421 Py_XDECREF(peer_alt_names);
1422 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001424 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001425}
1426
1427static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001428_get_aia_uri(X509 *certificate, int nid) {
1429 PyObject *lst = NULL, *ostr = NULL;
1430 int i, result;
1431 AUTHORITY_INFO_ACCESS *info;
1432
1433 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001434 if (info == NULL)
1435 return Py_None;
1436 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1437 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001438 return Py_None;
1439 }
1440
1441 if ((lst = PyList_New(0)) == NULL) {
1442 goto fail;
1443 }
1444
1445 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1446 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1447 ASN1_IA5STRING *uri;
1448
1449 if ((OBJ_obj2nid(ad->method) != nid) ||
1450 (ad->location->type != GEN_URI)) {
1451 continue;
1452 }
1453 uri = ad->location->d.uniformResourceIdentifier;
1454 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1455 uri->length);
1456 if (ostr == NULL) {
1457 goto fail;
1458 }
1459 result = PyList_Append(lst, ostr);
1460 Py_DECREF(ostr);
1461 if (result < 0) {
1462 goto fail;
1463 }
1464 }
1465 AUTHORITY_INFO_ACCESS_free(info);
1466
1467 /* convert to tuple or None */
1468 if (PyList_Size(lst) == 0) {
1469 Py_DECREF(lst);
1470 return Py_None;
1471 } else {
1472 PyObject *tup;
1473 tup = PyList_AsTuple(lst);
1474 Py_DECREF(lst);
1475 return tup;
1476 }
1477
1478 fail:
1479 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001480 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001481 return NULL;
1482}
1483
1484static PyObject *
1485_get_crl_dp(X509 *certificate) {
1486 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001487 int i, j;
1488 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001489
Christian Heimes598894f2016-09-05 23:19:05 +02001490 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001491
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001492 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001493 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001494
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001495 lst = PyList_New(0);
1496 if (lst == NULL)
1497 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001498
1499 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1500 DIST_POINT *dp;
1501 STACK_OF(GENERAL_NAME) *gns;
1502
1503 dp = sk_DIST_POINT_value(dps, i);
1504 gns = dp->distpoint->name.fullname;
1505
1506 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1507 GENERAL_NAME *gn;
1508 ASN1_IA5STRING *uri;
1509 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001510 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001511
1512 gn = sk_GENERAL_NAME_value(gns, j);
1513 if (gn->type != GEN_URI) {
1514 continue;
1515 }
1516 uri = gn->d.uniformResourceIdentifier;
1517 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1518 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001519 if (ouri == NULL)
1520 goto done;
1521
1522 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001523 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001524 if (err < 0)
1525 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001526 }
1527 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001528
1529 /* Convert to tuple. */
1530 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1531
1532 done:
1533 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001534 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001535 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001536}
1537
1538static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001539_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 PyObject *retval = NULL;
1542 BIO *biobuf = NULL;
1543 PyObject *peer;
1544 PyObject *peer_alt_names = NULL;
1545 PyObject *issuer;
1546 PyObject *version;
1547 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001548 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 ASN1_INTEGER *serialNumber;
1550 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001551 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 ASN1_TIME *notBefore, *notAfter;
1553 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001554
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 retval = PyDict_New();
1556 if (retval == NULL)
1557 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 peer = _create_tuple_for_X509_NAME(
1560 X509_get_subject_name(certificate));
1561 if (peer == NULL)
1562 goto fail0;
1563 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1564 Py_DECREF(peer);
1565 goto fail0;
1566 }
1567 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001568
Antoine Pitroufb046912010-11-09 20:21:19 +00001569 issuer = _create_tuple_for_X509_NAME(
1570 X509_get_issuer_name(certificate));
1571 if (issuer == NULL)
1572 goto fail0;
1573 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001574 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001575 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001576 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001577 Py_DECREF(issuer);
1578
1579 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001580 if (version == NULL)
1581 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001582 if (PyDict_SetItemString(retval, "version", version) < 0) {
1583 Py_DECREF(version);
1584 goto fail0;
1585 }
1586 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001587
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001588 /* get a memory buffer */
1589 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001590
Antoine Pitroufb046912010-11-09 20:21:19 +00001591 (void) BIO_reset(biobuf);
1592 serialNumber = X509_get_serialNumber(certificate);
1593 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1594 i2a_ASN1_INTEGER(biobuf, serialNumber);
1595 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1596 if (len < 0) {
1597 _setSSLError(NULL, 0, __FILE__, __LINE__);
1598 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001599 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001600 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1601 if (sn_obj == NULL)
1602 goto fail1;
1603 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1604 Py_DECREF(sn_obj);
1605 goto fail1;
1606 }
1607 Py_DECREF(sn_obj);
1608
1609 (void) BIO_reset(biobuf);
1610 notBefore = X509_get_notBefore(certificate);
1611 ASN1_TIME_print(biobuf, notBefore);
1612 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1613 if (len < 0) {
1614 _setSSLError(NULL, 0, __FILE__, __LINE__);
1615 goto fail1;
1616 }
1617 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1618 if (pnotBefore == NULL)
1619 goto fail1;
1620 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1621 Py_DECREF(pnotBefore);
1622 goto fail1;
1623 }
1624 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001625
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 (void) BIO_reset(biobuf);
1627 notAfter = X509_get_notAfter(certificate);
1628 ASN1_TIME_print(biobuf, notAfter);
1629 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1630 if (len < 0) {
1631 _setSSLError(NULL, 0, __FILE__, __LINE__);
1632 goto fail1;
1633 }
1634 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1635 if (pnotAfter == NULL)
1636 goto fail1;
1637 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1638 Py_DECREF(pnotAfter);
1639 goto fail1;
1640 }
1641 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001643 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001644
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001645 peer_alt_names = _get_peer_alt_names(certificate);
1646 if (peer_alt_names == NULL)
1647 goto fail1;
1648 else if (peer_alt_names != Py_None) {
1649 if (PyDict_SetItemString(retval, "subjectAltName",
1650 peer_alt_names) < 0) {
1651 Py_DECREF(peer_alt_names);
1652 goto fail1;
1653 }
1654 Py_DECREF(peer_alt_names);
1655 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001656
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001657 /* Authority Information Access: OCSP URIs */
1658 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1659 if (obj == NULL) {
1660 goto fail1;
1661 } else if (obj != Py_None) {
1662 result = PyDict_SetItemString(retval, "OCSP", obj);
1663 Py_DECREF(obj);
1664 if (result < 0) {
1665 goto fail1;
1666 }
1667 }
1668
1669 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1670 if (obj == NULL) {
1671 goto fail1;
1672 } else if (obj != Py_None) {
1673 result = PyDict_SetItemString(retval, "caIssuers", obj);
1674 Py_DECREF(obj);
1675 if (result < 0) {
1676 goto fail1;
1677 }
1678 }
1679
1680 /* CDP (CRL distribution points) */
1681 obj = _get_crl_dp(certificate);
1682 if (obj == NULL) {
1683 goto fail1;
1684 } else if (obj != Py_None) {
1685 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1686 Py_DECREF(obj);
1687 if (result < 0) {
1688 goto fail1;
1689 }
1690 }
1691
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 BIO_free(biobuf);
1693 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001694
1695 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001696 if (biobuf != NULL)
1697 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001698 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 Py_XDECREF(retval);
1700 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001701}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001702
Christian Heimes9a5395a2013-06-17 15:44:12 +02001703static PyObject *
1704_certificate_to_der(X509 *certificate)
1705{
1706 unsigned char *bytes_buf = NULL;
1707 int len;
1708 PyObject *retval;
1709
1710 bytes_buf = NULL;
1711 len = i2d_X509(certificate, &bytes_buf);
1712 if (len < 0) {
1713 _setSSLError(NULL, 0, __FILE__, __LINE__);
1714 return NULL;
1715 }
1716 /* this is actually an immutable bytes sequence */
1717 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1718 OPENSSL_free(bytes_buf);
1719 return retval;
1720}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001721
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001722/*[clinic input]
1723_ssl._test_decode_cert
1724 path: object(converter="PyUnicode_FSConverter")
1725 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001726
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001727[clinic start generated code]*/
1728
1729static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001730_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1731/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001732{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001733 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001734 X509 *x=NULL;
1735 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1738 PyErr_SetString(PySSLErrorObject,
1739 "Can't malloc memory to read file");
1740 goto fail0;
1741 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001742
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001743 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001744 PyErr_SetString(PySSLErrorObject,
1745 "Can't open file");
1746 goto fail0;
1747 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1750 if (x == NULL) {
1751 PyErr_SetString(PySSLErrorObject,
1752 "Error decoding PEM-encoded file");
1753 goto fail0;
1754 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001755
Antoine Pitroufb046912010-11-09 20:21:19 +00001756 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001757 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758
1759 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001760 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001761 if (cert != NULL) BIO_free(cert);
1762 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001763}
1764
1765
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001766/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001767_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001768 der as binary_mode: bool = False
1769 /
1770
1771Returns the certificate for the peer.
1772
1773If no certificate was provided, returns None. If a certificate was
1774provided, but not validated, returns an empty dictionary. Otherwise
1775returns a dict containing information about the peer certificate.
1776
1777If the optional argument is True, returns a DER-encoded copy of the
1778peer certificate, or None if no certificate was provided. This will
1779return the certificate even if it wasn't validated.
1780[clinic start generated code]*/
1781
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001783_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1784/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001786 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001787 X509 *peer_cert;
1788 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001789
Christian Heimes66dc33b2017-05-23 16:02:02 -07001790 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001791 PyErr_SetString(PyExc_ValueError,
1792 "handshake not done yet");
1793 return NULL;
1794 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001795 peer_cert = SSL_get_peer_certificate(self->ssl);
1796 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001798
Antoine Pitrou721738f2012-08-15 23:20:39 +02001799 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001801 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001802 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001803 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001804 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001805 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001806 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001807 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001808 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001809 X509_free(peer_cert);
1810 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001811}
1812
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001813static PyObject *
1814cipher_to_tuple(const SSL_CIPHER *cipher)
1815{
1816 const char *cipher_name, *cipher_protocol;
1817 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001818 if (retval == NULL)
1819 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001820
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001821 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001823 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001824 PyTuple_SET_ITEM(retval, 0, Py_None);
1825 } else {
1826 v = PyUnicode_FromString(cipher_name);
1827 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001828 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001829 PyTuple_SET_ITEM(retval, 0, v);
1830 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001831
1832 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001834 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001835 PyTuple_SET_ITEM(retval, 1, Py_None);
1836 } else {
1837 v = PyUnicode_FromString(cipher_protocol);
1838 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001839 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001840 PyTuple_SET_ITEM(retval, 1, v);
1841 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001842
1843 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001845 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001846 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001847
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001848 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001849
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001850 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 Py_DECREF(retval);
1852 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001853}
1854
Christian Heimes25bfcd52016-09-06 00:04:45 +02001855#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1856static PyObject *
1857cipher_to_dict(const SSL_CIPHER *cipher)
1858{
1859 const char *cipher_name, *cipher_protocol;
1860
1861 unsigned long cipher_id;
1862 int alg_bits, strength_bits, len;
1863 char buf[512] = {0};
1864#if OPENSSL_VERSION_1_1
1865 int aead, nid;
1866 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1867#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001868
1869 /* can be NULL */
1870 cipher_name = SSL_CIPHER_get_name(cipher);
1871 cipher_protocol = SSL_CIPHER_get_version(cipher);
1872 cipher_id = SSL_CIPHER_get_id(cipher);
1873 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001874 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1875 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001876 if (len > 1 && buf[len-1] == '\n')
1877 buf[len-1] = '\0';
1878 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1879
1880#if OPENSSL_VERSION_1_1
1881 aead = SSL_CIPHER_is_aead(cipher);
1882 nid = SSL_CIPHER_get_cipher_nid(cipher);
1883 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1884 nid = SSL_CIPHER_get_digest_nid(cipher);
1885 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1886 nid = SSL_CIPHER_get_kx_nid(cipher);
1887 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1888 nid = SSL_CIPHER_get_auth_nid(cipher);
1889 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1890#endif
1891
Victor Stinner410b9882016-09-12 12:00:23 +02001892 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001893 "{sksssssssisi"
1894#if OPENSSL_VERSION_1_1
1895 "sOssssssss"
1896#endif
1897 "}",
1898 "id", cipher_id,
1899 "name", cipher_name,
1900 "protocol", cipher_protocol,
1901 "description", buf,
1902 "strength_bits", strength_bits,
1903 "alg_bits", alg_bits
1904#if OPENSSL_VERSION_1_1
1905 ,"aead", aead ? Py_True : Py_False,
1906 "symmetric", skcipher,
1907 "digest", digest,
1908 "kea", kx,
1909 "auth", auth
1910#endif
1911 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001912}
1913#endif
1914
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001915/*[clinic input]
1916_ssl._SSLSocket.shared_ciphers
1917[clinic start generated code]*/
1918
1919static PyObject *
1920_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1921/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001922{
1923 STACK_OF(SSL_CIPHER) *ciphers;
1924 int i;
1925 PyObject *res;
1926
Christian Heimes598894f2016-09-05 23:19:05 +02001927 ciphers = SSL_get_ciphers(self->ssl);
1928 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001929 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001930 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1931 if (!res)
1932 return NULL;
1933 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1934 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1935 if (!tup) {
1936 Py_DECREF(res);
1937 return NULL;
1938 }
1939 PyList_SET_ITEM(res, i, tup);
1940 }
1941 return res;
1942}
1943
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001944/*[clinic input]
1945_ssl._SSLSocket.cipher
1946[clinic start generated code]*/
1947
1948static PyObject *
1949_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1950/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001951{
1952 const SSL_CIPHER *current;
1953
1954 if (self->ssl == NULL)
1955 Py_RETURN_NONE;
1956 current = SSL_get_current_cipher(self->ssl);
1957 if (current == NULL)
1958 Py_RETURN_NONE;
1959 return cipher_to_tuple(current);
1960}
1961
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001962/*[clinic input]
1963_ssl._SSLSocket.version
1964[clinic start generated code]*/
1965
1966static PyObject *
1967_ssl__SSLSocket_version_impl(PySSLSocket *self)
1968/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001969{
1970 const char *version;
1971
1972 if (self->ssl == NULL)
1973 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001974 if (!SSL_is_init_finished(self->ssl)) {
1975 /* handshake not finished */
1976 Py_RETURN_NONE;
1977 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001978 version = SSL_get_version(self->ssl);
1979 if (!strcmp(version, "unknown"))
1980 Py_RETURN_NONE;
1981 return PyUnicode_FromString(version);
1982}
1983
Christian Heimes29eab552018-02-25 12:31:33 +01001984#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001985/*[clinic input]
1986_ssl._SSLSocket.selected_npn_protocol
1987[clinic start generated code]*/
1988
1989static PyObject *
1990_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1991/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1992{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001993 const unsigned char *out;
1994 unsigned int outlen;
1995
Victor Stinner4569cd52013-06-23 14:58:43 +02001996 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001997 &out, &outlen);
1998
1999 if (out == NULL)
2000 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002001 return PyUnicode_FromStringAndSize((char *)out, outlen);
2002}
2003#endif
2004
Christian Heimes29eab552018-02-25 12:31:33 +01002005#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002006/*[clinic input]
2007_ssl._SSLSocket.selected_alpn_protocol
2008[clinic start generated code]*/
2009
2010static PyObject *
2011_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2012/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2013{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002014 const unsigned char *out;
2015 unsigned int outlen;
2016
2017 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2018
2019 if (out == NULL)
2020 Py_RETURN_NONE;
2021 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002022}
2023#endif
2024
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002025/*[clinic input]
2026_ssl._SSLSocket.compression
2027[clinic start generated code]*/
2028
2029static PyObject *
2030_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2031/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2032{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002033#ifdef OPENSSL_NO_COMP
2034 Py_RETURN_NONE;
2035#else
2036 const COMP_METHOD *comp_method;
2037 const char *short_name;
2038
2039 if (self->ssl == NULL)
2040 Py_RETURN_NONE;
2041 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002042 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002043 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002044 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002045 if (short_name == NULL)
2046 Py_RETURN_NONE;
2047 return PyUnicode_DecodeFSDefault(short_name);
2048#endif
2049}
2050
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002051static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2052 Py_INCREF(self->ctx);
2053 return self->ctx;
2054}
2055
2056static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2057 void *closure) {
2058
2059 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002060#if !HAVE_SNI
2061 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2062 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002063 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002064#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002065 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002066 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002067 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002068#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002069 } else {
2070 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2071 return -1;
2072 }
2073
2074 return 0;
2075}
2076
2077PyDoc_STRVAR(PySSL_set_context_doc,
2078"_setter_context(ctx)\n\
2079\
2080This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002081used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002082on the SSLContext to change the certificate information associated with the\n\
2083SSLSocket before the cryptographic exchange handshake messages\n");
2084
2085
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002086static PyObject *
2087PySSL_get_server_side(PySSLSocket *self, void *c)
2088{
2089 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2090}
2091
2092PyDoc_STRVAR(PySSL_get_server_side_doc,
2093"Whether this is a server-side socket.");
2094
2095static PyObject *
2096PySSL_get_server_hostname(PySSLSocket *self, void *c)
2097{
2098 if (self->server_hostname == NULL)
2099 Py_RETURN_NONE;
2100 Py_INCREF(self->server_hostname);
2101 return self->server_hostname;
2102}
2103
2104PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2105"The currently set server hostname (for SNI).");
2106
2107static PyObject *
2108PySSL_get_owner(PySSLSocket *self, void *c)
2109{
2110 PyObject *owner;
2111
2112 if (self->owner == NULL)
2113 Py_RETURN_NONE;
2114
2115 owner = PyWeakref_GetObject(self->owner);
2116 Py_INCREF(owner);
2117 return owner;
2118}
2119
2120static int
2121PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2122{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002123 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002124 if (self->owner == NULL)
2125 return -1;
2126 return 0;
2127}
2128
2129PyDoc_STRVAR(PySSL_get_owner_doc,
2130"The Python-level owner of this object.\
2131Passed as \"self\" in servername callback.");
2132
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002133
Antoine Pitrou152efa22010-05-16 18:19:27 +00002134static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002135{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002136 if (self->ssl)
2137 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002139 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002140 Py_XDECREF(self->server_hostname);
2141 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002143}
2144
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002145/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002146 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002147 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002148 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002149
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002150static int
Victor Stinner14690702015-04-06 22:46:13 +02002151PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002152{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002153 int rc;
2154#ifdef HAVE_POLL
2155 struct pollfd pollfd;
2156 _PyTime_t ms;
2157#else
2158 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 fd_set fds;
2160 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002161#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002162
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002164 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002166 else if (timeout < 0) {
2167 if (s->sock_timeout > 0)
2168 return SOCKET_HAS_TIMED_OUT;
2169 else
2170 return SOCKET_IS_BLOCKING;
2171 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002173 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002174 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002175 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002177 /* Prefer poll, if available, since you can poll() any fd
2178 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002179#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002180 pollfd.fd = s->sock_fd;
2181 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002182
Victor Stinner14690702015-04-06 22:46:13 +02002183 /* timeout is in seconds, poll() uses milliseconds */
2184 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002185 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002186
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002187 PySSL_BEGIN_ALLOW_THREADS
2188 rc = poll(&pollfd, 1, (int)ms);
2189 PySSL_END_ALLOW_THREADS
2190#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002191 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002192 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002194
Victor Stinner14690702015-04-06 22:46:13 +02002195 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002196
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002197 FD_ZERO(&fds);
2198 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002199
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002200 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002201 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002202 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002204 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002208#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2211 (when we are able to write or when there's something to read) */
2212 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002213}
2214
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002215/*[clinic input]
2216_ssl._SSLSocket.write
2217 b: Py_buffer
2218 /
2219
2220Writes the bytes-like object b into the SSL object.
2221
2222Returns the number of bytes written.
2223[clinic start generated code]*/
2224
2225static PyObject *
2226_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2227/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002228{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 int len;
2230 int sockstate;
2231 int err;
2232 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002233 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002234 _PyTime_t timeout, deadline = 0;
2235 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002236
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002237 if (sock != NULL) {
2238 if (((PyObject*)sock) == Py_None) {
2239 _setSSLError("Underlying socket connection gone",
2240 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2241 return NULL;
2242 }
2243 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 }
2245
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002246 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002247 PyErr_Format(PyExc_OverflowError,
2248 "string longer than %d bytes", INT_MAX);
2249 goto error;
2250 }
2251
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002252 if (sock != NULL) {
2253 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002254 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002255 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2256 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2257 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258
Victor Stinner14690702015-04-06 22:46:13 +02002259 timeout = GET_SOCKET_TIMEOUT(sock);
2260 has_timeout = (timeout > 0);
2261 if (has_timeout)
2262 deadline = _PyTime_GetMonotonicClock() + timeout;
2263
2264 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002266 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 "The write operation timed out");
2268 goto error;
2269 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2270 PyErr_SetString(PySSLErrorObject,
2271 "Underlying socket has been closed.");
2272 goto error;
2273 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2274 PyErr_SetString(PySSLErrorObject,
2275 "Underlying socket too large for select().");
2276 goto error;
2277 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002281 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002282 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002284 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002285
2286 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002288
Victor Stinner14690702015-04-06 22:46:13 +02002289 if (has_timeout)
2290 timeout = deadline - _PyTime_GetMonotonicClock();
2291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002292 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002293 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002295 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 } else {
2297 sockstate = SOCKET_OPERATION_OK;
2298 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002300 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002301 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002302 "The write operation timed out");
2303 goto error;
2304 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2305 PyErr_SetString(PySSLErrorObject,
2306 "Underlying socket has been closed.");
2307 goto error;
2308 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2309 break;
2310 }
2311 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002312
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002313 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 if (len > 0)
2315 return PyLong_FromLong(len);
2316 else
2317 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002318
2319error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002320 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002321 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002322}
2323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002324/*[clinic input]
2325_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002326
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002327Returns the number of already decrypted bytes available for read, pending on the connection.
2328[clinic start generated code]*/
2329
2330static PyObject *
2331_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2332/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002333{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002336 PySSL_BEGIN_ALLOW_THREADS
2337 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002338 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 PySSL_END_ALLOW_THREADS
2340 if (count < 0)
2341 return PySSL_SetError(self, count, __FILE__, __LINE__);
2342 else
2343 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002344}
2345
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002346/*[clinic input]
2347_ssl._SSLSocket.read
2348 size as len: int
2349 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002350 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002351 ]
2352 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002353
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002354Read up to size bytes from the SSL socket.
2355[clinic start generated code]*/
2356
2357static PyObject *
2358_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2359 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002360/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002361{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002362 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002364 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 int sockstate;
2366 int err;
2367 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002368 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002369 _PyTime_t timeout, deadline = 0;
2370 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002371
Martin Panter5503d472016-03-27 05:35:19 +00002372 if (!group_right_1 && len < 0) {
2373 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2374 return NULL;
2375 }
2376
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002377 if (sock != NULL) {
2378 if (((PyObject*)sock) == Py_None) {
2379 _setSSLError("Underlying socket connection gone",
2380 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2381 return NULL;
2382 }
2383 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 }
2385
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002386 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002387 dest = PyBytes_FromStringAndSize(NULL, len);
2388 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002389 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002390 if (len == 0) {
2391 Py_XDECREF(sock);
2392 return dest;
2393 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002394 mem = PyBytes_AS_STRING(dest);
2395 }
2396 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002397 mem = buffer->buf;
2398 if (len <= 0 || len > buffer->len) {
2399 len = (int) buffer->len;
2400 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002401 PyErr_SetString(PyExc_OverflowError,
2402 "maximum length can't fit in a C 'int'");
2403 goto error;
2404 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002405 if (len == 0) {
2406 count = 0;
2407 goto done;
2408 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002409 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002410 }
2411
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002412 if (sock != NULL) {
2413 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002414 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002415 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2416 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2417 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002418
Victor Stinner14690702015-04-06 22:46:13 +02002419 timeout = GET_SOCKET_TIMEOUT(sock);
2420 has_timeout = (timeout > 0);
2421 if (has_timeout)
2422 deadline = _PyTime_GetMonotonicClock() + timeout;
2423
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002424 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 PySSL_BEGIN_ALLOW_THREADS
2426 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002427 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 if (PyErr_CheckSignals())
2431 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002432
Victor Stinner14690702015-04-06 22:46:13 +02002433 if (has_timeout)
2434 timeout = deadline - _PyTime_GetMonotonicClock();
2435
Steve Dowere6eb48c2017-09-08 15:16:15 -07002436 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002437 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002438 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002440 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002441 } else if (err == SSL_ERROR_ZERO_RETURN &&
2442 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 {
2444 count = 0;
2445 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002447 else
2448 sockstate = SOCKET_OPERATION_OK;
2449
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002450 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002451 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 "The read operation timed out");
2453 goto error;
2454 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2455 break;
2456 }
2457 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002458
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 if (count <= 0) {
2460 PySSL_SetError(self, count, __FILE__, __LINE__);
2461 goto error;
2462 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002463
2464done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002465 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002466 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002467 _PyBytes_Resize(&dest, count);
2468 return dest;
2469 }
2470 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 return PyLong_FromLong(count);
2472 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002473
2474error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002475 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002476 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002477 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002478 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002479}
2480
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002481/*[clinic input]
2482_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002483
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002484Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002485[clinic start generated code]*/
2486
2487static PyObject *
2488_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002489/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002490{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002491 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002492 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002493 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002494 _PyTime_t timeout, deadline = 0;
2495 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002496
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002497 if (sock != NULL) {
2498 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002499 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002500 _setSSLError("Underlying socket connection gone",
2501 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2502 return NULL;
2503 }
2504 Py_INCREF(sock);
2505
2506 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002507 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002508 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2509 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511
Victor Stinner14690702015-04-06 22:46:13 +02002512 timeout = GET_SOCKET_TIMEOUT(sock);
2513 has_timeout = (timeout > 0);
2514 if (has_timeout)
2515 deadline = _PyTime_GetMonotonicClock() + timeout;
2516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517 while (1) {
2518 PySSL_BEGIN_ALLOW_THREADS
2519 /* Disable read-ahead so that unwrap can work correctly.
2520 * Otherwise OpenSSL might read in too much data,
2521 * eating clear text data that happens to be
2522 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002523 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 * function is used and the shutdown_seen_zero != 0
2525 * condition is met.
2526 */
2527 if (self->shutdown_seen_zero)
2528 SSL_set_read_ahead(self->ssl, 0);
2529 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002530 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002531 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002532
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002533 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2534 if (err > 0)
2535 break;
2536 if (err == 0) {
2537 /* Don't loop endlessly; instead preserve legacy
2538 behaviour of trying SSL_shutdown() only twice.
2539 This looks necessary for OpenSSL < 0.9.8m */
2540 if (++zeros > 1)
2541 break;
2542 /* Shutdown was sent, now try receiving */
2543 self->shutdown_seen_zero = 1;
2544 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002545 }
2546
Victor Stinner14690702015-04-06 22:46:13 +02002547 if (has_timeout)
2548 timeout = deadline - _PyTime_GetMonotonicClock();
2549
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002550 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002551 _PySSL_UPDATE_ERRNO(self, err);
2552 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002553 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002554 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002555 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002556 else
2557 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002560 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002561 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 "The read operation timed out");
2563 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002564 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002566 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002567 }
2568 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2569 PyErr_SetString(PySSLErrorObject,
2570 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002571 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002572 }
2573 else if (sockstate != SOCKET_OPERATION_OK)
2574 /* Retain the SSL error code */
2575 break;
2576 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002577
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002578 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002579 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002580 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002582 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002583 /* It's already INCREF'ed */
2584 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002585 else
2586 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002587
2588error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002589 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002590 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002591}
2592
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002593/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002594_ssl._SSLSocket.get_channel_binding
2595 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002596
Christian Heimes141c5e82018-02-24 21:10:57 +01002597Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002598
Christian Heimes141c5e82018-02-24 21:10:57 +01002599Raise ValueError if the requested `cb_type` is not supported. Return bytes
2600of the data or None if the data is not available (e.g. before the handshake).
2601Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002602[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002603
Antoine Pitroud6494802011-07-21 01:11:30 +02002604static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002605_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2606 const char *cb_type)
2607/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002608{
Antoine Pitroud6494802011-07-21 01:11:30 +02002609 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002610 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002611
Christian Heimes141c5e82018-02-24 21:10:57 +01002612 if (strcmp(cb_type, "tls-unique") == 0) {
2613 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2614 /* if session is resumed XOR we are the client */
2615 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2616 }
2617 else {
2618 /* if a new session XOR we are the server */
2619 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2620 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002621 }
2622 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002623 PyErr_Format(
2624 PyExc_ValueError,
2625 "'%s' channel binding type not implemented",
2626 cb_type
2627 );
2628 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002629 }
2630
2631 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002632 if (len == 0)
2633 Py_RETURN_NONE;
2634
Christian Heimes141c5e82018-02-24 21:10:57 +01002635 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002636}
2637
Christian Heimes99a65702016-09-10 23:44:53 +02002638#ifdef OPENSSL_VERSION_1_1
2639
2640static SSL_SESSION*
2641_ssl_session_dup(SSL_SESSION *session) {
2642 SSL_SESSION *newsession = NULL;
2643 int slen;
2644 unsigned char *senc = NULL, *p;
2645 const unsigned char *const_p;
2646
2647 if (session == NULL) {
2648 PyErr_SetString(PyExc_ValueError, "Invalid session");
2649 goto error;
2650 }
2651
2652 /* get length */
2653 slen = i2d_SSL_SESSION(session, NULL);
2654 if (slen == 0 || slen > 0xFF00) {
2655 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2656 goto error;
2657 }
2658 if ((senc = PyMem_Malloc(slen)) == NULL) {
2659 PyErr_NoMemory();
2660 goto error;
2661 }
2662 p = senc;
2663 if (!i2d_SSL_SESSION(session, &p)) {
2664 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2665 goto error;
2666 }
2667 const_p = senc;
2668 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2669 if (session == NULL) {
2670 goto error;
2671 }
2672 PyMem_Free(senc);
2673 return newsession;
2674 error:
2675 if (senc != NULL) {
2676 PyMem_Free(senc);
2677 }
2678 return NULL;
2679}
2680#endif
2681
2682static PyObject *
2683PySSL_get_session(PySSLSocket *self, void *closure) {
2684 /* get_session can return sessions from a server-side connection,
2685 * it does not check for handshake done or client socket. */
2686 PySSLSession *pysess;
2687 SSL_SESSION *session;
2688
2689#ifdef OPENSSL_VERSION_1_1
2690 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2691 * https://github.com/openssl/openssl/issues/1550 */
2692 session = SSL_get0_session(self->ssl); /* borrowed reference */
2693 if (session == NULL) {
2694 Py_RETURN_NONE;
2695 }
2696 if ((session = _ssl_session_dup(session)) == NULL) {
2697 return NULL;
2698 }
2699#else
2700 session = SSL_get1_session(self->ssl);
2701 if (session == NULL) {
2702 Py_RETURN_NONE;
2703 }
2704#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002705 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002706 if (pysess == NULL) {
2707 SSL_SESSION_free(session);
2708 return NULL;
2709 }
2710
2711 assert(self->ctx);
2712 pysess->ctx = self->ctx;
2713 Py_INCREF(pysess->ctx);
2714 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002715 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002716 return (PyObject *)pysess;
2717}
2718
2719static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2720 void *closure)
2721 {
2722 PySSLSession *pysess;
2723#ifdef OPENSSL_VERSION_1_1
2724 SSL_SESSION *session;
2725#endif
2726 int result;
2727
2728 if (!PySSLSession_Check(value)) {
2729 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2730 return -1;
2731 }
2732 pysess = (PySSLSession *)value;
2733
2734 if (self->ctx->ctx != pysess->ctx->ctx) {
2735 PyErr_SetString(PyExc_ValueError,
2736 "Session refers to a different SSLContext.");
2737 return -1;
2738 }
2739 if (self->socket_type != PY_SSL_CLIENT) {
2740 PyErr_SetString(PyExc_ValueError,
2741 "Cannot set session for server-side SSLSocket.");
2742 return -1;
2743 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002744 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002745 PyErr_SetString(PyExc_ValueError,
2746 "Cannot set session after handshake.");
2747 return -1;
2748 }
2749#ifdef OPENSSL_VERSION_1_1
2750 /* duplicate session */
2751 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2752 return -1;
2753 }
2754 result = SSL_set_session(self->ssl, session);
2755 /* free duplicate, SSL_set_session() bumps ref count */
2756 SSL_SESSION_free(session);
2757#else
2758 result = SSL_set_session(self->ssl, pysess->session);
2759#endif
2760 if (result == 0) {
2761 _setSSLError(NULL, 0, __FILE__, __LINE__);
2762 return -1;
2763 }
2764 return 0;
2765}
2766
2767PyDoc_STRVAR(PySSL_set_session_doc,
2768"_setter_session(session)\n\
2769\
2770Get / set SSLSession.");
2771
2772static PyObject *
2773PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2774 if (SSL_session_reused(self->ssl)) {
2775 Py_RETURN_TRUE;
2776 } else {
2777 Py_RETURN_FALSE;
2778 }
2779}
2780
2781PyDoc_STRVAR(PySSL_get_session_reused_doc,
2782"Was the client session reused during handshake?");
2783
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002784static PyGetSetDef ssl_getsetlist[] = {
2785 {"context", (getter) PySSL_get_context,
2786 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002787 {"server_side", (getter) PySSL_get_server_side, NULL,
2788 PySSL_get_server_side_doc},
2789 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2790 PySSL_get_server_hostname_doc},
2791 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2792 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002793 {"session", (getter) PySSL_get_session,
2794 (setter) PySSL_set_session, PySSL_set_session_doc},
2795 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2796 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002797 {NULL}, /* sentinel */
2798};
2799
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002800static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002801 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2802 _SSL__SSLSOCKET_WRITE_METHODDEF
2803 _SSL__SSLSOCKET_READ_METHODDEF
2804 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002805 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2806 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002807 _SSL__SSLSOCKET_CIPHER_METHODDEF
2808 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2809 _SSL__SSLSOCKET_VERSION_METHODDEF
2810 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2811 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2812 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2813 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002814 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002815};
2816
Antoine Pitrou152efa22010-05-16 18:19:27 +00002817static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002818 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002819 "_ssl._SSLSocket", /*tp_name*/
2820 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002821 0, /*tp_itemsize*/
2822 /* methods */
2823 (destructor)PySSL_dealloc, /*tp_dealloc*/
2824 0, /*tp_print*/
2825 0, /*tp_getattr*/
2826 0, /*tp_setattr*/
2827 0, /*tp_reserved*/
2828 0, /*tp_repr*/
2829 0, /*tp_as_number*/
2830 0, /*tp_as_sequence*/
2831 0, /*tp_as_mapping*/
2832 0, /*tp_hash*/
2833 0, /*tp_call*/
2834 0, /*tp_str*/
2835 0, /*tp_getattro*/
2836 0, /*tp_setattro*/
2837 0, /*tp_as_buffer*/
2838 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2839 0, /*tp_doc*/
2840 0, /*tp_traverse*/
2841 0, /*tp_clear*/
2842 0, /*tp_richcompare*/
2843 0, /*tp_weaklistoffset*/
2844 0, /*tp_iter*/
2845 0, /*tp_iternext*/
2846 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002847 0, /*tp_members*/
2848 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002849};
2850
Antoine Pitrou152efa22010-05-16 18:19:27 +00002851
2852/*
2853 * _SSLContext objects
2854 */
2855
Christian Heimes5fe668c2016-09-12 00:01:11 +02002856static int
2857_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2858{
2859 int mode;
2860 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2861
2862 switch(n) {
2863 case PY_SSL_CERT_NONE:
2864 mode = SSL_VERIFY_NONE;
2865 break;
2866 case PY_SSL_CERT_OPTIONAL:
2867 mode = SSL_VERIFY_PEER;
2868 break;
2869 case PY_SSL_CERT_REQUIRED:
2870 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2871 break;
2872 default:
2873 PyErr_SetString(PyExc_ValueError,
2874 "invalid value for verify_mode");
2875 return -1;
2876 }
2877 /* keep current verify cb */
2878 verify_cb = SSL_CTX_get_verify_callback(ctx);
2879 SSL_CTX_set_verify(ctx, mode, verify_cb);
2880 return 0;
2881}
2882
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002883/*[clinic input]
2884@classmethod
2885_ssl._SSLContext.__new__
2886 protocol as proto_version: int
2887 /
2888[clinic start generated code]*/
2889
Antoine Pitrou152efa22010-05-16 18:19:27 +00002890static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002891_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2892/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002893{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002894 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002895 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002896 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002897 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002898 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002899#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002900 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002901#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002902
Antoine Pitrou152efa22010-05-16 18:19:27 +00002903 PySSL_BEGIN_ALLOW_THREADS
2904 if (proto_version == PY_SSL_VERSION_TLS1)
2905 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002906#if HAVE_TLSv1_2
2907 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2908 ctx = SSL_CTX_new(TLSv1_1_method());
2909 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2910 ctx = SSL_CTX_new(TLSv1_2_method());
2911#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002912#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002913 else if (proto_version == PY_SSL_VERSION_SSL3)
2914 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002915#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002916#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002917 else if (proto_version == PY_SSL_VERSION_SSL2)
2918 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002919#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002920 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002921 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002922 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2923 ctx = SSL_CTX_new(TLS_client_method());
2924 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2925 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002926 else
2927 proto_version = -1;
2928 PySSL_END_ALLOW_THREADS
2929
2930 if (proto_version == -1) {
2931 PyErr_SetString(PyExc_ValueError,
2932 "invalid protocol version");
2933 return NULL;
2934 }
2935 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002936 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002937 return NULL;
2938 }
2939
2940 assert(type != NULL && type->tp_alloc != NULL);
2941 self = (PySSLContext *) type->tp_alloc(type, 0);
2942 if (self == NULL) {
2943 SSL_CTX_free(ctx);
2944 return NULL;
2945 }
2946 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002947 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002948 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002949#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002950 self->npn_protocols = NULL;
2951#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002952#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002953 self->alpn_protocols = NULL;
2954#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002955#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002956 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002957#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002958 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002959 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2960 self->check_hostname = 1;
2961 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2962 Py_DECREF(self);
2963 return NULL;
2964 }
2965 } else {
2966 self->check_hostname = 0;
2967 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2968 Py_DECREF(self);
2969 return NULL;
2970 }
2971 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002972 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002973 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2974 if (proto_version != PY_SSL_VERSION_SSL2)
2975 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002976 if (proto_version != PY_SSL_VERSION_SSL3)
2977 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002978 /* Minimal security flags for server and client side context.
2979 * Client sockets ignore server-side parameters. */
2980#ifdef SSL_OP_NO_COMPRESSION
2981 options |= SSL_OP_NO_COMPRESSION;
2982#endif
2983#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2984 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2985#endif
2986#ifdef SSL_OP_SINGLE_DH_USE
2987 options |= SSL_OP_SINGLE_DH_USE;
2988#endif
2989#ifdef SSL_OP_SINGLE_ECDH_USE
2990 options |= SSL_OP_SINGLE_ECDH_USE;
2991#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002992 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002993
Semen Zhydenko1295e112017-10-15 21:28:31 +02002994 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002995 * It's far from perfect but gives users a better head start. */
2996 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002997#if PY_SSL_DEFAULT_CIPHERS == 2
2998 /* stick to OpenSSL's default settings */
2999 result = 1;
3000#else
3001 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3002#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003003 } else {
3004 /* SSLv2 needs MD5 */
3005 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3006 }
3007 if (result == 0) {
3008 Py_DECREF(self);
3009 ERR_clear_error();
3010 PyErr_SetString(PySSLErrorObject,
3011 "No cipher can be selected.");
3012 return NULL;
3013 }
3014
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003015#if defined(SSL_MODE_RELEASE_BUFFERS)
3016 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3017 usage for no cost at all. However, don't do this for OpenSSL versions
3018 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3019 2014-0198. I can't find exactly which beta fixed this CVE, so be
3020 conservative and assume it wasn't fixed until release. We do this check
3021 at runtime to avoid problems from the dynamic linker.
3022 See #25672 for more on this. */
3023 libver = SSLeay();
3024 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3025 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3026 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3027 }
3028#endif
3029
3030
Donald Stufft8ae264c2017-03-02 11:45:29 -05003031#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003032 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3033 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003034 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3035 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003036#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003037 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3038#else
3039 {
3040 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3041 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3042 EC_KEY_free(key);
3043 }
3044#endif
3045#endif
3046
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003047#define SID_CTX "Python"
3048 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3049 sizeof(SID_CTX));
3050#undef SID_CTX
3051
Christian Heimes61d478c2018-01-27 15:51:38 +01003052 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003053#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003054 /* Improve trust chain building when cross-signed intermediate
3055 certificates are present. See https://bugs.python.org/issue23476. */
3056 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003057#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003058 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003059
Antoine Pitrou152efa22010-05-16 18:19:27 +00003060 return (PyObject *)self;
3061}
3062
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003063static int
3064context_traverse(PySSLContext *self, visitproc visit, void *arg)
3065{
3066#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003067 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003068#endif
3069 return 0;
3070}
3071
3072static int
3073context_clear(PySSLContext *self)
3074{
3075#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003076 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003077#endif
3078 return 0;
3079}
3080
Antoine Pitrou152efa22010-05-16 18:19:27 +00003081static void
3082context_dealloc(PySSLContext *self)
3083{
INADA Naokia6296d32017-08-24 14:55:17 +09003084 /* bpo-31095: UnTrack is needed before calling any callbacks */
3085 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003086 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003088#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003089 PyMem_FREE(self->npn_protocols);
3090#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003091#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003092 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003093#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003094 Py_TYPE(self)->tp_free(self);
3095}
3096
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003097/*[clinic input]
3098_ssl._SSLContext.set_ciphers
3099 cipherlist: str
3100 /
3101[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003102
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003103static PyObject *
3104_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3105/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3106{
3107 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003108 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003109 /* Clearing the error queue is necessary on some OpenSSL versions,
3110 otherwise the error will be reported again when another SSL call
3111 is done. */
3112 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003113 PyErr_SetString(PySSLErrorObject,
3114 "No cipher can be selected.");
3115 return NULL;
3116 }
3117 Py_RETURN_NONE;
3118}
3119
Christian Heimes25bfcd52016-09-06 00:04:45 +02003120#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3121/*[clinic input]
3122_ssl._SSLContext.get_ciphers
3123[clinic start generated code]*/
3124
3125static PyObject *
3126_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3127/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3128{
3129 SSL *ssl = NULL;
3130 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003131 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003132 int i=0;
3133 PyObject *result = NULL, *dct;
3134
3135 ssl = SSL_new(self->ctx);
3136 if (ssl == NULL) {
3137 _setSSLError(NULL, 0, __FILE__, __LINE__);
3138 goto exit;
3139 }
3140 sk = SSL_get_ciphers(ssl);
3141
3142 result = PyList_New(sk_SSL_CIPHER_num(sk));
3143 if (result == NULL) {
3144 goto exit;
3145 }
3146
3147 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3148 cipher = sk_SSL_CIPHER_value(sk, i);
3149 dct = cipher_to_dict(cipher);
3150 if (dct == NULL) {
3151 Py_CLEAR(result);
3152 goto exit;
3153 }
3154 PyList_SET_ITEM(result, i, dct);
3155 }
3156
3157 exit:
3158 if (ssl != NULL)
3159 SSL_free(ssl);
3160 return result;
3161
3162}
3163#endif
3164
3165
Christian Heimes29eab552018-02-25 12:31:33 +01003166#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003167static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003168do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3169 const unsigned char *server_protocols, unsigned int server_protocols_len,
3170 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003171{
Benjamin Peterson88615022015-01-23 17:30:26 -05003172 int ret;
3173 if (client_protocols == NULL) {
3174 client_protocols = (unsigned char *)"";
3175 client_protocols_len = 0;
3176 }
3177 if (server_protocols == NULL) {
3178 server_protocols = (unsigned char *)"";
3179 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003180 }
3181
Benjamin Peterson88615022015-01-23 17:30:26 -05003182 ret = SSL_select_next_proto(out, outlen,
3183 server_protocols, server_protocols_len,
3184 client_protocols, client_protocols_len);
3185 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3186 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003187
3188 return SSL_TLSEXT_ERR_OK;
3189}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003190#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003191
Christian Heimes29eab552018-02-25 12:31:33 +01003192#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003193/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3194static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003195_advertiseNPN_cb(SSL *s,
3196 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003197 void *args)
3198{
3199 PySSLContext *ssl_ctx = (PySSLContext *) args;
3200
3201 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003202 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003203 *len = 0;
3204 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003205 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003206 *len = ssl_ctx->npn_protocols_len;
3207 }
3208
3209 return SSL_TLSEXT_ERR_OK;
3210}
3211/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3212static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003213_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003214 unsigned char **out, unsigned char *outlen,
3215 const unsigned char *server, unsigned int server_len,
3216 void *args)
3217{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003218 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003219 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003220 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003221}
3222#endif
3223
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003224/*[clinic input]
3225_ssl._SSLContext._set_npn_protocols
3226 protos: Py_buffer
3227 /
3228[clinic start generated code]*/
3229
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003230static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003231_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3232 Py_buffer *protos)
3233/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003234{
Christian Heimes29eab552018-02-25 12:31:33 +01003235#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003236 PyMem_Free(self->npn_protocols);
3237 self->npn_protocols = PyMem_Malloc(protos->len);
3238 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003239 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003240 memcpy(self->npn_protocols, protos->buf, protos->len);
3241 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003242
3243 /* set both server and client callbacks, because the context can
3244 * be used to create both types of sockets */
3245 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3246 _advertiseNPN_cb,
3247 self);
3248 SSL_CTX_set_next_proto_select_cb(self->ctx,
3249 _selectNPN_cb,
3250 self);
3251
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003252 Py_RETURN_NONE;
3253#else
3254 PyErr_SetString(PyExc_NotImplementedError,
3255 "The NPN extension requires OpenSSL 1.0.1 or later.");
3256 return NULL;
3257#endif
3258}
3259
Christian Heimes29eab552018-02-25 12:31:33 +01003260#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003261static int
3262_selectALPN_cb(SSL *s,
3263 const unsigned char **out, unsigned char *outlen,
3264 const unsigned char *client_protocols, unsigned int client_protocols_len,
3265 void *args)
3266{
3267 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003268 return do_protocol_selection(1, (unsigned char **)out, outlen,
3269 ctx->alpn_protocols, ctx->alpn_protocols_len,
3270 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003271}
3272#endif
3273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003274/*[clinic input]
3275_ssl._SSLContext._set_alpn_protocols
3276 protos: Py_buffer
3277 /
3278[clinic start generated code]*/
3279
Benjamin Petersoncca27322015-01-23 16:35:37 -05003280static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003281_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3282 Py_buffer *protos)
3283/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003284{
Christian Heimes29eab552018-02-25 12:31:33 +01003285#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003286 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003287 PyErr_Format(PyExc_OverflowError,
3288 "protocols longer than %d bytes", UINT_MAX);
3289 return NULL;
3290 }
3291
Benjamin Petersoncca27322015-01-23 16:35:37 -05003292 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003293 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003294 if (!self->alpn_protocols)
3295 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003296 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003297 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003298
3299 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3300 return PyErr_NoMemory();
3301 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3302
Benjamin Petersoncca27322015-01-23 16:35:37 -05003303 Py_RETURN_NONE;
3304#else
3305 PyErr_SetString(PyExc_NotImplementedError,
3306 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3307 return NULL;
3308#endif
3309}
3310
Antoine Pitrou152efa22010-05-16 18:19:27 +00003311static PyObject *
3312get_verify_mode(PySSLContext *self, void *c)
3313{
3314 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3315 case SSL_VERIFY_NONE:
3316 return PyLong_FromLong(PY_SSL_CERT_NONE);
3317 case SSL_VERIFY_PEER:
3318 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3319 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3320 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3321 }
3322 PyErr_SetString(PySSLErrorObject,
3323 "invalid return value from SSL_CTX_get_verify_mode");
3324 return NULL;
3325}
3326
3327static int
3328set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3329{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003330 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003331 if (!PyArg_Parse(arg, "i", &n))
3332 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003333 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003334 PyErr_SetString(PyExc_ValueError,
3335 "Cannot set verify_mode to CERT_NONE when "
3336 "check_hostname is enabled.");
3337 return -1;
3338 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003339 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003340}
3341
3342static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003343get_verify_flags(PySSLContext *self, void *c)
3344{
Christian Heimes598894f2016-09-05 23:19:05 +02003345 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003346 unsigned long flags;
3347
Christian Heimes61d478c2018-01-27 15:51:38 +01003348 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003349 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003350 return PyLong_FromUnsignedLong(flags);
3351}
3352
3353static int
3354set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3355{
Christian Heimes598894f2016-09-05 23:19:05 +02003356 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003357 unsigned long new_flags, flags, set, clear;
3358
3359 if (!PyArg_Parse(arg, "k", &new_flags))
3360 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003361 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003362 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003363 clear = flags & ~new_flags;
3364 set = ~flags & new_flags;
3365 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003366 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003367 _setSSLError(NULL, 0, __FILE__, __LINE__);
3368 return -1;
3369 }
3370 }
3371 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003372 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003373 _setSSLError(NULL, 0, __FILE__, __LINE__);
3374 return -1;
3375 }
3376 }
3377 return 0;
3378}
3379
Christian Heimes698dde12018-02-27 11:54:43 +01003380/* Getter and setter for protocol version */
3381#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3382
3383
3384static int
3385set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3386{
3387 long v;
3388 int result;
3389
3390 if (!PyArg_Parse(arg, "l", &v))
3391 return -1;
3392 if (v > INT_MAX) {
3393 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3394 return -1;
3395 }
3396
3397 switch(self->protocol) {
3398 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3399 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3400 case PY_SSL_VERSION_TLS:
3401 break;
3402 default:
3403 PyErr_SetString(
3404 PyExc_ValueError,
3405 "The context's protocol doesn't support modification of "
3406 "highest and lowest version."
3407 );
3408 return -1;
3409 }
3410
3411 if (what == 0) {
3412 switch(v) {
3413 case PY_PROTO_MINIMUM_SUPPORTED:
3414 v = 0;
3415 break;
3416 case PY_PROTO_MAXIMUM_SUPPORTED:
3417 /* Emulate max for set_min_proto_version */
3418 v = PY_PROTO_MAXIMUM_AVAILABLE;
3419 break;
3420 default:
3421 break;
3422 }
3423 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3424 }
3425 else {
3426 switch(v) {
3427 case PY_PROTO_MAXIMUM_SUPPORTED:
3428 v = 0;
3429 break;
3430 case PY_PROTO_MINIMUM_SUPPORTED:
3431 /* Emulate max for set_min_proto_version */
3432 v = PY_PROTO_MINIMUM_AVAILABLE;
3433 break;
3434 default:
3435 break;
3436 }
3437 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3438 }
3439 if (result == 0) {
3440 PyErr_Format(PyExc_ValueError,
3441 "Unsupported protocol version 0x%x", v);
3442 return -1;
3443 }
3444 return 0;
3445}
3446
3447static PyObject *
3448get_minimum_version(PySSLContext *self, void *c)
3449{
3450 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3451 if (v == 0) {
3452 v = PY_PROTO_MINIMUM_SUPPORTED;
3453 }
3454 return PyLong_FromLong(v);
3455}
3456
3457static int
3458set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3459{
3460 return set_min_max_proto_version(self, arg, 0);
3461}
3462
3463static PyObject *
3464get_maximum_version(PySSLContext *self, void *c)
3465{
3466 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3467 if (v == 0) {
3468 v = PY_PROTO_MAXIMUM_SUPPORTED;
3469 }
3470 return PyLong_FromLong(v);
3471}
3472
3473static int
3474set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3475{
3476 return set_min_max_proto_version(self, arg, 1);
3477}
3478#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3479
Christian Heimes22587792013-11-21 23:56:13 +01003480static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003481get_options(PySSLContext *self, void *c)
3482{
3483 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3484}
3485
3486static int
3487set_options(PySSLContext *self, PyObject *arg, void *c)
3488{
3489 long new_opts, opts, set, clear;
3490 if (!PyArg_Parse(arg, "l", &new_opts))
3491 return -1;
3492 opts = SSL_CTX_get_options(self->ctx);
3493 clear = opts & ~new_opts;
3494 set = ~opts & new_opts;
3495 if (clear) {
3496#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3497 SSL_CTX_clear_options(self->ctx, clear);
3498#else
3499 PyErr_SetString(PyExc_ValueError,
3500 "can't clear options before OpenSSL 0.9.8m");
3501 return -1;
3502#endif
3503 }
3504 if (set)
3505 SSL_CTX_set_options(self->ctx, set);
3506 return 0;
3507}
3508
Christian Heimes1aa9a752013-12-02 02:41:19 +01003509static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003510get_host_flags(PySSLContext *self, void *c)
3511{
3512 return PyLong_FromUnsignedLong(self->hostflags);
3513}
3514
3515static int
3516set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3517{
3518 X509_VERIFY_PARAM *param;
3519 unsigned int new_flags = 0;
3520
3521 if (!PyArg_Parse(arg, "I", &new_flags))
3522 return -1;
3523
3524 param = SSL_CTX_get0_param(self->ctx);
3525 self->hostflags = new_flags;
3526 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3527 return 0;
3528}
3529
3530static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003531get_check_hostname(PySSLContext *self, void *c)
3532{
3533 return PyBool_FromLong(self->check_hostname);
3534}
3535
3536static int
3537set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3538{
3539 int check_hostname;
3540 if (!PyArg_Parse(arg, "p", &check_hostname))
3541 return -1;
3542 if (check_hostname &&
3543 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003544 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3545 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3546 return -1;
3547 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003548 }
3549 self->check_hostname = check_hostname;
3550 return 0;
3551}
3552
Christian Heimes11a14932018-02-24 02:35:08 +01003553static PyObject *
3554get_protocol(PySSLContext *self, void *c) {
3555 return PyLong_FromLong(self->protocol);
3556}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003557
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003558typedef struct {
3559 PyThreadState *thread_state;
3560 PyObject *callable;
3561 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003562 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003563 int error;
3564} _PySSLPasswordInfo;
3565
3566static int
3567_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3568 const char *bad_type_error)
3569{
3570 /* Set the password and size fields of a _PySSLPasswordInfo struct
3571 from a unicode, bytes, or byte array object.
3572 The password field will be dynamically allocated and must be freed
3573 by the caller */
3574 PyObject *password_bytes = NULL;
3575 const char *data = NULL;
3576 Py_ssize_t size;
3577
3578 if (PyUnicode_Check(password)) {
3579 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3580 if (!password_bytes) {
3581 goto error;
3582 }
3583 data = PyBytes_AS_STRING(password_bytes);
3584 size = PyBytes_GET_SIZE(password_bytes);
3585 } else if (PyBytes_Check(password)) {
3586 data = PyBytes_AS_STRING(password);
3587 size = PyBytes_GET_SIZE(password);
3588 } else if (PyByteArray_Check(password)) {
3589 data = PyByteArray_AS_STRING(password);
3590 size = PyByteArray_GET_SIZE(password);
3591 } else {
3592 PyErr_SetString(PyExc_TypeError, bad_type_error);
3593 goto error;
3594 }
3595
Victor Stinner9ee02032013-06-23 15:08:23 +02003596 if (size > (Py_ssize_t)INT_MAX) {
3597 PyErr_Format(PyExc_ValueError,
3598 "password cannot be longer than %d bytes", INT_MAX);
3599 goto error;
3600 }
3601
Victor Stinner11ebff22013-07-07 17:07:52 +02003602 PyMem_Free(pw_info->password);
3603 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003604 if (!pw_info->password) {
3605 PyErr_SetString(PyExc_MemoryError,
3606 "unable to allocate password buffer");
3607 goto error;
3608 }
3609 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003610 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003611
3612 Py_XDECREF(password_bytes);
3613 return 1;
3614
3615error:
3616 Py_XDECREF(password_bytes);
3617 return 0;
3618}
3619
3620static int
3621_password_callback(char *buf, int size, int rwflag, void *userdata)
3622{
3623 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3624 PyObject *fn_ret = NULL;
3625
3626 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3627
3628 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003629 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003630 if (!fn_ret) {
3631 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3632 core python API, so we could use it to add a frame here */
3633 goto error;
3634 }
3635
3636 if (!_pwinfo_set(pw_info, fn_ret,
3637 "password callback must return a string")) {
3638 goto error;
3639 }
3640 Py_CLEAR(fn_ret);
3641 }
3642
3643 if (pw_info->size > size) {
3644 PyErr_Format(PyExc_ValueError,
3645 "password cannot be longer than %d bytes", size);
3646 goto error;
3647 }
3648
3649 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3650 memcpy(buf, pw_info->password, pw_info->size);
3651 return pw_info->size;
3652
3653error:
3654 Py_XDECREF(fn_ret);
3655 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3656 pw_info->error = 1;
3657 return -1;
3658}
3659
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003660/*[clinic input]
3661_ssl._SSLContext.load_cert_chain
3662 certfile: object
3663 keyfile: object = NULL
3664 password: object = NULL
3665
3666[clinic start generated code]*/
3667
Antoine Pitroub5218772010-05-21 09:56:06 +00003668static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003669_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3670 PyObject *keyfile, PyObject *password)
3671/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003672{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003673 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003674 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3675 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003676 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003677 int r;
3678
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003679 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003680 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003681 if (keyfile == Py_None)
3682 keyfile = NULL;
3683 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3684 PyErr_SetString(PyExc_TypeError,
3685 "certfile should be a valid filesystem path");
3686 return NULL;
3687 }
3688 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3689 PyErr_SetString(PyExc_TypeError,
3690 "keyfile should be a valid filesystem path");
3691 goto error;
3692 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003693 if (password && password != Py_None) {
3694 if (PyCallable_Check(password)) {
3695 pw_info.callable = password;
3696 } else if (!_pwinfo_set(&pw_info, password,
3697 "password should be a string or callable")) {
3698 goto error;
3699 }
3700 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3701 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3702 }
3703 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003704 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3705 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003706 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003707 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003708 if (pw_info.error) {
3709 ERR_clear_error();
3710 /* the password callback has already set the error information */
3711 }
3712 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003713 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003714 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003715 }
3716 else {
3717 _setSSLError(NULL, 0, __FILE__, __LINE__);
3718 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003719 goto error;
3720 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003721 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003722 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003723 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3724 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003725 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3726 Py_CLEAR(keyfile_bytes);
3727 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003728 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003729 if (pw_info.error) {
3730 ERR_clear_error();
3731 /* the password callback has already set the error information */
3732 }
3733 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003734 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003735 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003736 }
3737 else {
3738 _setSSLError(NULL, 0, __FILE__, __LINE__);
3739 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003740 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003741 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003742 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003743 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003744 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003745 if (r != 1) {
3746 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003747 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003748 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003749 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3750 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003751 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003752 Py_RETURN_NONE;
3753
3754error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003755 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3756 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003757 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003758 Py_XDECREF(keyfile_bytes);
3759 Py_XDECREF(certfile_bytes);
3760 return NULL;
3761}
3762
Christian Heimesefff7062013-11-21 03:35:02 +01003763/* internal helper function, returns -1 on error
3764 */
3765static int
3766_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3767 int filetype)
3768{
3769 BIO *biobuf = NULL;
3770 X509_STORE *store;
3771 int retval = 0, err, loaded = 0;
3772
3773 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3774
3775 if (len <= 0) {
3776 PyErr_SetString(PyExc_ValueError,
3777 "Empty certificate data");
3778 return -1;
3779 } else if (len > INT_MAX) {
3780 PyErr_SetString(PyExc_OverflowError,
3781 "Certificate data is too long.");
3782 return -1;
3783 }
3784
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003785 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003786 if (biobuf == NULL) {
3787 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3788 return -1;
3789 }
3790
3791 store = SSL_CTX_get_cert_store(self->ctx);
3792 assert(store != NULL);
3793
3794 while (1) {
3795 X509 *cert = NULL;
3796 int r;
3797
3798 if (filetype == SSL_FILETYPE_ASN1) {
3799 cert = d2i_X509_bio(biobuf, NULL);
3800 } else {
3801 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003802 SSL_CTX_get_default_passwd_cb(self->ctx),
3803 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3804 );
Christian Heimesefff7062013-11-21 03:35:02 +01003805 }
3806 if (cert == NULL) {
3807 break;
3808 }
3809 r = X509_STORE_add_cert(store, cert);
3810 X509_free(cert);
3811 if (!r) {
3812 err = ERR_peek_last_error();
3813 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3814 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3815 /* cert already in hash table, not an error */
3816 ERR_clear_error();
3817 } else {
3818 break;
3819 }
3820 }
3821 loaded++;
3822 }
3823
3824 err = ERR_peek_last_error();
3825 if ((filetype == SSL_FILETYPE_ASN1) &&
3826 (loaded > 0) &&
3827 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3828 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3829 /* EOF ASN1 file, not an error */
3830 ERR_clear_error();
3831 retval = 0;
3832 } else if ((filetype == SSL_FILETYPE_PEM) &&
3833 (loaded > 0) &&
3834 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3835 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3836 /* EOF PEM file, not an error */
3837 ERR_clear_error();
3838 retval = 0;
3839 } else {
3840 _setSSLError(NULL, 0, __FILE__, __LINE__);
3841 retval = -1;
3842 }
3843
3844 BIO_free(biobuf);
3845 return retval;
3846}
3847
3848
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003849/*[clinic input]
3850_ssl._SSLContext.load_verify_locations
3851 cafile: object = NULL
3852 capath: object = NULL
3853 cadata: object = NULL
3854
3855[clinic start generated code]*/
3856
Antoine Pitrou152efa22010-05-16 18:19:27 +00003857static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003858_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3859 PyObject *cafile,
3860 PyObject *capath,
3861 PyObject *cadata)
3862/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003863{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003864 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3865 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003866 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003867
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003868 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003869 if (cafile == Py_None)
3870 cafile = NULL;
3871 if (capath == Py_None)
3872 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003873 if (cadata == Py_None)
3874 cadata = NULL;
3875
3876 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003877 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003878 "cafile, capath and cadata cannot be all omitted");
3879 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003880 }
3881 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3882 PyErr_SetString(PyExc_TypeError,
3883 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003884 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003885 }
3886 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003887 PyErr_SetString(PyExc_TypeError,
3888 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003889 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003890 }
Christian Heimesefff7062013-11-21 03:35:02 +01003891
3892 /* validata cadata type and load cadata */
3893 if (cadata) {
3894 Py_buffer buf;
3895 PyObject *cadata_ascii = NULL;
3896
3897 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3898 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3899 PyBuffer_Release(&buf);
3900 PyErr_SetString(PyExc_TypeError,
3901 "cadata should be a contiguous buffer with "
3902 "a single dimension");
3903 goto error;
3904 }
3905 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3906 PyBuffer_Release(&buf);
3907 if (r == -1) {
3908 goto error;
3909 }
3910 } else {
3911 PyErr_Clear();
3912 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3913 if (cadata_ascii == NULL) {
3914 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003915 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003916 "bytes-like object");
3917 goto error;
3918 }
3919 r = _add_ca_certs(self,
3920 PyBytes_AS_STRING(cadata_ascii),
3921 PyBytes_GET_SIZE(cadata_ascii),
3922 SSL_FILETYPE_PEM);
3923 Py_DECREF(cadata_ascii);
3924 if (r == -1) {
3925 goto error;
3926 }
3927 }
3928 }
3929
3930 /* load cafile or capath */
3931 if (cafile || capath) {
3932 if (cafile)
3933 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3934 if (capath)
3935 capath_buf = PyBytes_AS_STRING(capath_bytes);
3936 PySSL_BEGIN_ALLOW_THREADS
3937 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3938 PySSL_END_ALLOW_THREADS
3939 if (r != 1) {
3940 ok = 0;
3941 if (errno != 0) {
3942 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003943 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003944 }
3945 else {
3946 _setSSLError(NULL, 0, __FILE__, __LINE__);
3947 }
3948 goto error;
3949 }
3950 }
3951 goto end;
3952
3953 error:
3954 ok = 0;
3955 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003956 Py_XDECREF(cafile_bytes);
3957 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003958 if (ok) {
3959 Py_RETURN_NONE;
3960 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003961 return NULL;
3962 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003963}
3964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003965/*[clinic input]
3966_ssl._SSLContext.load_dh_params
3967 path as filepath: object
3968 /
3969
3970[clinic start generated code]*/
3971
Antoine Pitrou152efa22010-05-16 18:19:27 +00003972static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003973_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3974/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003975{
3976 FILE *f;
3977 DH *dh;
3978
Victor Stinnerdaf45552013-08-28 00:53:59 +02003979 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003980 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003981 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003982
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003983 errno = 0;
3984 PySSL_BEGIN_ALLOW_THREADS
3985 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003986 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003987 PySSL_END_ALLOW_THREADS
3988 if (dh == NULL) {
3989 if (errno != 0) {
3990 ERR_clear_error();
3991 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3992 }
3993 else {
3994 _setSSLError(NULL, 0, __FILE__, __LINE__);
3995 }
3996 return NULL;
3997 }
3998 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3999 _setSSLError(NULL, 0, __FILE__, __LINE__);
4000 DH_free(dh);
4001 Py_RETURN_NONE;
4002}
4003
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004004/*[clinic input]
4005_ssl._SSLContext._wrap_socket
4006 sock: object(subclass_of="PySocketModule.Sock_Type")
4007 server_side: int
4008 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004009 *
4010 owner: object = None
4011 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004012
4013[clinic start generated code]*/
4014
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004015static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004016_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004017 int server_side, PyObject *hostname_obj,
4018 PyObject *owner, PyObject *session)
4019/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020{
Antoine Pitroud5323212010-10-22 18:19:07 +00004021 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004022 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023
Antoine Pitroud5323212010-10-22 18:19:07 +00004024 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004025 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004026 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004027 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004028 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004029 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004030
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004031 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4032 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004033 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004034 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004035 if (hostname != NULL)
4036 PyMem_Free(hostname);
4037 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004038}
4039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004040/*[clinic input]
4041_ssl._SSLContext._wrap_bio
4042 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4043 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4044 server_side: int
4045 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004046 *
4047 owner: object = None
4048 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004049
4050[clinic start generated code]*/
4051
Antoine Pitroub0182c82010-10-12 20:09:02 +00004052static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004053_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4054 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004055 PyObject *hostname_obj, PyObject *owner,
4056 PyObject *session)
4057/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004058{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004059 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004060 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004061
4062 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004063 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004064 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004065 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004066 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067 }
4068
4069 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004070 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004071 incoming, outgoing);
4072
4073 PyMem_Free(hostname);
4074 return res;
4075}
4076
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004077/*[clinic input]
4078_ssl._SSLContext.session_stats
4079[clinic start generated code]*/
4080
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004081static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004082_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4083/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004084{
4085 int r;
4086 PyObject *value, *stats = PyDict_New();
4087 if (!stats)
4088 return NULL;
4089
4090#define ADD_STATS(SSL_NAME, KEY_NAME) \
4091 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4092 if (value == NULL) \
4093 goto error; \
4094 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4095 Py_DECREF(value); \
4096 if (r < 0) \
4097 goto error;
4098
4099 ADD_STATS(number, "number");
4100 ADD_STATS(connect, "connect");
4101 ADD_STATS(connect_good, "connect_good");
4102 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4103 ADD_STATS(accept, "accept");
4104 ADD_STATS(accept_good, "accept_good");
4105 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4106 ADD_STATS(accept, "accept");
4107 ADD_STATS(hits, "hits");
4108 ADD_STATS(misses, "misses");
4109 ADD_STATS(timeouts, "timeouts");
4110 ADD_STATS(cache_full, "cache_full");
4111
4112#undef ADD_STATS
4113
4114 return stats;
4115
4116error:
4117 Py_DECREF(stats);
4118 return NULL;
4119}
4120
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004121/*[clinic input]
4122_ssl._SSLContext.set_default_verify_paths
4123[clinic start generated code]*/
4124
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004125static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004126_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4127/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004128{
4129 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4130 _setSSLError(NULL, 0, __FILE__, __LINE__);
4131 return NULL;
4132 }
4133 Py_RETURN_NONE;
4134}
4135
Antoine Pitrou501da612011-12-21 09:27:41 +01004136#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004137/*[clinic input]
4138_ssl._SSLContext.set_ecdh_curve
4139 name: object
4140 /
4141
4142[clinic start generated code]*/
4143
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004144static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004145_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4146/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004147{
4148 PyObject *name_bytes;
4149 int nid;
4150 EC_KEY *key;
4151
4152 if (!PyUnicode_FSConverter(name, &name_bytes))
4153 return NULL;
4154 assert(PyBytes_Check(name_bytes));
4155 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4156 Py_DECREF(name_bytes);
4157 if (nid == 0) {
4158 PyErr_Format(PyExc_ValueError,
4159 "unknown elliptic curve name %R", name);
4160 return NULL;
4161 }
4162 key = EC_KEY_new_by_curve_name(nid);
4163 if (key == NULL) {
4164 _setSSLError(NULL, 0, __FILE__, __LINE__);
4165 return NULL;
4166 }
4167 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4168 EC_KEY_free(key);
4169 Py_RETURN_NONE;
4170}
Antoine Pitrou501da612011-12-21 09:27:41 +01004171#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004172
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004173#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004174static int
4175_servername_callback(SSL *s, int *al, void *args)
4176{
4177 int ret;
4178 PySSLContext *ssl_ctx = (PySSLContext *) args;
4179 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004180 PyObject *result;
4181 /* The high-level ssl.SSLSocket object */
4182 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004183 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004184 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004185
Christian Heimes11a14932018-02-24 02:35:08 +01004186 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004187 /* remove race condition in this the call back while if removing the
4188 * callback is in progress */
4189 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004190 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004191 }
4192
4193 ssl = SSL_get_app_data(s);
4194 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004196 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004197 * SSL connection and that has a .context attribute that can be changed to
4198 * identify the requested hostname. Since the official API is the Python
4199 * level API we want to pass the callback a Python level object rather than
4200 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4201 * SSLObject) that will be passed. Otherwise if there's a socket then that
4202 * will be passed. If both do not exist only then the C-level object is
4203 * passed. */
4204 if (ssl->owner)
4205 ssl_socket = PyWeakref_GetObject(ssl->owner);
4206 else if (ssl->Socket)
4207 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4208 else
4209 ssl_socket = (PyObject *) ssl;
4210
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004211 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004212 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004213 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004214
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004215 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004216 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004217 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004218 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004219 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004220 PyObject *servername_bytes;
4221 PyObject *servername_str;
4222
4223 servername_bytes = PyBytes_FromString(servername);
4224 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004225 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4226 goto error;
4227 }
Christian Heimes11a14932018-02-24 02:35:08 +01004228 /* server_hostname was encoded to an A-label by our caller; put it
4229 * back into a str object, but still as an A-label (bpo-28414)
4230 */
4231 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4232 Py_DECREF(servername_bytes);
4233 if (servername_str == NULL) {
4234 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004235 goto error;
4236 }
Christian Heimes11a14932018-02-24 02:35:08 +01004237 result = PyObject_CallFunctionObjArgs(
4238 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4239 ssl_ctx, NULL);
4240 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004241 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004242 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004243
4244 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004245 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004246 *al = SSL_AD_HANDSHAKE_FAILURE;
4247 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4248 }
4249 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004250 /* Result may be None, a SSLContext or an integer
4251 * None and SSLContext are OK, integer or other values are an error.
4252 */
4253 if (result == Py_None) {
4254 ret = SSL_TLSEXT_ERR_OK;
4255 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004256 *al = (int) PyLong_AsLong(result);
4257 if (PyErr_Occurred()) {
4258 PyErr_WriteUnraisable(result);
4259 *al = SSL_AD_INTERNAL_ERROR;
4260 }
4261 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4262 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004263 Py_DECREF(result);
4264 }
4265
4266 PyGILState_Release(gstate);
4267 return ret;
4268
4269error:
4270 Py_DECREF(ssl_socket);
4271 *al = SSL_AD_INTERNAL_ERROR;
4272 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4273 PyGILState_Release(gstate);
4274 return ret;
4275}
Antoine Pitroua5963382013-03-30 16:39:00 +01004276#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004277
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004278static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004279get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004280{
Christian Heimes11a14932018-02-24 02:35:08 +01004281 PyObject *cb = self->set_sni_cb;
4282 if (cb == NULL) {
4283 Py_RETURN_NONE;
4284 }
4285 Py_INCREF(cb);
4286 return cb;
4287}
4288
4289static int
4290set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4291{
4292 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4293 PyErr_SetString(PyExc_ValueError,
4294 "sni_callback cannot be set on TLS_CLIENT context");
4295 return -1;
4296 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004297#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004298 Py_CLEAR(self->set_sni_cb);
4299 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004300 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4301 }
4302 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004303 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004304 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4305 PyErr_SetString(PyExc_TypeError,
4306 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004307 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004308 }
Christian Heimes11a14932018-02-24 02:35:08 +01004309 Py_INCREF(arg);
4310 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004311 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4312 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4313 }
Christian Heimes11a14932018-02-24 02:35:08 +01004314 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004315#else
4316 PyErr_SetString(PyExc_NotImplementedError,
4317 "The TLS extension servername callback, "
4318 "SSL_CTX_set_tlsext_servername_callback, "
4319 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004320 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004321#endif
4322}
4323
Christian Heimes11a14932018-02-24 02:35:08 +01004324PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4325"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4326\n\
4327If the argument is None then the callback is disabled. The method is called\n\
4328with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4329See RFC 6066 for details of the SNI extension.");
4330
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004331/*[clinic input]
4332_ssl._SSLContext.cert_store_stats
4333
4334Returns quantities of loaded X.509 certificates.
4335
4336X.509 certificates with a CA extension and certificate revocation lists
4337inside the context's cert store.
4338
4339NOTE: Certificates in a capath directory aren't loaded unless they have
4340been used at least once.
4341[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004342
4343static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004344_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4345/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004346{
4347 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004348 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004349 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004350 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004351
4352 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004353 objs = X509_STORE_get0_objects(store);
4354 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4355 obj = sk_X509_OBJECT_value(objs, i);
4356 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004357 case X509_LU_X509:
4358 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004359 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004360 ca++;
4361 }
4362 break;
4363 case X509_LU_CRL:
4364 crl++;
4365 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004366 default:
4367 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4368 * As far as I can tell they are internal states and never
4369 * stored in a cert store */
4370 break;
4371 }
4372 }
4373 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4374 "x509_ca", ca);
4375}
4376
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004377/*[clinic input]
4378_ssl._SSLContext.get_ca_certs
4379 binary_form: bool = False
4380
4381Returns a list of dicts with information of loaded CA certs.
4382
4383If the optional argument is True, returns a DER-encoded copy of the CA
4384certificate.
4385
4386NOTE: Certificates in a capath directory aren't loaded unless they have
4387been used at least once.
4388[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004389
4390static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004391_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4392/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004393{
4394 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004395 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004396 PyObject *ci = NULL, *rlist = NULL;
4397 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004398
4399 if ((rlist = PyList_New(0)) == NULL) {
4400 return NULL;
4401 }
4402
4403 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004404 objs = X509_STORE_get0_objects(store);
4405 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004406 X509_OBJECT *obj;
4407 X509 *cert;
4408
Christian Heimes598894f2016-09-05 23:19:05 +02004409 obj = sk_X509_OBJECT_value(objs, i);
4410 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004411 /* not a x509 cert */
4412 continue;
4413 }
4414 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004415 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004416 if (!X509_check_ca(cert)) {
4417 continue;
4418 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004419 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004420 ci = _certificate_to_der(cert);
4421 } else {
4422 ci = _decode_certificate(cert);
4423 }
4424 if (ci == NULL) {
4425 goto error;
4426 }
4427 if (PyList_Append(rlist, ci) == -1) {
4428 goto error;
4429 }
4430 Py_CLEAR(ci);
4431 }
4432 return rlist;
4433
4434 error:
4435 Py_XDECREF(ci);
4436 Py_XDECREF(rlist);
4437 return NULL;
4438}
4439
4440
Antoine Pitrou152efa22010-05-16 18:19:27 +00004441static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004442 {"check_hostname", (getter) get_check_hostname,
4443 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004444 {"_host_flags", (getter) get_host_flags,
4445 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004446#if SSL_CTRL_GET_MAX_PROTO_VERSION
4447 {"minimum_version", (getter) get_minimum_version,
4448 (setter) set_minimum_version, NULL},
4449 {"maximum_version", (getter) get_maximum_version,
4450 (setter) set_maximum_version, NULL},
4451#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004452 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004453 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004454 {"options", (getter) get_options,
4455 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004456 {"protocol", (getter) get_protocol,
4457 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004458 {"verify_flags", (getter) get_verify_flags,
4459 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004460 {"verify_mode", (getter) get_verify_mode,
4461 (setter) set_verify_mode, NULL},
4462 {NULL}, /* sentinel */
4463};
4464
4465static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004466 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4467 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4468 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4469 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4470 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4471 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4472 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4473 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4474 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4475 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4476 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004477 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4478 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004479 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004480 {NULL, NULL} /* sentinel */
4481};
4482
4483static PyTypeObject PySSLContext_Type = {
4484 PyVarObject_HEAD_INIT(NULL, 0)
4485 "_ssl._SSLContext", /*tp_name*/
4486 sizeof(PySSLContext), /*tp_basicsize*/
4487 0, /*tp_itemsize*/
4488 (destructor)context_dealloc, /*tp_dealloc*/
4489 0, /*tp_print*/
4490 0, /*tp_getattr*/
4491 0, /*tp_setattr*/
4492 0, /*tp_reserved*/
4493 0, /*tp_repr*/
4494 0, /*tp_as_number*/
4495 0, /*tp_as_sequence*/
4496 0, /*tp_as_mapping*/
4497 0, /*tp_hash*/
4498 0, /*tp_call*/
4499 0, /*tp_str*/
4500 0, /*tp_getattro*/
4501 0, /*tp_setattro*/
4502 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004503 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004504 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004505 (traverseproc) context_traverse, /*tp_traverse*/
4506 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004507 0, /*tp_richcompare*/
4508 0, /*tp_weaklistoffset*/
4509 0, /*tp_iter*/
4510 0, /*tp_iternext*/
4511 context_methods, /*tp_methods*/
4512 0, /*tp_members*/
4513 context_getsetlist, /*tp_getset*/
4514 0, /*tp_base*/
4515 0, /*tp_dict*/
4516 0, /*tp_descr_get*/
4517 0, /*tp_descr_set*/
4518 0, /*tp_dictoffset*/
4519 0, /*tp_init*/
4520 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004521 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004522};
4523
4524
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004525/*
4526 * MemoryBIO objects
4527 */
4528
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004529/*[clinic input]
4530@classmethod
4531_ssl.MemoryBIO.__new__
4532
4533[clinic start generated code]*/
4534
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004535static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004536_ssl_MemoryBIO_impl(PyTypeObject *type)
4537/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004538{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004539 BIO *bio;
4540 PySSLMemoryBIO *self;
4541
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004542 bio = BIO_new(BIO_s_mem());
4543 if (bio == NULL) {
4544 PyErr_SetString(PySSLErrorObject,
4545 "failed to allocate BIO");
4546 return NULL;
4547 }
4548 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4549 * just that no data is currently available. The SSL routines should retry
4550 * the read, which we can achieve by calling BIO_set_retry_read(). */
4551 BIO_set_retry_read(bio);
4552 BIO_set_mem_eof_return(bio, -1);
4553
4554 assert(type != NULL && type->tp_alloc != NULL);
4555 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4556 if (self == NULL) {
4557 BIO_free(bio);
4558 return NULL;
4559 }
4560 self->bio = bio;
4561 self->eof_written = 0;
4562
4563 return (PyObject *) self;
4564}
4565
4566static void
4567memory_bio_dealloc(PySSLMemoryBIO *self)
4568{
4569 BIO_free(self->bio);
4570 Py_TYPE(self)->tp_free(self);
4571}
4572
4573static PyObject *
4574memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4575{
Segev Finer5cff6372017-07-27 01:19:17 +03004576 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004577}
4578
4579PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4580"The number of bytes pending in the memory BIO.");
4581
4582static PyObject *
4583memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4584{
4585 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4586 && self->eof_written);
4587}
4588
4589PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4590"Whether the memory BIO is at EOF.");
4591
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004592/*[clinic input]
4593_ssl.MemoryBIO.read
4594 size as len: int = -1
4595 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004596
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004597Read up to size bytes from the memory BIO.
4598
4599If size is not specified, read the entire buffer.
4600If the return value is an empty bytes instance, this means either
4601EOF or that no data is available. Use the "eof" property to
4602distinguish between the two.
4603[clinic start generated code]*/
4604
4605static PyObject *
4606_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4607/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4608{
4609 int avail, nbytes;
4610 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004611
Segev Finer5cff6372017-07-27 01:19:17 +03004612 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004613 if ((len < 0) || (len > avail))
4614 len = avail;
4615
4616 result = PyBytes_FromStringAndSize(NULL, len);
4617 if ((result == NULL) || (len == 0))
4618 return result;
4619
4620 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4621 /* There should never be any short reads but check anyway. */
4622 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4623 Py_DECREF(result);
4624 return NULL;
4625 }
4626
4627 return result;
4628}
4629
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004630/*[clinic input]
4631_ssl.MemoryBIO.write
4632 b: Py_buffer
4633 /
4634
4635Writes the bytes b into the memory BIO.
4636
4637Returns the number of bytes written.
4638[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004639
4640static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004641_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4642/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004643{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004644 int nbytes;
4645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004646 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647 PyErr_Format(PyExc_OverflowError,
4648 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004650 }
4651
4652 if (self->eof_written) {
4653 PyErr_SetString(PySSLErrorObject,
4654 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004655 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004656 }
4657
Segev Finer5cff6372017-07-27 01:19:17 +03004658 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004659 if (nbytes < 0) {
4660 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004661 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004662 }
4663
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004664 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004665}
4666
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004667/*[clinic input]
4668_ssl.MemoryBIO.write_eof
4669
4670Write an EOF marker to the memory BIO.
4671
4672When all data has been read, the "eof" property will be True.
4673[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004674
4675static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004676_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4677/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004678{
4679 self->eof_written = 1;
4680 /* After an EOF is written, a zero return from read() should be a real EOF
4681 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4682 BIO_clear_retry_flags(self->bio);
4683 BIO_set_mem_eof_return(self->bio, 0);
4684
4685 Py_RETURN_NONE;
4686}
4687
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004688static PyGetSetDef memory_bio_getsetlist[] = {
4689 {"pending", (getter) memory_bio_get_pending, NULL,
4690 PySSL_memory_bio_pending_doc},
4691 {"eof", (getter) memory_bio_get_eof, NULL,
4692 PySSL_memory_bio_eof_doc},
4693 {NULL}, /* sentinel */
4694};
4695
4696static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004697 _SSL_MEMORYBIO_READ_METHODDEF
4698 _SSL_MEMORYBIO_WRITE_METHODDEF
4699 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004700 {NULL, NULL} /* sentinel */
4701};
4702
4703static PyTypeObject PySSLMemoryBIO_Type = {
4704 PyVarObject_HEAD_INIT(NULL, 0)
4705 "_ssl.MemoryBIO", /*tp_name*/
4706 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4707 0, /*tp_itemsize*/
4708 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4709 0, /*tp_print*/
4710 0, /*tp_getattr*/
4711 0, /*tp_setattr*/
4712 0, /*tp_reserved*/
4713 0, /*tp_repr*/
4714 0, /*tp_as_number*/
4715 0, /*tp_as_sequence*/
4716 0, /*tp_as_mapping*/
4717 0, /*tp_hash*/
4718 0, /*tp_call*/
4719 0, /*tp_str*/
4720 0, /*tp_getattro*/
4721 0, /*tp_setattro*/
4722 0, /*tp_as_buffer*/
4723 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4724 0, /*tp_doc*/
4725 0, /*tp_traverse*/
4726 0, /*tp_clear*/
4727 0, /*tp_richcompare*/
4728 0, /*tp_weaklistoffset*/
4729 0, /*tp_iter*/
4730 0, /*tp_iternext*/
4731 memory_bio_methods, /*tp_methods*/
4732 0, /*tp_members*/
4733 memory_bio_getsetlist, /*tp_getset*/
4734 0, /*tp_base*/
4735 0, /*tp_dict*/
4736 0, /*tp_descr_get*/
4737 0, /*tp_descr_set*/
4738 0, /*tp_dictoffset*/
4739 0, /*tp_init*/
4740 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004741 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004742};
4743
Antoine Pitrou152efa22010-05-16 18:19:27 +00004744
Christian Heimes99a65702016-09-10 23:44:53 +02004745/*
4746 * SSL Session object
4747 */
4748
4749static void
4750PySSLSession_dealloc(PySSLSession *self)
4751{
INADA Naokia6296d32017-08-24 14:55:17 +09004752 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004753 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004754 Py_XDECREF(self->ctx);
4755 if (self->session != NULL) {
4756 SSL_SESSION_free(self->session);
4757 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004758 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004759}
4760
4761static PyObject *
4762PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4763{
4764 int result;
4765
4766 if (left == NULL || right == NULL) {
4767 PyErr_BadInternalCall();
4768 return NULL;
4769 }
4770
4771 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4772 Py_RETURN_NOTIMPLEMENTED;
4773 }
4774
4775 if (left == right) {
4776 result = 0;
4777 } else {
4778 const unsigned char *left_id, *right_id;
4779 unsigned int left_len, right_len;
4780 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4781 &left_len);
4782 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4783 &right_len);
4784 if (left_len == right_len) {
4785 result = memcmp(left_id, right_id, left_len);
4786 } else {
4787 result = 1;
4788 }
4789 }
4790
4791 switch (op) {
4792 case Py_EQ:
4793 if (result == 0) {
4794 Py_RETURN_TRUE;
4795 } else {
4796 Py_RETURN_FALSE;
4797 }
4798 break;
4799 case Py_NE:
4800 if (result != 0) {
4801 Py_RETURN_TRUE;
4802 } else {
4803 Py_RETURN_FALSE;
4804 }
4805 break;
4806 case Py_LT:
4807 case Py_LE:
4808 case Py_GT:
4809 case Py_GE:
4810 Py_RETURN_NOTIMPLEMENTED;
4811 break;
4812 default:
4813 PyErr_BadArgument();
4814 return NULL;
4815 }
4816}
4817
4818static int
4819PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4820{
4821 Py_VISIT(self->ctx);
4822 return 0;
4823}
4824
4825static int
4826PySSLSession_clear(PySSLSession *self)
4827{
4828 Py_CLEAR(self->ctx);
4829 return 0;
4830}
4831
4832
4833static PyObject *
4834PySSLSession_get_time(PySSLSession *self, void *closure) {
4835 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4836}
4837
4838PyDoc_STRVAR(PySSLSession_get_time_doc,
4839"Session creation time (seconds since epoch).");
4840
4841
4842static PyObject *
4843PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4844 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4845}
4846
4847PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4848"Session timeout (delta in seconds).");
4849
4850
4851static PyObject *
4852PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4853 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4854 return PyLong_FromUnsignedLong(hint);
4855}
4856
4857PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4858"Ticket life time hint.");
4859
4860
4861static PyObject *
4862PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4863 const unsigned char *id;
4864 unsigned int len;
4865 id = SSL_SESSION_get_id(self->session, &len);
4866 return PyBytes_FromStringAndSize((const char *)id, len);
4867}
4868
4869PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4870"Session id");
4871
4872
4873static PyObject *
4874PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4875 if (SSL_SESSION_has_ticket(self->session)) {
4876 Py_RETURN_TRUE;
4877 } else {
4878 Py_RETURN_FALSE;
4879 }
4880}
4881
4882PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4883"Does the session contain a ticket?");
4884
4885
4886static PyGetSetDef PySSLSession_getsetlist[] = {
4887 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4888 PySSLSession_get_has_ticket_doc},
4889 {"id", (getter) PySSLSession_get_session_id, NULL,
4890 PySSLSession_get_session_id_doc},
4891 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4892 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4893 {"time", (getter) PySSLSession_get_time, NULL,
4894 PySSLSession_get_time_doc},
4895 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4896 PySSLSession_get_timeout_doc},
4897 {NULL}, /* sentinel */
4898};
4899
4900static PyTypeObject PySSLSession_Type = {
4901 PyVarObject_HEAD_INIT(NULL, 0)
4902 "_ssl.Session", /*tp_name*/
4903 sizeof(PySSLSession), /*tp_basicsize*/
4904 0, /*tp_itemsize*/
4905 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4906 0, /*tp_print*/
4907 0, /*tp_getattr*/
4908 0, /*tp_setattr*/
4909 0, /*tp_reserved*/
4910 0, /*tp_repr*/
4911 0, /*tp_as_number*/
4912 0, /*tp_as_sequence*/
4913 0, /*tp_as_mapping*/
4914 0, /*tp_hash*/
4915 0, /*tp_call*/
4916 0, /*tp_str*/
4917 0, /*tp_getattro*/
4918 0, /*tp_setattro*/
4919 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004920 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004921 0, /*tp_doc*/
4922 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4923 (inquiry)PySSLSession_clear, /*tp_clear*/
4924 PySSLSession_richcompare, /*tp_richcompare*/
4925 0, /*tp_weaklistoffset*/
4926 0, /*tp_iter*/
4927 0, /*tp_iternext*/
4928 0, /*tp_methods*/
4929 0, /*tp_members*/
4930 PySSLSession_getsetlist, /*tp_getset*/
4931};
4932
4933
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004934/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004935/*[clinic input]
4936_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004937 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004938 entropy: double
4939 /
4940
4941Mix string into the OpenSSL PRNG state.
4942
4943entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304944string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004945[clinic start generated code]*/
4946
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004947static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004948_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004949/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004950{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004951 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004952 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004953
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004954 buf = (const char *)view->buf;
4955 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004956 do {
4957 written = Py_MIN(len, INT_MAX);
4958 RAND_add(buf, (int)written, entropy);
4959 buf += written;
4960 len -= written;
4961 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004962 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004963}
4964
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004965static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004966PySSL_RAND(int len, int pseudo)
4967{
4968 int ok;
4969 PyObject *bytes;
4970 unsigned long err;
4971 const char *errstr;
4972 PyObject *v;
4973
Victor Stinner1e81a392013-12-19 16:47:04 +01004974 if (len < 0) {
4975 PyErr_SetString(PyExc_ValueError, "num must be positive");
4976 return NULL;
4977 }
4978
Victor Stinner99c8b162011-05-24 12:05:19 +02004979 bytes = PyBytes_FromStringAndSize(NULL, len);
4980 if (bytes == NULL)
4981 return NULL;
4982 if (pseudo) {
4983 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4984 if (ok == 0 || ok == 1)
4985 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4986 }
4987 else {
4988 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4989 if (ok == 1)
4990 return bytes;
4991 }
4992 Py_DECREF(bytes);
4993
4994 err = ERR_get_error();
4995 errstr = ERR_reason_error_string(err);
4996 v = Py_BuildValue("(ks)", err, errstr);
4997 if (v != NULL) {
4998 PyErr_SetObject(PySSLErrorObject, v);
4999 Py_DECREF(v);
5000 }
5001 return NULL;
5002}
5003
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005004/*[clinic input]
5005_ssl.RAND_bytes
5006 n: int
5007 /
5008
5009Generate n cryptographically strong pseudo-random bytes.
5010[clinic start generated code]*/
5011
Victor Stinner99c8b162011-05-24 12:05:19 +02005012static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005013_ssl_RAND_bytes_impl(PyObject *module, int n)
5014/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005015{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005016 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005017}
5018
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005019/*[clinic input]
5020_ssl.RAND_pseudo_bytes
5021 n: int
5022 /
5023
5024Generate n pseudo-random bytes.
5025
5026Return a pair (bytes, is_cryptographic). is_cryptographic is True
5027if the bytes generated are cryptographically strong.
5028[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005029
5030static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005031_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5032/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005033{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005034 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005035}
5036
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005037/*[clinic input]
5038_ssl.RAND_status
5039
5040Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5041
5042It is necessary to seed the PRNG with RAND_add() on some platforms before
5043using the ssl() function.
5044[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005045
5046static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005047_ssl_RAND_status_impl(PyObject *module)
5048/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005049{
Christian Heimes217cfd12007-12-02 14:31:20 +00005050 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005051}
5052
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005053#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005054/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005055/*[clinic input]
5056_ssl.RAND_egd
5057 path: object(converter="PyUnicode_FSConverter")
5058 /
5059
5060Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5061
5062Returns number of bytes read. Raises SSLError if connection to EGD
5063fails or if it does not provide enough data to seed PRNG.
5064[clinic start generated code]*/
5065
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005066static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005067_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5068/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005069{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005070 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005071 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005072 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005073 PyErr_SetString(PySSLErrorObject,
5074 "EGD connection failed or EGD did not return "
5075 "enough data to seed the PRNG");
5076 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005077 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005078 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005079}
Christian Heimesa5d07652016-09-24 10:48:05 +02005080/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005081#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005082
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005083
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005084
5085/*[clinic input]
5086_ssl.get_default_verify_paths
5087
5088Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5089
5090The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5091[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005092
5093static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005094_ssl_get_default_verify_paths_impl(PyObject *module)
5095/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005096{
5097 PyObject *ofile_env = NULL;
5098 PyObject *ofile = NULL;
5099 PyObject *odir_env = NULL;
5100 PyObject *odir = NULL;
5101
Benjamin Petersond113c962015-07-18 10:59:13 -07005102#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005103 const char *tmp = (info); \
5104 target = NULL; \
5105 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5106 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5107 target = PyBytes_FromString(tmp); } \
5108 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005109 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005110
Benjamin Petersond113c962015-07-18 10:59:13 -07005111 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5112 CONVERT(X509_get_default_cert_file(), ofile);
5113 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5114 CONVERT(X509_get_default_cert_dir(), odir);
5115#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005116
Christian Heimes200bb1b2013-06-14 15:14:29 +02005117 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005118
5119 error:
5120 Py_XDECREF(ofile_env);
5121 Py_XDECREF(ofile);
5122 Py_XDECREF(odir_env);
5123 Py_XDECREF(odir);
5124 return NULL;
5125}
5126
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005127static PyObject*
5128asn1obj2py(ASN1_OBJECT *obj)
5129{
5130 int nid;
5131 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005132
5133 nid = OBJ_obj2nid(obj);
5134 if (nid == NID_undef) {
5135 PyErr_Format(PyExc_ValueError, "Unknown object");
5136 return NULL;
5137 }
5138 sn = OBJ_nid2sn(nid);
5139 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005140 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005141}
5142
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005143/*[clinic input]
5144_ssl.txt2obj
5145 txt: str
5146 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005147
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005148Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5149
5150By default objects are looked up by OID. With name=True short and
5151long name are also matched.
5152[clinic start generated code]*/
5153
5154static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005155_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5156/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005157{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005158 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005159 ASN1_OBJECT *obj;
5160
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005161 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5162 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005163 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005164 return NULL;
5165 }
5166 result = asn1obj2py(obj);
5167 ASN1_OBJECT_free(obj);
5168 return result;
5169}
5170
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005171/*[clinic input]
5172_ssl.nid2obj
5173 nid: int
5174 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005175
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005176Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5177[clinic start generated code]*/
5178
5179static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005180_ssl_nid2obj_impl(PyObject *module, int nid)
5181/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005182{
5183 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005184 ASN1_OBJECT *obj;
5185
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005186 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005187 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005188 return NULL;
5189 }
5190 obj = OBJ_nid2obj(nid);
5191 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005192 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005193 return NULL;
5194 }
5195 result = asn1obj2py(obj);
5196 ASN1_OBJECT_free(obj);
5197 return result;
5198}
5199
Christian Heimes46bebee2013-06-09 19:03:31 +02005200#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005201
5202static PyObject*
5203certEncodingType(DWORD encodingType)
5204{
5205 static PyObject *x509_asn = NULL;
5206 static PyObject *pkcs_7_asn = NULL;
5207
5208 if (x509_asn == NULL) {
5209 x509_asn = PyUnicode_InternFromString("x509_asn");
5210 if (x509_asn == NULL)
5211 return NULL;
5212 }
5213 if (pkcs_7_asn == NULL) {
5214 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5215 if (pkcs_7_asn == NULL)
5216 return NULL;
5217 }
5218 switch(encodingType) {
5219 case X509_ASN_ENCODING:
5220 Py_INCREF(x509_asn);
5221 return x509_asn;
5222 case PKCS_7_ASN_ENCODING:
5223 Py_INCREF(pkcs_7_asn);
5224 return pkcs_7_asn;
5225 default:
5226 return PyLong_FromLong(encodingType);
5227 }
5228}
5229
5230static PyObject*
5231parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5232{
5233 CERT_ENHKEY_USAGE *usage;
5234 DWORD size, error, i;
5235 PyObject *retval;
5236
5237 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5238 error = GetLastError();
5239 if (error == CRYPT_E_NOT_FOUND) {
5240 Py_RETURN_TRUE;
5241 }
5242 return PyErr_SetFromWindowsErr(error);
5243 }
5244
5245 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5246 if (usage == NULL) {
5247 return PyErr_NoMemory();
5248 }
5249
5250 /* Now get the actual enhanced usage property */
5251 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5252 PyMem_Free(usage);
5253 error = GetLastError();
5254 if (error == CRYPT_E_NOT_FOUND) {
5255 Py_RETURN_TRUE;
5256 }
5257 return PyErr_SetFromWindowsErr(error);
5258 }
5259 retval = PySet_New(NULL);
5260 if (retval == NULL) {
5261 goto error;
5262 }
5263 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5264 if (usage->rgpszUsageIdentifier[i]) {
5265 PyObject *oid;
5266 int err;
5267 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5268 if (oid == NULL) {
5269 Py_CLEAR(retval);
5270 goto error;
5271 }
5272 err = PySet_Add(retval, oid);
5273 Py_DECREF(oid);
5274 if (err == -1) {
5275 Py_CLEAR(retval);
5276 goto error;
5277 }
5278 }
5279 }
5280 error:
5281 PyMem_Free(usage);
5282 return retval;
5283}
5284
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005285/*[clinic input]
5286_ssl.enum_certificates
5287 store_name: str
5288
5289Retrieve certificates from Windows' cert store.
5290
5291store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5292more cert storages, too. The function returns a list of (bytes,
5293encoding_type, trust) tuples. The encoding_type flag can be interpreted
5294with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5295a set of OIDs or the boolean True.
5296[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005297
Christian Heimes46bebee2013-06-09 19:03:31 +02005298static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005299_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5300/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005301{
Christian Heimes46bebee2013-06-09 19:03:31 +02005302 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005303 PCCERT_CONTEXT pCertCtx = NULL;
5304 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005305 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005306
Christian Heimes44109d72013-11-22 01:51:30 +01005307 result = PyList_New(0);
5308 if (result == NULL) {
5309 return NULL;
5310 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005311 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5312 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5313 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005314 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005315 Py_DECREF(result);
5316 return PyErr_SetFromWindowsErr(GetLastError());
5317 }
5318
Christian Heimes44109d72013-11-22 01:51:30 +01005319 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5320 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5321 pCertCtx->cbCertEncoded);
5322 if (!cert) {
5323 Py_CLEAR(result);
5324 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005325 }
Christian Heimes44109d72013-11-22 01:51:30 +01005326 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5327 Py_CLEAR(result);
5328 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005329 }
Christian Heimes44109d72013-11-22 01:51:30 +01005330 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5331 if (keyusage == Py_True) {
5332 Py_DECREF(keyusage);
5333 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005334 }
Christian Heimes44109d72013-11-22 01:51:30 +01005335 if (keyusage == NULL) {
5336 Py_CLEAR(result);
5337 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005338 }
Christian Heimes44109d72013-11-22 01:51:30 +01005339 if ((tup = PyTuple_New(3)) == NULL) {
5340 Py_CLEAR(result);
5341 break;
5342 }
5343 PyTuple_SET_ITEM(tup, 0, cert);
5344 cert = NULL;
5345 PyTuple_SET_ITEM(tup, 1, enc);
5346 enc = NULL;
5347 PyTuple_SET_ITEM(tup, 2, keyusage);
5348 keyusage = NULL;
5349 if (PyList_Append(result, tup) < 0) {
5350 Py_CLEAR(result);
5351 break;
5352 }
5353 Py_CLEAR(tup);
5354 }
5355 if (pCertCtx) {
5356 /* loop ended with an error, need to clean up context manually */
5357 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005358 }
5359
5360 /* In error cases cert, enc and tup may not be NULL */
5361 Py_XDECREF(cert);
5362 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005363 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005364 Py_XDECREF(tup);
5365
5366 if (!CertCloseStore(hStore, 0)) {
5367 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005368 Py_XDECREF(result);
5369 return PyErr_SetFromWindowsErr(GetLastError());
5370 }
5371 return result;
5372}
5373
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005374/*[clinic input]
5375_ssl.enum_crls
5376 store_name: str
5377
5378Retrieve CRLs from Windows' cert store.
5379
5380store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5381more cert storages, too. The function returns a list of (bytes,
5382encoding_type) tuples. The encoding_type flag can be interpreted with
5383X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5384[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005385
5386static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005387_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5388/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005389{
Christian Heimes44109d72013-11-22 01:51:30 +01005390 HCERTSTORE hStore = NULL;
5391 PCCRL_CONTEXT pCrlCtx = NULL;
5392 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5393 PyObject *result = NULL;
5394
Christian Heimes44109d72013-11-22 01:51:30 +01005395 result = PyList_New(0);
5396 if (result == NULL) {
5397 return NULL;
5398 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005399 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5400 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5401 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005402 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005403 Py_DECREF(result);
5404 return PyErr_SetFromWindowsErr(GetLastError());
5405 }
Christian Heimes44109d72013-11-22 01:51:30 +01005406
5407 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5408 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5409 pCrlCtx->cbCrlEncoded);
5410 if (!crl) {
5411 Py_CLEAR(result);
5412 break;
5413 }
5414 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5415 Py_CLEAR(result);
5416 break;
5417 }
5418 if ((tup = PyTuple_New(2)) == NULL) {
5419 Py_CLEAR(result);
5420 break;
5421 }
5422 PyTuple_SET_ITEM(tup, 0, crl);
5423 crl = NULL;
5424 PyTuple_SET_ITEM(tup, 1, enc);
5425 enc = NULL;
5426
5427 if (PyList_Append(result, tup) < 0) {
5428 Py_CLEAR(result);
5429 break;
5430 }
5431 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005432 }
Christian Heimes44109d72013-11-22 01:51:30 +01005433 if (pCrlCtx) {
5434 /* loop ended with an error, need to clean up context manually */
5435 CertFreeCRLContext(pCrlCtx);
5436 }
5437
5438 /* In error cases cert, enc and tup may not be NULL */
5439 Py_XDECREF(crl);
5440 Py_XDECREF(enc);
5441 Py_XDECREF(tup);
5442
5443 if (!CertCloseStore(hStore, 0)) {
5444 /* This error case might shadow another exception.*/
5445 Py_XDECREF(result);
5446 return PyErr_SetFromWindowsErr(GetLastError());
5447 }
5448 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005449}
Christian Heimes44109d72013-11-22 01:51:30 +01005450
5451#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005452
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005453/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005454static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005455 _SSL__TEST_DECODE_CERT_METHODDEF
5456 _SSL_RAND_ADD_METHODDEF
5457 _SSL_RAND_BYTES_METHODDEF
5458 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5459 _SSL_RAND_EGD_METHODDEF
5460 _SSL_RAND_STATUS_METHODDEF
5461 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5462 _SSL_ENUM_CERTIFICATES_METHODDEF
5463 _SSL_ENUM_CRLS_METHODDEF
5464 _SSL_TXT2OBJ_METHODDEF
5465 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005466 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005467};
5468
5469
Christian Heimes598894f2016-09-05 23:19:05 +02005470#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005471
5472/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005473 * of the Python C thread library
5474 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5475 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005476
5477static PyThread_type_lock *_ssl_locks = NULL;
5478
Christian Heimes4d98ca92013-08-19 17:36:29 +02005479#if OPENSSL_VERSION_NUMBER >= 0x10000000
5480/* use new CRYPTO_THREADID API. */
5481static void
5482_ssl_threadid_callback(CRYPTO_THREADID *id)
5483{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005484 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005485}
5486#else
5487/* deprecated CRYPTO_set_id_callback() API. */
5488static unsigned long
5489_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005490 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005491}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005492#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005493
Bill Janssen6e027db2007-11-15 22:23:56 +00005494static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005495 (int mode, int n, const char *file, int line) {
5496 /* this function is needed to perform locking on shared data
5497 structures. (Note that OpenSSL uses a number of global data
5498 structures that will be implicitly shared whenever multiple
5499 threads use OpenSSL.) Multi-threaded applications will
5500 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005502 locking_function() must be able to handle up to
5503 CRYPTO_num_locks() different mutex locks. It sets the n-th
5504 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005505
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005506 file and line are the file number of the function setting the
5507 lock. They can be useful for debugging.
5508 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005510 if ((_ssl_locks == NULL) ||
5511 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5512 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005514 if (mode & CRYPTO_LOCK) {
5515 PyThread_acquire_lock(_ssl_locks[n], 1);
5516 } else {
5517 PyThread_release_lock(_ssl_locks[n]);
5518 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005519}
5520
5521static int _setup_ssl_threads(void) {
5522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005523 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005524
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005525 if (_ssl_locks == NULL) {
5526 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005527 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5528 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005529 if (_ssl_locks == NULL) {
5530 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005531 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005532 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005533 for (i = 0; i < _ssl_locks_count; i++) {
5534 _ssl_locks[i] = PyThread_allocate_lock();
5535 if (_ssl_locks[i] == NULL) {
5536 unsigned int j;
5537 for (j = 0; j < i; j++) {
5538 PyThread_free_lock(_ssl_locks[j]);
5539 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005540 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005541 return 0;
5542 }
5543 }
5544 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005545#if OPENSSL_VERSION_NUMBER >= 0x10000000
5546 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5547#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005548 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005549#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005550 }
5551 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005552}
5553
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005554#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005555
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005556PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005557"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005558for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005559
Martin v. Löwis1a214512008-06-11 05:26:20 +00005560
5561static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005562 PyModuleDef_HEAD_INIT,
5563 "_ssl",
5564 module_doc,
5565 -1,
5566 PySSL_methods,
5567 NULL,
5568 NULL,
5569 NULL,
5570 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005571};
5572
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005573
5574static void
5575parse_openssl_version(unsigned long libver,
5576 unsigned int *major, unsigned int *minor,
5577 unsigned int *fix, unsigned int *patch,
5578 unsigned int *status)
5579{
5580 *status = libver & 0xF;
5581 libver >>= 4;
5582 *patch = libver & 0xFF;
5583 libver >>= 8;
5584 *fix = libver & 0xFF;
5585 libver >>= 8;
5586 *minor = libver & 0xFF;
5587 libver >>= 8;
5588 *major = libver & 0xFF;
5589}
5590
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005591PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005592PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005593{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005594 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005595 unsigned long libver;
5596 unsigned int major, minor, fix, patch, status;
5597 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005598 struct py_ssl_error_code *errcode;
5599 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005600
Antoine Pitrou152efa22010-05-16 18:19:27 +00005601 if (PyType_Ready(&PySSLContext_Type) < 0)
5602 return NULL;
5603 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005604 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005605 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5606 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005607 if (PyType_Ready(&PySSLSession_Type) < 0)
5608 return NULL;
5609
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005610
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005611 m = PyModule_Create(&_sslmodule);
5612 if (m == NULL)
5613 return NULL;
5614 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005615
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005616 /* Load _socket module and its C API */
5617 socket_api = PySocketModule_ImportModuleAndAPI();
5618 if (!socket_api)
5619 return NULL;
5620 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005621
Christian Heimesc941e622017-09-05 15:47:11 +02005622#ifndef OPENSSL_VERSION_1_1
5623 /* Load all algorithms and initialize cpuid */
5624 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005625 /* Init OpenSSL */
5626 SSL_load_error_strings();
5627 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005628#endif
5629
Christian Heimes598894f2016-09-05 23:19:05 +02005630#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005631 /* note that this will start threading if not already started */
5632 if (!_setup_ssl_threads()) {
5633 return NULL;
5634 }
Christian Heimes598894f2016-09-05 23:19:05 +02005635#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5636 /* OpenSSL 1.1.0 builtin thread support is enabled */
5637 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005638#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005640 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005641 sslerror_type_slots[0].pfunc = PyExc_OSError;
5642 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005643 if (PySSLErrorObject == NULL)
5644 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005645
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005646 /* ssl.CertificateError used to be a subclass of ValueError */
5647 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5648 if (bases == NULL)
5649 return NULL;
5650 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5651 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5652 bases, NULL);
5653 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005654 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5655 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5656 PySSLErrorObject, NULL);
5657 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5658 "ssl.SSLWantReadError", SSLWantReadError_doc,
5659 PySSLErrorObject, NULL);
5660 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5661 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5662 PySSLErrorObject, NULL);
5663 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5664 "ssl.SSLSyscallError", SSLSyscallError_doc,
5665 PySSLErrorObject, NULL);
5666 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5667 "ssl.SSLEOFError", SSLEOFError_doc,
5668 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005669 if (PySSLCertVerificationErrorObject == NULL
5670 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005671 || PySSLWantReadErrorObject == NULL
5672 || PySSLWantWriteErrorObject == NULL
5673 || PySSLSyscallErrorObject == NULL
5674 || PySSLEOFErrorObject == NULL)
5675 return NULL;
5676 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005677 || PyDict_SetItemString(d, "SSLCertVerificationError",
5678 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005679 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5680 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5681 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5682 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5683 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005684 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005685 if (PyDict_SetItemString(d, "_SSLContext",
5686 (PyObject *)&PySSLContext_Type) != 0)
5687 return NULL;
5688 if (PyDict_SetItemString(d, "_SSLSocket",
5689 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005690 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005691 if (PyDict_SetItemString(d, "MemoryBIO",
5692 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5693 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005694 if (PyDict_SetItemString(d, "SSLSession",
5695 (PyObject *)&PySSLSession_Type) != 0)
5696 return NULL;
5697
Christian Heimes892d66e2018-01-29 14:10:18 +01005698 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5699 PY_SSL_DEFAULT_CIPHER_STRING);
5700
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005701 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5702 PY_SSL_ERROR_ZERO_RETURN);
5703 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5704 PY_SSL_ERROR_WANT_READ);
5705 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5706 PY_SSL_ERROR_WANT_WRITE);
5707 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5708 PY_SSL_ERROR_WANT_X509_LOOKUP);
5709 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5710 PY_SSL_ERROR_SYSCALL);
5711 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5712 PY_SSL_ERROR_SSL);
5713 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5714 PY_SSL_ERROR_WANT_CONNECT);
5715 /* non ssl.h errorcodes */
5716 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5717 PY_SSL_ERROR_EOF);
5718 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5719 PY_SSL_ERROR_INVALID_ERROR_CODE);
5720 /* cert requirements */
5721 PyModule_AddIntConstant(m, "CERT_NONE",
5722 PY_SSL_CERT_NONE);
5723 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5724 PY_SSL_CERT_OPTIONAL);
5725 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5726 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005727 /* CRL verification for verification_flags */
5728 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5729 0);
5730 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5731 X509_V_FLAG_CRL_CHECK);
5732 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5733 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5734 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5735 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005736#ifdef X509_V_FLAG_TRUSTED_FIRST
5737 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5738 X509_V_FLAG_TRUSTED_FIRST);
5739#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005740
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005741 /* Alert Descriptions from ssl.h */
5742 /* note RESERVED constants no longer intended for use have been removed */
5743 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5744
5745#define ADD_AD_CONSTANT(s) \
5746 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5747 SSL_AD_##s)
5748
5749 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5750 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5751 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5752 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5753 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5754 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5755 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5756 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5757 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5758 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5759 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5760 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5761 ADD_AD_CONSTANT(UNKNOWN_CA);
5762 ADD_AD_CONSTANT(ACCESS_DENIED);
5763 ADD_AD_CONSTANT(DECODE_ERROR);
5764 ADD_AD_CONSTANT(DECRYPT_ERROR);
5765 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5766 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5767 ADD_AD_CONSTANT(INTERNAL_ERROR);
5768 ADD_AD_CONSTANT(USER_CANCELLED);
5769 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005770 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005771#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5772 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5773#endif
5774#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5775 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5776#endif
5777#ifdef SSL_AD_UNRECOGNIZED_NAME
5778 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5779#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005780#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5781 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5782#endif
5783#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5784 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5785#endif
5786#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5787 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5788#endif
5789
5790#undef ADD_AD_CONSTANT
5791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005792 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005793#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005794 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5795 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005796#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005797#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005798 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5799 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005800#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005801 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005802 PY_SSL_VERSION_TLS);
5803 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5804 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005805 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5806 PY_SSL_VERSION_TLS_CLIENT);
5807 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5808 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005809 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5810 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005811#if HAVE_TLSv1_2
5812 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5813 PY_SSL_VERSION_TLS1_1);
5814 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5815 PY_SSL_VERSION_TLS1_2);
5816#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005817
Antoine Pitroub5218772010-05-21 09:56:06 +00005818 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005819 PyModule_AddIntConstant(m, "OP_ALL",
5820 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005821 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5822 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5823 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005824#if HAVE_TLSv1_2
5825 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5826 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5827#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005828#ifdef SSL_OP_NO_TLSv1_3
5829 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5830#else
5831 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5832#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005833 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5834 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005835 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005836 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005837#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005838 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005839#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005840#ifdef SSL_OP_NO_COMPRESSION
5841 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5842 SSL_OP_NO_COMPRESSION);
5843#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005844#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5845 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5846 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5847#endif
Christian Heimes67c48012018-05-15 16:25:40 -04005848#ifdef SSL_OP_NO_RENEGOTIATION
5849 PyModule_AddIntConstant(m, "OP_NO_RENEGOTIATION",
5850 SSL_OP_NO_RENEGOTIATION);
5851#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005852
Christian Heimes61d478c2018-01-27 15:51:38 +01005853#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5854 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5855 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5856#endif
5857#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5858 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5859 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5860#endif
5861#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5862 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5863 X509_CHECK_FLAG_NO_WILDCARDS);
5864#endif
5865#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5866 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5867 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5868#endif
5869#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5870 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5871 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5872#endif
5873#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5874 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5875 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5876#endif
5877
Christian Heimes698dde12018-02-27 11:54:43 +01005878 /* protocol versions */
5879 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5880 PY_PROTO_MINIMUM_SUPPORTED);
5881 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5882 PY_PROTO_MAXIMUM_SUPPORTED);
5883 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5884 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5885 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5886 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5887 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005888
Christian Heimes698dde12018-02-27 11:54:43 +01005889#define addbool(m, v, b) \
5890 Py_INCREF((b) ? Py_True : Py_False); \
5891 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5892
5893#if HAVE_SNI
5894 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005895#else
Christian Heimes698dde12018-02-27 11:54:43 +01005896 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005897#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005898
5899 addbool(m, "HAS_TLS_UNIQUE", 1);
5900
5901#ifndef OPENSSL_NO_ECDH
5902 addbool(m, "HAS_ECDH", 1);
5903#else
5904 addbool(m, "HAS_ECDH", 0);
5905#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005906
Christian Heimes29eab552018-02-25 12:31:33 +01005907#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005908 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005909#else
Christian Heimes698dde12018-02-27 11:54:43 +01005910 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005911#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005912
Christian Heimes29eab552018-02-25 12:31:33 +01005913#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005914 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005915#else
Christian Heimes698dde12018-02-27 11:54:43 +01005916 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005917#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005918
5919#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5920 addbool(m, "HAS_SSLv2", 1);
5921#else
5922 addbool(m, "HAS_SSLv2", 0);
5923#endif
5924
5925#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5926 addbool(m, "HAS_SSLv3", 1);
5927#else
5928 addbool(m, "HAS_SSLv3", 0);
5929#endif
5930
5931#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5932 addbool(m, "HAS_TLSv1", 1);
5933#else
5934 addbool(m, "HAS_TLSv1", 0);
5935#endif
5936
5937#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5938 addbool(m, "HAS_TLSv1_1", 1);
5939#else
5940 addbool(m, "HAS_TLSv1_1", 0);
5941#endif
5942
5943#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5944 addbool(m, "HAS_TLSv1_2", 1);
5945#else
5946 addbool(m, "HAS_TLSv1_2", 0);
5947#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005948
Christian Heimescb5b68a2017-09-07 18:07:00 -07005949#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005950 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005951#else
Christian Heimes698dde12018-02-27 11:54:43 +01005952 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005953#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005954
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005955 /* Mappings for error codes */
5956 err_codes_to_names = PyDict_New();
5957 err_names_to_codes = PyDict_New();
5958 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5959 return NULL;
5960 errcode = error_codes;
5961 while (errcode->mnemonic != NULL) {
5962 PyObject *mnemo, *key;
5963 mnemo = PyUnicode_FromString(errcode->mnemonic);
5964 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5965 if (mnemo == NULL || key == NULL)
5966 return NULL;
5967 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5968 return NULL;
5969 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5970 return NULL;
5971 Py_DECREF(key);
5972 Py_DECREF(mnemo);
5973 errcode++;
5974 }
5975 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5976 return NULL;
5977 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5978 return NULL;
5979
5980 lib_codes_to_names = PyDict_New();
5981 if (lib_codes_to_names == NULL)
5982 return NULL;
5983 libcode = library_codes;
5984 while (libcode->library != NULL) {
5985 PyObject *mnemo, *key;
5986 key = PyLong_FromLong(libcode->code);
5987 mnemo = PyUnicode_FromString(libcode->library);
5988 if (key == NULL || mnemo == NULL)
5989 return NULL;
5990 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5991 return NULL;
5992 Py_DECREF(key);
5993 Py_DECREF(mnemo);
5994 libcode++;
5995 }
5996 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5997 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005999 /* OpenSSL version */
6000 /* SSLeay() gives us the version of the library linked against,
6001 which could be different from the headers version.
6002 */
6003 libver = SSLeay();
6004 r = PyLong_FromUnsignedLong(libver);
6005 if (r == NULL)
6006 return NULL;
6007 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6008 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006009 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006010 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6011 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6012 return NULL;
6013 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6014 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6015 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006016
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006017 libver = OPENSSL_VERSION_NUMBER;
6018 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6019 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6020 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6021 return NULL;
6022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006023 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006024}