blob: 30c340376a4f70a0b1cef9f1f2cc84ebf8814e70 [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) {
855 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
856 _setSSLError(NULL, 0, __FILE__, __LINE__);
857 goto error;
858 }
859 } else {
860 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
861 ASN1_STRING_length(ip))) {
862 _setSSLError(NULL, 0, __FILE__, __LINE__);
863 goto error;
864 }
865 }
866 }
867 retval = 0;
868 error:
869 if (ip != NULL) {
870 ASN1_OCTET_STRING_free(ip);
871 }
872 return retval;
873}
874
Antoine Pitrou152efa22010-05-16 18:19:27 +0000875static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100876newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000877 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200878 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100879 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200880 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000881{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000882 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100883 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200884 long mode;
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 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200921 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000922#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200923 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000924#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200925 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000926
Christian Heimes61d478c2018-01-27 15:51:38 +0100927 if (server_hostname != NULL) {
928 if (_ssl_configure_hostname(self, server_hostname) < 0) {
929 Py_DECREF(self);
930 return NULL;
931 }
932 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 /* If the socket is in non-blocking mode or timeout mode, set the BIO
934 * to non-blocking mode (blocking is the default)
935 */
Victor Stinnere2452312015-03-28 03:00:46 +0100936 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
938 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
939 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 PySSL_BEGIN_ALLOW_THREADS
942 if (socket_type == PY_SSL_CLIENT)
943 SSL_set_connect_state(self->ssl);
944 else
945 SSL_set_accept_state(self->ssl);
946 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000947
Antoine Pitroud6494802011-07-21 01:11:30 +0200948 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200949 if (sock != NULL) {
950 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
951 if (self->Socket == NULL) {
952 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200953 return NULL;
954 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100955 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100956 if (owner && owner != Py_None) {
957 if (PySSL_set_owner(self, owner, NULL) == -1) {
958 Py_DECREF(self);
959 return NULL;
960 }
961 }
962 if (session && session != Py_None) {
963 if (PySSL_set_session(self, session, NULL) == -1) {
964 Py_DECREF(self);
965 return NULL;
966 }
967 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000969}
970
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000971/* SSL object methods */
972
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300973/*[clinic input]
974_ssl._SSLSocket.do_handshake
975[clinic start generated code]*/
976
977static PyObject *
978_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
979/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000980{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000981 int ret;
982 int err;
983 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200984 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200985 _PyTime_t timeout, deadline = 0;
986 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000987
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200988 if (sock) {
989 if (((PyObject*)sock) == Py_None) {
990 _setSSLError("Underlying socket connection gone",
991 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
992 return NULL;
993 }
994 Py_INCREF(sock);
995
996 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100997 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200998 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
999 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001001
Victor Stinner14690702015-04-06 22:46:13 +02001002 timeout = GET_SOCKET_TIMEOUT(sock);
1003 has_timeout = (timeout > 0);
1004 if (has_timeout)
1005 deadline = _PyTime_GetMonotonicClock() + timeout;
1006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 /* Actually negotiate SSL connection */
1008 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001010 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07001012 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07001014 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001015
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001016 if (PyErr_CheckSignals())
1017 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001018
Victor Stinner14690702015-04-06 22:46:13 +02001019 if (has_timeout)
1020 timeout = deadline - _PyTime_GetMonotonicClock();
1021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001023 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001025 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 } else {
1027 sockstate = SOCKET_OPERATION_OK;
1028 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001030 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001031 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001032 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001033 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1035 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001036 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001037 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1039 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001040 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001041 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1043 break;
1044 }
1045 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001046 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 if (ret < 1)
1048 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001049
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001050 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001051
1052error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001053 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001054 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001055}
1056
Thomas Woutersed03b412007-08-28 21:37:11 +00001057static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001058_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1059{
1060 char buf[X509_NAME_MAXLEN];
1061 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001063 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001064
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001065 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 if (buflen < 0) {
1067 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001068 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001069 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001070 /* initial buffer is too small for oid + terminating null byte */
1071 if (buflen > X509_NAME_MAXLEN - 1) {
1072 /* make OBJ_obj2txt() calculate the required buflen */
1073 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1074 /* allocate len + 1 for terminating NULL byte */
1075 namebuf = PyMem_Malloc(buflen + 1);
1076 if (namebuf == NULL) {
1077 PyErr_NoMemory();
1078 return NULL;
1079 }
1080 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1081 if (buflen < 0) {
1082 _setSSLError(NULL, 0, __FILE__, __LINE__);
1083 goto done;
1084 }
1085 }
1086 if (!buflen && no_name) {
1087 Py_INCREF(Py_None);
1088 name_obj = Py_None;
1089 }
1090 else {
1091 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1092 }
1093
1094 done:
1095 if (buf != namebuf) {
1096 PyMem_Free(namebuf);
1097 }
1098 return name_obj;
1099}
1100
1101static PyObject *
1102_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1103{
1104 Py_ssize_t buflen;
1105 unsigned char *valuebuf = NULL;
1106 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001108 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1109 if (buflen < 0) {
1110 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001111 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001113 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001116}
1117
1118static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001120{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1122 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1123 PyObject *rdnt;
1124 PyObject *attr = NULL; /* tuple to hold an attribute */
1125 int entry_count = X509_NAME_entry_count(xname);
1126 X509_NAME_ENTRY *entry;
1127 ASN1_OBJECT *name;
1128 ASN1_STRING *value;
1129 int index_counter;
1130 int rdn_level = -1;
1131 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 dn = PyList_New(0);
1134 if (dn == NULL)
1135 return NULL;
1136 /* now create another tuple to hold the top-level RDN */
1137 rdn = PyList_New(0);
1138 if (rdn == NULL)
1139 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 for (index_counter = 0;
1142 index_counter < entry_count;
1143 index_counter++)
1144 {
1145 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 /* check to see if we've gotten to a new RDN */
1148 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001149 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 /* yes, new RDN */
1151 /* add old RDN to DN */
1152 rdnt = PyList_AsTuple(rdn);
1153 Py_DECREF(rdn);
1154 if (rdnt == NULL)
1155 goto fail0;
1156 retcode = PyList_Append(dn, rdnt);
1157 Py_DECREF(rdnt);
1158 if (retcode < 0)
1159 goto fail0;
1160 /* create new RDN */
1161 rdn = PyList_New(0);
1162 if (rdn == NULL)
1163 goto fail0;
1164 }
1165 }
Christian Heimes598894f2016-09-05 23:19:05 +02001166 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001168 /* now add this attribute to the current RDN */
1169 name = X509_NAME_ENTRY_get_object(entry);
1170 value = X509_NAME_ENTRY_get_data(entry);
1171 attr = _create_tuple_for_attribute(name, value);
1172 /*
1173 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1174 entry->set,
1175 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1176 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1177 */
1178 if (attr == NULL)
1179 goto fail1;
1180 retcode = PyList_Append(rdn, attr);
1181 Py_DECREF(attr);
1182 if (retcode < 0)
1183 goto fail1;
1184 }
1185 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001186 if (rdn != NULL) {
1187 if (PyList_GET_SIZE(rdn) > 0) {
1188 rdnt = PyList_AsTuple(rdn);
1189 Py_DECREF(rdn);
1190 if (rdnt == NULL)
1191 goto fail0;
1192 retcode = PyList_Append(dn, rdnt);
1193 Py_DECREF(rdnt);
1194 if (retcode < 0)
1195 goto fail0;
1196 }
1197 else {
1198 Py_DECREF(rdn);
1199 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 /* convert list to tuple */
1203 rdnt = PyList_AsTuple(dn);
1204 Py_DECREF(dn);
1205 if (rdnt == NULL)
1206 return NULL;
1207 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
1209 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001211
1212 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 Py_XDECREF(dn);
1214 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215}
1216
1217static PyObject *
1218_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 /* this code follows the procedure outlined in
1221 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1222 function to extract the STACK_OF(GENERAL_NAME),
1223 then iterates through the stack to add the
1224 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001226 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001228 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 GENERAL_NAMES *names = NULL;
1230 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 BIO *biobuf = NULL;
1232 char buf[2048];
1233 char *vptr;
1234 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 if (certificate == NULL)
1237 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 /* get a memory buffer */
1240 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001242 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1243 certificate, NID_subject_alt_name, NULL, NULL);
1244 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001245 if (peer_alt_names == Py_None) {
1246 peer_alt_names = PyList_New(0);
1247 if (peer_alt_names == NULL)
1248 goto fail;
1249 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001251 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001252 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001253 int gntype;
1254 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001256 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001257 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001258 switch (gntype) {
1259 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 /* we special-case DirName as a tuple of
1261 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001263 t = PyTuple_New(2);
1264 if (t == NULL) {
1265 goto fail;
1266 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001268 v = PyUnicode_FromString("DirName");
1269 if (v == NULL) {
1270 Py_DECREF(t);
1271 goto fail;
1272 }
1273 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 v = _create_tuple_for_X509_NAME (name->d.dirn);
1276 if (v == NULL) {
1277 Py_DECREF(t);
1278 goto fail;
1279 }
1280 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001281 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001282
Christian Heimes824f7f32013-08-17 00:54:47 +02001283 case GEN_EMAIL:
1284 case GEN_DNS:
1285 case GEN_URI:
1286 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1287 correctly, CVE-2013-4238 */
1288 t = PyTuple_New(2);
1289 if (t == NULL)
1290 goto fail;
1291 switch (gntype) {
1292 case GEN_EMAIL:
1293 v = PyUnicode_FromString("email");
1294 as = name->d.rfc822Name;
1295 break;
1296 case GEN_DNS:
1297 v = PyUnicode_FromString("DNS");
1298 as = name->d.dNSName;
1299 break;
1300 case GEN_URI:
1301 v = PyUnicode_FromString("URI");
1302 as = name->d.uniformResourceIdentifier;
1303 break;
1304 }
1305 if (v == NULL) {
1306 Py_DECREF(t);
1307 goto fail;
1308 }
1309 PyTuple_SET_ITEM(t, 0, v);
1310 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1311 ASN1_STRING_length(as));
1312 if (v == NULL) {
1313 Py_DECREF(t);
1314 goto fail;
1315 }
1316 PyTuple_SET_ITEM(t, 1, v);
1317 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001318
Christian Heimes1c03abd2016-09-06 23:25:35 +02001319 case GEN_RID:
1320 t = PyTuple_New(2);
1321 if (t == NULL)
1322 goto fail;
1323
1324 v = PyUnicode_FromString("Registered ID");
1325 if (v == NULL) {
1326 Py_DECREF(t);
1327 goto fail;
1328 }
1329 PyTuple_SET_ITEM(t, 0, v);
1330
1331 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1332 if (len < 0) {
1333 Py_DECREF(t);
1334 _setSSLError(NULL, 0, __FILE__, __LINE__);
1335 goto fail;
1336 } else if (len >= (int)sizeof(buf)) {
1337 v = PyUnicode_FromString("<INVALID>");
1338 } else {
1339 v = PyUnicode_FromStringAndSize(buf, len);
1340 }
1341 if (v == NULL) {
1342 Py_DECREF(t);
1343 goto fail;
1344 }
1345 PyTuple_SET_ITEM(t, 1, v);
1346 break;
1347
Christian Heimes824f7f32013-08-17 00:54:47 +02001348 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001349 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001350 switch (gntype) {
1351 /* check for new general name type */
1352 case GEN_OTHERNAME:
1353 case GEN_X400:
1354 case GEN_EDIPARTY:
1355 case GEN_IPADD:
1356 case GEN_RID:
1357 break;
1358 default:
1359 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1360 "Unknown general name type %d",
1361 gntype) == -1) {
1362 goto fail;
1363 }
1364 break;
1365 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001366 (void) BIO_reset(biobuf);
1367 GENERAL_NAME_print(biobuf, name);
1368 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1369 if (len < 0) {
1370 _setSSLError(NULL, 0, __FILE__, __LINE__);
1371 goto fail;
1372 }
1373 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001374 if (vptr == NULL) {
1375 PyErr_Format(PyExc_ValueError,
1376 "Invalid value %.200s",
1377 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001379 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 t = PyTuple_New(2);
1381 if (t == NULL)
1382 goto fail;
1383 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1384 if (v == NULL) {
1385 Py_DECREF(t);
1386 goto fail;
1387 }
1388 PyTuple_SET_ITEM(t, 0, v);
1389 v = PyUnicode_FromStringAndSize((vptr + 1),
1390 (len - (vptr - buf + 1)));
1391 if (v == NULL) {
1392 Py_DECREF(t);
1393 goto fail;
1394 }
1395 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001396 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001400
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001401 if (PyList_Append(peer_alt_names, t) < 0) {
1402 Py_DECREF(t);
1403 goto fail;
1404 }
1405 Py_DECREF(t);
1406 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001407 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001408 }
1409 BIO_free(biobuf);
1410 if (peer_alt_names != Py_None) {
1411 v = PyList_AsTuple(peer_alt_names);
1412 Py_DECREF(peer_alt_names);
1413 return v;
1414 } else {
1415 return peer_alt_names;
1416 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001417
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418
1419 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001420 if (biobuf != NULL)
1421 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 if (peer_alt_names != Py_None) {
1424 Py_XDECREF(peer_alt_names);
1425 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001428}
1429
1430static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001431_get_aia_uri(X509 *certificate, int nid) {
1432 PyObject *lst = NULL, *ostr = NULL;
1433 int i, result;
1434 AUTHORITY_INFO_ACCESS *info;
1435
1436 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001437 if (info == NULL)
1438 return Py_None;
1439 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1440 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001441 return Py_None;
1442 }
1443
1444 if ((lst = PyList_New(0)) == NULL) {
1445 goto fail;
1446 }
1447
1448 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1449 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1450 ASN1_IA5STRING *uri;
1451
1452 if ((OBJ_obj2nid(ad->method) != nid) ||
1453 (ad->location->type != GEN_URI)) {
1454 continue;
1455 }
1456 uri = ad->location->d.uniformResourceIdentifier;
1457 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1458 uri->length);
1459 if (ostr == NULL) {
1460 goto fail;
1461 }
1462 result = PyList_Append(lst, ostr);
1463 Py_DECREF(ostr);
1464 if (result < 0) {
1465 goto fail;
1466 }
1467 }
1468 AUTHORITY_INFO_ACCESS_free(info);
1469
1470 /* convert to tuple or None */
1471 if (PyList_Size(lst) == 0) {
1472 Py_DECREF(lst);
1473 return Py_None;
1474 } else {
1475 PyObject *tup;
1476 tup = PyList_AsTuple(lst);
1477 Py_DECREF(lst);
1478 return tup;
1479 }
1480
1481 fail:
1482 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001483 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001484 return NULL;
1485}
1486
1487static PyObject *
1488_get_crl_dp(X509 *certificate) {
1489 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001490 int i, j;
1491 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001492
Christian Heimes598894f2016-09-05 23:19:05 +02001493 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001494
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001495 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001496 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001497
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001498 lst = PyList_New(0);
1499 if (lst == NULL)
1500 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001501
1502 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1503 DIST_POINT *dp;
1504 STACK_OF(GENERAL_NAME) *gns;
1505
1506 dp = sk_DIST_POINT_value(dps, i);
1507 gns = dp->distpoint->name.fullname;
1508
1509 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1510 GENERAL_NAME *gn;
1511 ASN1_IA5STRING *uri;
1512 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001513 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001514
1515 gn = sk_GENERAL_NAME_value(gns, j);
1516 if (gn->type != GEN_URI) {
1517 continue;
1518 }
1519 uri = gn->d.uniformResourceIdentifier;
1520 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1521 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001522 if (ouri == NULL)
1523 goto done;
1524
1525 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001526 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001527 if (err < 0)
1528 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529 }
1530 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001531
1532 /* Convert to tuple. */
1533 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1534
1535 done:
1536 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001537 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001538 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001539}
1540
1541static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001542_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 PyObject *retval = NULL;
1545 BIO *biobuf = NULL;
1546 PyObject *peer;
1547 PyObject *peer_alt_names = NULL;
1548 PyObject *issuer;
1549 PyObject *version;
1550 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001551 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 ASN1_INTEGER *serialNumber;
1553 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001554 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 ASN1_TIME *notBefore, *notAfter;
1556 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 retval = PyDict_New();
1559 if (retval == NULL)
1560 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001562 peer = _create_tuple_for_X509_NAME(
1563 X509_get_subject_name(certificate));
1564 if (peer == NULL)
1565 goto fail0;
1566 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1567 Py_DECREF(peer);
1568 goto fail0;
1569 }
1570 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001571
Antoine Pitroufb046912010-11-09 20:21:19 +00001572 issuer = _create_tuple_for_X509_NAME(
1573 X509_get_issuer_name(certificate));
1574 if (issuer == NULL)
1575 goto fail0;
1576 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001578 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001580 Py_DECREF(issuer);
1581
1582 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001583 if (version == NULL)
1584 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001585 if (PyDict_SetItemString(retval, "version", version) < 0) {
1586 Py_DECREF(version);
1587 goto fail0;
1588 }
1589 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001590
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001591 /* get a memory buffer */
1592 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001593
Antoine Pitroufb046912010-11-09 20:21:19 +00001594 (void) BIO_reset(biobuf);
1595 serialNumber = X509_get_serialNumber(certificate);
1596 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1597 i2a_ASN1_INTEGER(biobuf, serialNumber);
1598 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1599 if (len < 0) {
1600 _setSSLError(NULL, 0, __FILE__, __LINE__);
1601 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001603 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1604 if (sn_obj == NULL)
1605 goto fail1;
1606 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1607 Py_DECREF(sn_obj);
1608 goto fail1;
1609 }
1610 Py_DECREF(sn_obj);
1611
1612 (void) BIO_reset(biobuf);
1613 notBefore = X509_get_notBefore(certificate);
1614 ASN1_TIME_print(biobuf, notBefore);
1615 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1616 if (len < 0) {
1617 _setSSLError(NULL, 0, __FILE__, __LINE__);
1618 goto fail1;
1619 }
1620 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1621 if (pnotBefore == NULL)
1622 goto fail1;
1623 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1624 Py_DECREF(pnotBefore);
1625 goto fail1;
1626 }
1627 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001628
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 (void) BIO_reset(biobuf);
1630 notAfter = X509_get_notAfter(certificate);
1631 ASN1_TIME_print(biobuf, notAfter);
1632 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1633 if (len < 0) {
1634 _setSSLError(NULL, 0, __FILE__, __LINE__);
1635 goto fail1;
1636 }
1637 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1638 if (pnotAfter == NULL)
1639 goto fail1;
1640 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1641 Py_DECREF(pnotAfter);
1642 goto fail1;
1643 }
1644 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001647
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 peer_alt_names = _get_peer_alt_names(certificate);
1649 if (peer_alt_names == NULL)
1650 goto fail1;
1651 else if (peer_alt_names != Py_None) {
1652 if (PyDict_SetItemString(retval, "subjectAltName",
1653 peer_alt_names) < 0) {
1654 Py_DECREF(peer_alt_names);
1655 goto fail1;
1656 }
1657 Py_DECREF(peer_alt_names);
1658 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001659
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001660 /* Authority Information Access: OCSP URIs */
1661 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1662 if (obj == NULL) {
1663 goto fail1;
1664 } else if (obj != Py_None) {
1665 result = PyDict_SetItemString(retval, "OCSP", obj);
1666 Py_DECREF(obj);
1667 if (result < 0) {
1668 goto fail1;
1669 }
1670 }
1671
1672 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1673 if (obj == NULL) {
1674 goto fail1;
1675 } else if (obj != Py_None) {
1676 result = PyDict_SetItemString(retval, "caIssuers", obj);
1677 Py_DECREF(obj);
1678 if (result < 0) {
1679 goto fail1;
1680 }
1681 }
1682
1683 /* CDP (CRL distribution points) */
1684 obj = _get_crl_dp(certificate);
1685 if (obj == NULL) {
1686 goto fail1;
1687 } else if (obj != Py_None) {
1688 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1689 Py_DECREF(obj);
1690 if (result < 0) {
1691 goto fail1;
1692 }
1693 }
1694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001695 BIO_free(biobuf);
1696 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001697
1698 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 if (biobuf != NULL)
1700 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001701 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001702 Py_XDECREF(retval);
1703 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001704}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001705
Christian Heimes9a5395a2013-06-17 15:44:12 +02001706static PyObject *
1707_certificate_to_der(X509 *certificate)
1708{
1709 unsigned char *bytes_buf = NULL;
1710 int len;
1711 PyObject *retval;
1712
1713 bytes_buf = NULL;
1714 len = i2d_X509(certificate, &bytes_buf);
1715 if (len < 0) {
1716 _setSSLError(NULL, 0, __FILE__, __LINE__);
1717 return NULL;
1718 }
1719 /* this is actually an immutable bytes sequence */
1720 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1721 OPENSSL_free(bytes_buf);
1722 return retval;
1723}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001725/*[clinic input]
1726_ssl._test_decode_cert
1727 path: object(converter="PyUnicode_FSConverter")
1728 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001730[clinic start generated code]*/
1731
1732static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001733_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1734/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001735{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 X509 *x=NULL;
1738 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001740 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1741 PyErr_SetString(PySSLErrorObject,
1742 "Can't malloc memory to read file");
1743 goto fail0;
1744 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001745
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001746 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 PyErr_SetString(PySSLErrorObject,
1748 "Can't open file");
1749 goto fail0;
1750 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1753 if (x == NULL) {
1754 PyErr_SetString(PySSLErrorObject,
1755 "Error decoding PEM-encoded file");
1756 goto fail0;
1757 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001758
Antoine Pitroufb046912010-11-09 20:21:19 +00001759 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001760 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001761
1762 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001763 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 if (cert != NULL) BIO_free(cert);
1765 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766}
1767
1768
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001769/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001770_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001771 der as binary_mode: bool = False
1772 /
1773
1774Returns the certificate for the peer.
1775
1776If no certificate was provided, returns None. If a certificate was
1777provided, but not validated, returns an empty dictionary. Otherwise
1778returns a dict containing information about the peer certificate.
1779
1780If the optional argument is True, returns a DER-encoded copy of the
1781peer certificate, or None if no certificate was provided. This will
1782return the certificate even if it wasn't validated.
1783[clinic start generated code]*/
1784
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001785static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001786_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1787/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001788{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001789 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001790 X509 *peer_cert;
1791 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001792
Christian Heimes66dc33b2017-05-23 16:02:02 -07001793 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001794 PyErr_SetString(PyExc_ValueError,
1795 "handshake not done yet");
1796 return NULL;
1797 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001798 peer_cert = SSL_get_peer_certificate(self->ssl);
1799 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001800 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001801
Antoine Pitrou721738f2012-08-15 23:20:39 +02001802 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001804 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001806 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001810 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001812 X509_free(peer_cert);
1813 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001814}
1815
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001816static PyObject *
1817cipher_to_tuple(const SSL_CIPHER *cipher)
1818{
1819 const char *cipher_name, *cipher_protocol;
1820 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001821 if (retval == NULL)
1822 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001823
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001826 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001827 PyTuple_SET_ITEM(retval, 0, Py_None);
1828 } else {
1829 v = PyUnicode_FromString(cipher_name);
1830 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001831 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001832 PyTuple_SET_ITEM(retval, 0, v);
1833 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001834
1835 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001837 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001838 PyTuple_SET_ITEM(retval, 1, Py_None);
1839 } else {
1840 v = PyUnicode_FromString(cipher_protocol);
1841 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001842 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001843 PyTuple_SET_ITEM(retval, 1, v);
1844 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001845
1846 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001848 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001850
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001851 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001852
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001853 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 Py_DECREF(retval);
1855 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001856}
1857
Christian Heimes25bfcd52016-09-06 00:04:45 +02001858#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1859static PyObject *
1860cipher_to_dict(const SSL_CIPHER *cipher)
1861{
1862 const char *cipher_name, *cipher_protocol;
1863
1864 unsigned long cipher_id;
1865 int alg_bits, strength_bits, len;
1866 char buf[512] = {0};
1867#if OPENSSL_VERSION_1_1
1868 int aead, nid;
1869 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1870#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001871
1872 /* can be NULL */
1873 cipher_name = SSL_CIPHER_get_name(cipher);
1874 cipher_protocol = SSL_CIPHER_get_version(cipher);
1875 cipher_id = SSL_CIPHER_get_id(cipher);
1876 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001877 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1878 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001879 if (len > 1 && buf[len-1] == '\n')
1880 buf[len-1] = '\0';
1881 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1882
1883#if OPENSSL_VERSION_1_1
1884 aead = SSL_CIPHER_is_aead(cipher);
1885 nid = SSL_CIPHER_get_cipher_nid(cipher);
1886 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1887 nid = SSL_CIPHER_get_digest_nid(cipher);
1888 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1889 nid = SSL_CIPHER_get_kx_nid(cipher);
1890 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1891 nid = SSL_CIPHER_get_auth_nid(cipher);
1892 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1893#endif
1894
Victor Stinner410b9882016-09-12 12:00:23 +02001895 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001896 "{sksssssssisi"
1897#if OPENSSL_VERSION_1_1
1898 "sOssssssss"
1899#endif
1900 "}",
1901 "id", cipher_id,
1902 "name", cipher_name,
1903 "protocol", cipher_protocol,
1904 "description", buf,
1905 "strength_bits", strength_bits,
1906 "alg_bits", alg_bits
1907#if OPENSSL_VERSION_1_1
1908 ,"aead", aead ? Py_True : Py_False,
1909 "symmetric", skcipher,
1910 "digest", digest,
1911 "kea", kx,
1912 "auth", auth
1913#endif
1914 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001915}
1916#endif
1917
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001918/*[clinic input]
1919_ssl._SSLSocket.shared_ciphers
1920[clinic start generated code]*/
1921
1922static PyObject *
1923_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1924/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001925{
1926 STACK_OF(SSL_CIPHER) *ciphers;
1927 int i;
1928 PyObject *res;
1929
Christian Heimes598894f2016-09-05 23:19:05 +02001930 ciphers = SSL_get_ciphers(self->ssl);
1931 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001932 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001933 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1934 if (!res)
1935 return NULL;
1936 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1937 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1938 if (!tup) {
1939 Py_DECREF(res);
1940 return NULL;
1941 }
1942 PyList_SET_ITEM(res, i, tup);
1943 }
1944 return res;
1945}
1946
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001947/*[clinic input]
1948_ssl._SSLSocket.cipher
1949[clinic start generated code]*/
1950
1951static PyObject *
1952_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1953/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001954{
1955 const SSL_CIPHER *current;
1956
1957 if (self->ssl == NULL)
1958 Py_RETURN_NONE;
1959 current = SSL_get_current_cipher(self->ssl);
1960 if (current == NULL)
1961 Py_RETURN_NONE;
1962 return cipher_to_tuple(current);
1963}
1964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001965/*[clinic input]
1966_ssl._SSLSocket.version
1967[clinic start generated code]*/
1968
1969static PyObject *
1970_ssl__SSLSocket_version_impl(PySSLSocket *self)
1971/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001972{
1973 const char *version;
1974
1975 if (self->ssl == NULL)
1976 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001977 if (!SSL_is_init_finished(self->ssl)) {
1978 /* handshake not finished */
1979 Py_RETURN_NONE;
1980 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001981 version = SSL_get_version(self->ssl);
1982 if (!strcmp(version, "unknown"))
1983 Py_RETURN_NONE;
1984 return PyUnicode_FromString(version);
1985}
1986
Christian Heimes29eab552018-02-25 12:31:33 +01001987#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001988/*[clinic input]
1989_ssl._SSLSocket.selected_npn_protocol
1990[clinic start generated code]*/
1991
1992static PyObject *
1993_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1994/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1995{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001996 const unsigned char *out;
1997 unsigned int outlen;
1998
Victor Stinner4569cd52013-06-23 14:58:43 +02001999 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002000 &out, &outlen);
2001
2002 if (out == NULL)
2003 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002004 return PyUnicode_FromStringAndSize((char *)out, outlen);
2005}
2006#endif
2007
Christian Heimes29eab552018-02-25 12:31:33 +01002008#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002009/*[clinic input]
2010_ssl._SSLSocket.selected_alpn_protocol
2011[clinic start generated code]*/
2012
2013static PyObject *
2014_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2015/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2016{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002017 const unsigned char *out;
2018 unsigned int outlen;
2019
2020 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2021
2022 if (out == NULL)
2023 Py_RETURN_NONE;
2024 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002025}
2026#endif
2027
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002028/*[clinic input]
2029_ssl._SSLSocket.compression
2030[clinic start generated code]*/
2031
2032static PyObject *
2033_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2034/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2035{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002036#ifdef OPENSSL_NO_COMP
2037 Py_RETURN_NONE;
2038#else
2039 const COMP_METHOD *comp_method;
2040 const char *short_name;
2041
2042 if (self->ssl == NULL)
2043 Py_RETURN_NONE;
2044 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002045 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002046 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002047 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002048 if (short_name == NULL)
2049 Py_RETURN_NONE;
2050 return PyUnicode_DecodeFSDefault(short_name);
2051#endif
2052}
2053
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002054static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2055 Py_INCREF(self->ctx);
2056 return self->ctx;
2057}
2058
2059static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2060 void *closure) {
2061
2062 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002063#if !HAVE_SNI
2064 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2065 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002066 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002067#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002068 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002069 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002070 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002071#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002072 } else {
2073 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2074 return -1;
2075 }
2076
2077 return 0;
2078}
2079
2080PyDoc_STRVAR(PySSL_set_context_doc,
2081"_setter_context(ctx)\n\
2082\
2083This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002084used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002085on the SSLContext to change the certificate information associated with the\n\
2086SSLSocket before the cryptographic exchange handshake messages\n");
2087
2088
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002089static PyObject *
2090PySSL_get_server_side(PySSLSocket *self, void *c)
2091{
2092 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2093}
2094
2095PyDoc_STRVAR(PySSL_get_server_side_doc,
2096"Whether this is a server-side socket.");
2097
2098static PyObject *
2099PySSL_get_server_hostname(PySSLSocket *self, void *c)
2100{
2101 if (self->server_hostname == NULL)
2102 Py_RETURN_NONE;
2103 Py_INCREF(self->server_hostname);
2104 return self->server_hostname;
2105}
2106
2107PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2108"The currently set server hostname (for SNI).");
2109
2110static PyObject *
2111PySSL_get_owner(PySSLSocket *self, void *c)
2112{
2113 PyObject *owner;
2114
2115 if (self->owner == NULL)
2116 Py_RETURN_NONE;
2117
2118 owner = PyWeakref_GetObject(self->owner);
2119 Py_INCREF(owner);
2120 return owner;
2121}
2122
2123static int
2124PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2125{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002126 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002127 if (self->owner == NULL)
2128 return -1;
2129 return 0;
2130}
2131
2132PyDoc_STRVAR(PySSL_get_owner_doc,
2133"The Python-level owner of this object.\
2134Passed as \"self\" in servername callback.");
2135
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002136
Antoine Pitrou152efa22010-05-16 18:19:27 +00002137static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002138{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 if (self->ssl)
2140 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002141 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002142 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002143 Py_XDECREF(self->server_hostname);
2144 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002145 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002146}
2147
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002148/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002149 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002150 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002151 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002152
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002153static int
Victor Stinner14690702015-04-06 22:46:13 +02002154PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002155{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002156 int rc;
2157#ifdef HAVE_POLL
2158 struct pollfd pollfd;
2159 _PyTime_t ms;
2160#else
2161 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 fd_set fds;
2163 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002164#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002167 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002169 else if (timeout < 0) {
2170 if (s->sock_timeout > 0)
2171 return SOCKET_HAS_TIMED_OUT;
2172 else
2173 return SOCKET_IS_BLOCKING;
2174 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002177 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 /* Prefer poll, if available, since you can poll() any fd
2181 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002182#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002183 pollfd.fd = s->sock_fd;
2184 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002185
Victor Stinner14690702015-04-06 22:46:13 +02002186 /* timeout is in seconds, poll() uses milliseconds */
2187 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002188 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002189
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002190 PySSL_BEGIN_ALLOW_THREADS
2191 rc = poll(&pollfd, 1, (int)ms);
2192 PySSL_END_ALLOW_THREADS
2193#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002195 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002197
Victor Stinner14690702015-04-06 22:46:13 +02002198 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 FD_ZERO(&fds);
2201 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002202
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002203 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002205 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002207 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002209 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002211#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2214 (when we are able to write or when there's something to read) */
2215 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002216}
2217
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002218/*[clinic input]
2219_ssl._SSLSocket.write
2220 b: Py_buffer
2221 /
2222
2223Writes the bytes-like object b into the SSL object.
2224
2225Returns the number of bytes written.
2226[clinic start generated code]*/
2227
2228static PyObject *
2229_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2230/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002231{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 int len;
2233 int sockstate;
2234 int err;
2235 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002236 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002237 _PyTime_t timeout, deadline = 0;
2238 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002239
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002240 if (sock != NULL) {
2241 if (((PyObject*)sock) == Py_None) {
2242 _setSSLError("Underlying socket connection gone",
2243 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2244 return NULL;
2245 }
2246 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 }
2248
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002249 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002250 PyErr_Format(PyExc_OverflowError,
2251 "string longer than %d bytes", INT_MAX);
2252 goto error;
2253 }
2254
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002255 if (sock != NULL) {
2256 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002257 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002258 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2259 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2260 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002261
Victor Stinner14690702015-04-06 22:46:13 +02002262 timeout = GET_SOCKET_TIMEOUT(sock);
2263 has_timeout = (timeout > 0);
2264 if (has_timeout)
2265 deadline = _PyTime_GetMonotonicClock() + timeout;
2266
2267 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002269 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002270 "The write operation timed out");
2271 goto error;
2272 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2273 PyErr_SetString(PySSLErrorObject,
2274 "Underlying socket has been closed.");
2275 goto error;
2276 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2277 PyErr_SetString(PySSLErrorObject,
2278 "Underlying socket too large for select().");
2279 goto error;
2280 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002281
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002284 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002285 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002287 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002288
2289 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002291
Victor Stinner14690702015-04-06 22:46:13 +02002292 if (has_timeout)
2293 timeout = deadline - _PyTime_GetMonotonicClock();
2294
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002296 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002298 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002299 } else {
2300 sockstate = SOCKET_OPERATION_OK;
2301 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002302
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002304 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002305 "The write operation timed out");
2306 goto error;
2307 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2308 PyErr_SetString(PySSLErrorObject,
2309 "Underlying socket has been closed.");
2310 goto error;
2311 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2312 break;
2313 }
2314 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002315
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002316 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002317 if (len > 0)
2318 return PyLong_FromLong(len);
2319 else
2320 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002321
2322error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002323 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002325}
2326
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002327/*[clinic input]
2328_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002329
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002330Returns the number of already decrypted bytes available for read, pending on the connection.
2331[clinic start generated code]*/
2332
2333static PyObject *
2334_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2335/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002336{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 PySSL_BEGIN_ALLOW_THREADS
2340 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002341 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 PySSL_END_ALLOW_THREADS
2343 if (count < 0)
2344 return PySSL_SetError(self, count, __FILE__, __LINE__);
2345 else
2346 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002347}
2348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002349/*[clinic input]
2350_ssl._SSLSocket.read
2351 size as len: int
2352 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002353 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002354 ]
2355 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002356
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002357Read up to size bytes from the SSL socket.
2358[clinic start generated code]*/
2359
2360static PyObject *
2361_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2362 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002363/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002364{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002367 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002368 int sockstate;
2369 int err;
2370 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002371 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002372 _PyTime_t timeout, deadline = 0;
2373 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002374
Martin Panter5503d472016-03-27 05:35:19 +00002375 if (!group_right_1 && len < 0) {
2376 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2377 return NULL;
2378 }
2379
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002380 if (sock != NULL) {
2381 if (((PyObject*)sock) == Py_None) {
2382 _setSSLError("Underlying socket connection gone",
2383 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2384 return NULL;
2385 }
2386 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 }
2388
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002389 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002390 dest = PyBytes_FromStringAndSize(NULL, len);
2391 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002392 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002393 if (len == 0) {
2394 Py_XDECREF(sock);
2395 return dest;
2396 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002397 mem = PyBytes_AS_STRING(dest);
2398 }
2399 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002400 mem = buffer->buf;
2401 if (len <= 0 || len > buffer->len) {
2402 len = (int) buffer->len;
2403 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002404 PyErr_SetString(PyExc_OverflowError,
2405 "maximum length can't fit in a C 'int'");
2406 goto error;
2407 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002408 if (len == 0) {
2409 count = 0;
2410 goto done;
2411 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002412 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002413 }
2414
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002415 if (sock != NULL) {
2416 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002417 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002418 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2419 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2420 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421
Victor Stinner14690702015-04-06 22:46:13 +02002422 timeout = GET_SOCKET_TIMEOUT(sock);
2423 has_timeout = (timeout > 0);
2424 if (has_timeout)
2425 deadline = _PyTime_GetMonotonicClock() + timeout;
2426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002428 PySSL_BEGIN_ALLOW_THREADS
2429 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002430 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002431 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 if (PyErr_CheckSignals())
2434 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002435
Victor Stinner14690702015-04-06 22:46:13 +02002436 if (has_timeout)
2437 timeout = deadline - _PyTime_GetMonotonicClock();
2438
Steve Dowere6eb48c2017-09-08 15:16:15 -07002439 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002441 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002442 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002443 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002444 } else if (err == SSL_ERROR_ZERO_RETURN &&
2445 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 {
2447 count = 0;
2448 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002450 else
2451 sockstate = SOCKET_OPERATION_OK;
2452
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002454 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002455 "The read operation timed out");
2456 goto error;
2457 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2458 break;
2459 }
2460 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002461
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002462 if (count <= 0) {
2463 PySSL_SetError(self, count, __FILE__, __LINE__);
2464 goto error;
2465 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002466
2467done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002468 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002469 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002470 _PyBytes_Resize(&dest, count);
2471 return dest;
2472 }
2473 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474 return PyLong_FromLong(count);
2475 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002476
2477error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002478 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002479 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002480 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002481 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002482}
2483
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002484/*[clinic input]
2485_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002486
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002487Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002488[clinic start generated code]*/
2489
2490static PyObject *
2491_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002492/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002493{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002494 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002495 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002496 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002497 _PyTime_t timeout, deadline = 0;
2498 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002499
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002500 if (sock != NULL) {
2501 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002502 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002503 _setSSLError("Underlying socket connection gone",
2504 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2505 return NULL;
2506 }
2507 Py_INCREF(sock);
2508
2509 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002510 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002511 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2512 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002513 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002514
Victor Stinner14690702015-04-06 22:46:13 +02002515 timeout = GET_SOCKET_TIMEOUT(sock);
2516 has_timeout = (timeout > 0);
2517 if (has_timeout)
2518 deadline = _PyTime_GetMonotonicClock() + timeout;
2519
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002520 while (1) {
2521 PySSL_BEGIN_ALLOW_THREADS
2522 /* Disable read-ahead so that unwrap can work correctly.
2523 * Otherwise OpenSSL might read in too much data,
2524 * eating clear text data that happens to be
2525 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002526 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002527 * function is used and the shutdown_seen_zero != 0
2528 * condition is met.
2529 */
2530 if (self->shutdown_seen_zero)
2531 SSL_set_read_ahead(self->ssl, 0);
2532 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002533 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002535
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2537 if (err > 0)
2538 break;
2539 if (err == 0) {
2540 /* Don't loop endlessly; instead preserve legacy
2541 behaviour of trying SSL_shutdown() only twice.
2542 This looks necessary for OpenSSL < 0.9.8m */
2543 if (++zeros > 1)
2544 break;
2545 /* Shutdown was sent, now try receiving */
2546 self->shutdown_seen_zero = 1;
2547 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002548 }
2549
Victor Stinner14690702015-04-06 22:46:13 +02002550 if (has_timeout)
2551 timeout = deadline - _PyTime_GetMonotonicClock();
2552
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002553 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002554 _PySSL_UPDATE_ERRNO(self, err);
2555 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002556 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002557 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002558 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002559 else
2560 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002561
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002562 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002563 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002564 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 "The read operation timed out");
2566 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002567 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002569 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002570 }
2571 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2572 PyErr_SetString(PySSLErrorObject,
2573 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002574 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002575 }
2576 else if (sockstate != SOCKET_OPERATION_OK)
2577 /* Retain the SSL error code */
2578 break;
2579 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002580
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002581 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002582 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002583 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002584 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002585 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002586 /* It's already INCREF'ed */
2587 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002588 else
2589 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002590
2591error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002592 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002593 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002594}
2595
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002596/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002597_ssl._SSLSocket.get_channel_binding
2598 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002599
Christian Heimes141c5e82018-02-24 21:10:57 +01002600Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002601
Christian Heimes141c5e82018-02-24 21:10:57 +01002602Raise ValueError if the requested `cb_type` is not supported. Return bytes
2603of the data or None if the data is not available (e.g. before the handshake).
2604Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002605[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002606
Antoine Pitroud6494802011-07-21 01:11:30 +02002607static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002608_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2609 const char *cb_type)
2610/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002611{
Antoine Pitroud6494802011-07-21 01:11:30 +02002612 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002613 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002614
Christian Heimes141c5e82018-02-24 21:10:57 +01002615 if (strcmp(cb_type, "tls-unique") == 0) {
2616 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2617 /* if session is resumed XOR we are the client */
2618 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2619 }
2620 else {
2621 /* if a new session XOR we are the server */
2622 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2623 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002624 }
2625 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002626 PyErr_Format(
2627 PyExc_ValueError,
2628 "'%s' channel binding type not implemented",
2629 cb_type
2630 );
2631 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002632 }
2633
2634 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002635 if (len == 0)
2636 Py_RETURN_NONE;
2637
Christian Heimes141c5e82018-02-24 21:10:57 +01002638 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002639}
2640
Christian Heimes99a65702016-09-10 23:44:53 +02002641#ifdef OPENSSL_VERSION_1_1
2642
2643static SSL_SESSION*
2644_ssl_session_dup(SSL_SESSION *session) {
2645 SSL_SESSION *newsession = NULL;
2646 int slen;
2647 unsigned char *senc = NULL, *p;
2648 const unsigned char *const_p;
2649
2650 if (session == NULL) {
2651 PyErr_SetString(PyExc_ValueError, "Invalid session");
2652 goto error;
2653 }
2654
2655 /* get length */
2656 slen = i2d_SSL_SESSION(session, NULL);
2657 if (slen == 0 || slen > 0xFF00) {
2658 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2659 goto error;
2660 }
2661 if ((senc = PyMem_Malloc(slen)) == NULL) {
2662 PyErr_NoMemory();
2663 goto error;
2664 }
2665 p = senc;
2666 if (!i2d_SSL_SESSION(session, &p)) {
2667 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2668 goto error;
2669 }
2670 const_p = senc;
2671 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2672 if (session == NULL) {
2673 goto error;
2674 }
2675 PyMem_Free(senc);
2676 return newsession;
2677 error:
2678 if (senc != NULL) {
2679 PyMem_Free(senc);
2680 }
2681 return NULL;
2682}
2683#endif
2684
2685static PyObject *
2686PySSL_get_session(PySSLSocket *self, void *closure) {
2687 /* get_session can return sessions from a server-side connection,
2688 * it does not check for handshake done or client socket. */
2689 PySSLSession *pysess;
2690 SSL_SESSION *session;
2691
2692#ifdef OPENSSL_VERSION_1_1
2693 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2694 * https://github.com/openssl/openssl/issues/1550 */
2695 session = SSL_get0_session(self->ssl); /* borrowed reference */
2696 if (session == NULL) {
2697 Py_RETURN_NONE;
2698 }
2699 if ((session = _ssl_session_dup(session)) == NULL) {
2700 return NULL;
2701 }
2702#else
2703 session = SSL_get1_session(self->ssl);
2704 if (session == NULL) {
2705 Py_RETURN_NONE;
2706 }
2707#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002708 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002709 if (pysess == NULL) {
2710 SSL_SESSION_free(session);
2711 return NULL;
2712 }
2713
2714 assert(self->ctx);
2715 pysess->ctx = self->ctx;
2716 Py_INCREF(pysess->ctx);
2717 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002718 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002719 return (PyObject *)pysess;
2720}
2721
2722static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2723 void *closure)
2724 {
2725 PySSLSession *pysess;
2726#ifdef OPENSSL_VERSION_1_1
2727 SSL_SESSION *session;
2728#endif
2729 int result;
2730
2731 if (!PySSLSession_Check(value)) {
2732 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2733 return -1;
2734 }
2735 pysess = (PySSLSession *)value;
2736
2737 if (self->ctx->ctx != pysess->ctx->ctx) {
2738 PyErr_SetString(PyExc_ValueError,
2739 "Session refers to a different SSLContext.");
2740 return -1;
2741 }
2742 if (self->socket_type != PY_SSL_CLIENT) {
2743 PyErr_SetString(PyExc_ValueError,
2744 "Cannot set session for server-side SSLSocket.");
2745 return -1;
2746 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002747 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002748 PyErr_SetString(PyExc_ValueError,
2749 "Cannot set session after handshake.");
2750 return -1;
2751 }
2752#ifdef OPENSSL_VERSION_1_1
2753 /* duplicate session */
2754 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2755 return -1;
2756 }
2757 result = SSL_set_session(self->ssl, session);
2758 /* free duplicate, SSL_set_session() bumps ref count */
2759 SSL_SESSION_free(session);
2760#else
2761 result = SSL_set_session(self->ssl, pysess->session);
2762#endif
2763 if (result == 0) {
2764 _setSSLError(NULL, 0, __FILE__, __LINE__);
2765 return -1;
2766 }
2767 return 0;
2768}
2769
2770PyDoc_STRVAR(PySSL_set_session_doc,
2771"_setter_session(session)\n\
2772\
2773Get / set SSLSession.");
2774
2775static PyObject *
2776PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2777 if (SSL_session_reused(self->ssl)) {
2778 Py_RETURN_TRUE;
2779 } else {
2780 Py_RETURN_FALSE;
2781 }
2782}
2783
2784PyDoc_STRVAR(PySSL_get_session_reused_doc,
2785"Was the client session reused during handshake?");
2786
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002787static PyGetSetDef ssl_getsetlist[] = {
2788 {"context", (getter) PySSL_get_context,
2789 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002790 {"server_side", (getter) PySSL_get_server_side, NULL,
2791 PySSL_get_server_side_doc},
2792 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2793 PySSL_get_server_hostname_doc},
2794 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2795 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002796 {"session", (getter) PySSL_get_session,
2797 (setter) PySSL_set_session, PySSL_set_session_doc},
2798 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2799 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002800 {NULL}, /* sentinel */
2801};
2802
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002803static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002804 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2805 _SSL__SSLSOCKET_WRITE_METHODDEF
2806 _SSL__SSLSOCKET_READ_METHODDEF
2807 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002808 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2809 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002810 _SSL__SSLSOCKET_CIPHER_METHODDEF
2811 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2812 _SSL__SSLSOCKET_VERSION_METHODDEF
2813 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2814 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2815 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2816 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002817 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002818};
2819
Antoine Pitrou152efa22010-05-16 18:19:27 +00002820static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002821 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002822 "_ssl._SSLSocket", /*tp_name*/
2823 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002824 0, /*tp_itemsize*/
2825 /* methods */
2826 (destructor)PySSL_dealloc, /*tp_dealloc*/
2827 0, /*tp_print*/
2828 0, /*tp_getattr*/
2829 0, /*tp_setattr*/
2830 0, /*tp_reserved*/
2831 0, /*tp_repr*/
2832 0, /*tp_as_number*/
2833 0, /*tp_as_sequence*/
2834 0, /*tp_as_mapping*/
2835 0, /*tp_hash*/
2836 0, /*tp_call*/
2837 0, /*tp_str*/
2838 0, /*tp_getattro*/
2839 0, /*tp_setattro*/
2840 0, /*tp_as_buffer*/
2841 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2842 0, /*tp_doc*/
2843 0, /*tp_traverse*/
2844 0, /*tp_clear*/
2845 0, /*tp_richcompare*/
2846 0, /*tp_weaklistoffset*/
2847 0, /*tp_iter*/
2848 0, /*tp_iternext*/
2849 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002850 0, /*tp_members*/
2851 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002852};
2853
Antoine Pitrou152efa22010-05-16 18:19:27 +00002854
2855/*
2856 * _SSLContext objects
2857 */
2858
Christian Heimes5fe668c2016-09-12 00:01:11 +02002859static int
2860_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2861{
2862 int mode;
2863 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2864
2865 switch(n) {
2866 case PY_SSL_CERT_NONE:
2867 mode = SSL_VERIFY_NONE;
2868 break;
2869 case PY_SSL_CERT_OPTIONAL:
2870 mode = SSL_VERIFY_PEER;
2871 break;
2872 case PY_SSL_CERT_REQUIRED:
2873 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2874 break;
2875 default:
2876 PyErr_SetString(PyExc_ValueError,
2877 "invalid value for verify_mode");
2878 return -1;
2879 }
2880 /* keep current verify cb */
2881 verify_cb = SSL_CTX_get_verify_callback(ctx);
2882 SSL_CTX_set_verify(ctx, mode, verify_cb);
2883 return 0;
2884}
2885
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002886/*[clinic input]
2887@classmethod
2888_ssl._SSLContext.__new__
2889 protocol as proto_version: int
2890 /
2891[clinic start generated code]*/
2892
Antoine Pitrou152efa22010-05-16 18:19:27 +00002893static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002894_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2895/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002896{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002898 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002899 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002900 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002901 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002902#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002903 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002904#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002905
Antoine Pitrou152efa22010-05-16 18:19:27 +00002906 PySSL_BEGIN_ALLOW_THREADS
2907 if (proto_version == PY_SSL_VERSION_TLS1)
2908 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002909#if HAVE_TLSv1_2
2910 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2911 ctx = SSL_CTX_new(TLSv1_1_method());
2912 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2913 ctx = SSL_CTX_new(TLSv1_2_method());
2914#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002915#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002916 else if (proto_version == PY_SSL_VERSION_SSL3)
2917 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002918#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002919#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002920 else if (proto_version == PY_SSL_VERSION_SSL2)
2921 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002922#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002923 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002924 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002925 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2926 ctx = SSL_CTX_new(TLS_client_method());
2927 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2928 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002929 else
2930 proto_version = -1;
2931 PySSL_END_ALLOW_THREADS
2932
2933 if (proto_version == -1) {
2934 PyErr_SetString(PyExc_ValueError,
2935 "invalid protocol version");
2936 return NULL;
2937 }
2938 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002939 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002940 return NULL;
2941 }
2942
2943 assert(type != NULL && type->tp_alloc != NULL);
2944 self = (PySSLContext *) type->tp_alloc(type, 0);
2945 if (self == NULL) {
2946 SSL_CTX_free(ctx);
2947 return NULL;
2948 }
2949 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002950 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002951 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002952#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002953 self->npn_protocols = NULL;
2954#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002955#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002956 self->alpn_protocols = NULL;
2957#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002958#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002959 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002960#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002961 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002962 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2963 self->check_hostname = 1;
2964 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2965 Py_DECREF(self);
2966 return NULL;
2967 }
2968 } else {
2969 self->check_hostname = 0;
2970 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2971 Py_DECREF(self);
2972 return NULL;
2973 }
2974 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002975 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002976 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2977 if (proto_version != PY_SSL_VERSION_SSL2)
2978 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002979 if (proto_version != PY_SSL_VERSION_SSL3)
2980 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002981 /* Minimal security flags for server and client side context.
2982 * Client sockets ignore server-side parameters. */
2983#ifdef SSL_OP_NO_COMPRESSION
2984 options |= SSL_OP_NO_COMPRESSION;
2985#endif
2986#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2987 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2988#endif
2989#ifdef SSL_OP_SINGLE_DH_USE
2990 options |= SSL_OP_SINGLE_DH_USE;
2991#endif
2992#ifdef SSL_OP_SINGLE_ECDH_USE
2993 options |= SSL_OP_SINGLE_ECDH_USE;
2994#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002995 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002996
Semen Zhydenko1295e112017-10-15 21:28:31 +02002997 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002998 * It's far from perfect but gives users a better head start. */
2999 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01003000#if PY_SSL_DEFAULT_CIPHERS == 2
3001 /* stick to OpenSSL's default settings */
3002 result = 1;
3003#else
3004 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3005#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003006 } else {
3007 /* SSLv2 needs MD5 */
3008 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3009 }
3010 if (result == 0) {
3011 Py_DECREF(self);
3012 ERR_clear_error();
3013 PyErr_SetString(PySSLErrorObject,
3014 "No cipher can be selected.");
3015 return NULL;
3016 }
3017
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003018#if defined(SSL_MODE_RELEASE_BUFFERS)
3019 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3020 usage for no cost at all. However, don't do this for OpenSSL versions
3021 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3022 2014-0198. I can't find exactly which beta fixed this CVE, so be
3023 conservative and assume it wasn't fixed until release. We do this check
3024 at runtime to avoid problems from the dynamic linker.
3025 See #25672 for more on this. */
3026 libver = SSLeay();
3027 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3028 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3029 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3030 }
3031#endif
3032
3033
Donald Stufft8ae264c2017-03-02 11:45:29 -05003034#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003035 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3036 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003037 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3038 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003039#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003040 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3041#else
3042 {
3043 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3044 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3045 EC_KEY_free(key);
3046 }
3047#endif
3048#endif
3049
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003050#define SID_CTX "Python"
3051 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3052 sizeof(SID_CTX));
3053#undef SID_CTX
3054
Christian Heimes61d478c2018-01-27 15:51:38 +01003055 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003056#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003057 /* Improve trust chain building when cross-signed intermediate
3058 certificates are present. See https://bugs.python.org/issue23476. */
3059 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003060#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003061 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003062
Antoine Pitrou152efa22010-05-16 18:19:27 +00003063 return (PyObject *)self;
3064}
3065
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003066static int
3067context_traverse(PySSLContext *self, visitproc visit, void *arg)
3068{
3069#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003070 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003071#endif
3072 return 0;
3073}
3074
3075static int
3076context_clear(PySSLContext *self)
3077{
3078#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003079 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003080#endif
3081 return 0;
3082}
3083
Antoine Pitrou152efa22010-05-16 18:19:27 +00003084static void
3085context_dealloc(PySSLContext *self)
3086{
INADA Naokia6296d32017-08-24 14:55:17 +09003087 /* bpo-31095: UnTrack is needed before calling any callbacks */
3088 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003089 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003090 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003091#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003092 PyMem_FREE(self->npn_protocols);
3093#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003094#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003095 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003096#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003097 Py_TYPE(self)->tp_free(self);
3098}
3099
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003100/*[clinic input]
3101_ssl._SSLContext.set_ciphers
3102 cipherlist: str
3103 /
3104[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003105
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003106static PyObject *
3107_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3108/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3109{
3110 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003111 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003112 /* Clearing the error queue is necessary on some OpenSSL versions,
3113 otherwise the error will be reported again when another SSL call
3114 is done. */
3115 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003116 PyErr_SetString(PySSLErrorObject,
3117 "No cipher can be selected.");
3118 return NULL;
3119 }
3120 Py_RETURN_NONE;
3121}
3122
Christian Heimes25bfcd52016-09-06 00:04:45 +02003123#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3124/*[clinic input]
3125_ssl._SSLContext.get_ciphers
3126[clinic start generated code]*/
3127
3128static PyObject *
3129_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3130/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3131{
3132 SSL *ssl = NULL;
3133 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003134 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003135 int i=0;
3136 PyObject *result = NULL, *dct;
3137
3138 ssl = SSL_new(self->ctx);
3139 if (ssl == NULL) {
3140 _setSSLError(NULL, 0, __FILE__, __LINE__);
3141 goto exit;
3142 }
3143 sk = SSL_get_ciphers(ssl);
3144
3145 result = PyList_New(sk_SSL_CIPHER_num(sk));
3146 if (result == NULL) {
3147 goto exit;
3148 }
3149
3150 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3151 cipher = sk_SSL_CIPHER_value(sk, i);
3152 dct = cipher_to_dict(cipher);
3153 if (dct == NULL) {
3154 Py_CLEAR(result);
3155 goto exit;
3156 }
3157 PyList_SET_ITEM(result, i, dct);
3158 }
3159
3160 exit:
3161 if (ssl != NULL)
3162 SSL_free(ssl);
3163 return result;
3164
3165}
3166#endif
3167
3168
Christian Heimes29eab552018-02-25 12:31:33 +01003169#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003170static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003171do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3172 const unsigned char *server_protocols, unsigned int server_protocols_len,
3173 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003174{
Benjamin Peterson88615022015-01-23 17:30:26 -05003175 int ret;
3176 if (client_protocols == NULL) {
3177 client_protocols = (unsigned char *)"";
3178 client_protocols_len = 0;
3179 }
3180 if (server_protocols == NULL) {
3181 server_protocols = (unsigned char *)"";
3182 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003183 }
3184
Benjamin Peterson88615022015-01-23 17:30:26 -05003185 ret = SSL_select_next_proto(out, outlen,
3186 server_protocols, server_protocols_len,
3187 client_protocols, client_protocols_len);
3188 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3189 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003190
3191 return SSL_TLSEXT_ERR_OK;
3192}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003193#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003194
Christian Heimes29eab552018-02-25 12:31:33 +01003195#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003196/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3197static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003198_advertiseNPN_cb(SSL *s,
3199 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003200 void *args)
3201{
3202 PySSLContext *ssl_ctx = (PySSLContext *) args;
3203
3204 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003205 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003206 *len = 0;
3207 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003208 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003209 *len = ssl_ctx->npn_protocols_len;
3210 }
3211
3212 return SSL_TLSEXT_ERR_OK;
3213}
3214/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3215static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003216_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003217 unsigned char **out, unsigned char *outlen,
3218 const unsigned char *server, unsigned int server_len,
3219 void *args)
3220{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003221 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003222 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003223 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003224}
3225#endif
3226
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003227/*[clinic input]
3228_ssl._SSLContext._set_npn_protocols
3229 protos: Py_buffer
3230 /
3231[clinic start generated code]*/
3232
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003233static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003234_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3235 Py_buffer *protos)
3236/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003237{
Christian Heimes29eab552018-02-25 12:31:33 +01003238#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003239 PyMem_Free(self->npn_protocols);
3240 self->npn_protocols = PyMem_Malloc(protos->len);
3241 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003242 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003243 memcpy(self->npn_protocols, protos->buf, protos->len);
3244 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003245
3246 /* set both server and client callbacks, because the context can
3247 * be used to create both types of sockets */
3248 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3249 _advertiseNPN_cb,
3250 self);
3251 SSL_CTX_set_next_proto_select_cb(self->ctx,
3252 _selectNPN_cb,
3253 self);
3254
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003255 Py_RETURN_NONE;
3256#else
3257 PyErr_SetString(PyExc_NotImplementedError,
3258 "The NPN extension requires OpenSSL 1.0.1 or later.");
3259 return NULL;
3260#endif
3261}
3262
Christian Heimes29eab552018-02-25 12:31:33 +01003263#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003264static int
3265_selectALPN_cb(SSL *s,
3266 const unsigned char **out, unsigned char *outlen,
3267 const unsigned char *client_protocols, unsigned int client_protocols_len,
3268 void *args)
3269{
3270 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003271 return do_protocol_selection(1, (unsigned char **)out, outlen,
3272 ctx->alpn_protocols, ctx->alpn_protocols_len,
3273 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003274}
3275#endif
3276
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003277/*[clinic input]
3278_ssl._SSLContext._set_alpn_protocols
3279 protos: Py_buffer
3280 /
3281[clinic start generated code]*/
3282
Benjamin Petersoncca27322015-01-23 16:35:37 -05003283static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003284_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3285 Py_buffer *protos)
3286/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003287{
Christian Heimes29eab552018-02-25 12:31:33 +01003288#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003289 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003290 PyErr_Format(PyExc_OverflowError,
3291 "protocols longer than %d bytes", UINT_MAX);
3292 return NULL;
3293 }
3294
Benjamin Petersoncca27322015-01-23 16:35:37 -05003295 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003296 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003297 if (!self->alpn_protocols)
3298 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003299 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003300 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003301
3302 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3303 return PyErr_NoMemory();
3304 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3305
Benjamin Petersoncca27322015-01-23 16:35:37 -05003306 Py_RETURN_NONE;
3307#else
3308 PyErr_SetString(PyExc_NotImplementedError,
3309 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3310 return NULL;
3311#endif
3312}
3313
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314static PyObject *
3315get_verify_mode(PySSLContext *self, void *c)
3316{
3317 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3318 case SSL_VERIFY_NONE:
3319 return PyLong_FromLong(PY_SSL_CERT_NONE);
3320 case SSL_VERIFY_PEER:
3321 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3322 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3323 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3324 }
3325 PyErr_SetString(PySSLErrorObject,
3326 "invalid return value from SSL_CTX_get_verify_mode");
3327 return NULL;
3328}
3329
3330static int
3331set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3332{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003333 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003334 if (!PyArg_Parse(arg, "i", &n))
3335 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003336 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003337 PyErr_SetString(PyExc_ValueError,
3338 "Cannot set verify_mode to CERT_NONE when "
3339 "check_hostname is enabled.");
3340 return -1;
3341 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003342 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003343}
3344
3345static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003346get_verify_flags(PySSLContext *self, void *c)
3347{
Christian Heimes598894f2016-09-05 23:19:05 +02003348 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003349 unsigned long flags;
3350
Christian Heimes61d478c2018-01-27 15:51:38 +01003351 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003352 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003353 return PyLong_FromUnsignedLong(flags);
3354}
3355
3356static int
3357set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3358{
Christian Heimes598894f2016-09-05 23:19:05 +02003359 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003360 unsigned long new_flags, flags, set, clear;
3361
3362 if (!PyArg_Parse(arg, "k", &new_flags))
3363 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003364 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003365 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003366 clear = flags & ~new_flags;
3367 set = ~flags & new_flags;
3368 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003369 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003370 _setSSLError(NULL, 0, __FILE__, __LINE__);
3371 return -1;
3372 }
3373 }
3374 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003375 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003376 _setSSLError(NULL, 0, __FILE__, __LINE__);
3377 return -1;
3378 }
3379 }
3380 return 0;
3381}
3382
Christian Heimes698dde12018-02-27 11:54:43 +01003383/* Getter and setter for protocol version */
3384#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3385
3386
3387static int
3388set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3389{
3390 long v;
3391 int result;
3392
3393 if (!PyArg_Parse(arg, "l", &v))
3394 return -1;
3395 if (v > INT_MAX) {
3396 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3397 return -1;
3398 }
3399
3400 switch(self->protocol) {
3401 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3402 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3403 case PY_SSL_VERSION_TLS:
3404 break;
3405 default:
3406 PyErr_SetString(
3407 PyExc_ValueError,
3408 "The context's protocol doesn't support modification of "
3409 "highest and lowest version."
3410 );
3411 return -1;
3412 }
3413
3414 if (what == 0) {
3415 switch(v) {
3416 case PY_PROTO_MINIMUM_SUPPORTED:
3417 v = 0;
3418 break;
3419 case PY_PROTO_MAXIMUM_SUPPORTED:
3420 /* Emulate max for set_min_proto_version */
3421 v = PY_PROTO_MAXIMUM_AVAILABLE;
3422 break;
3423 default:
3424 break;
3425 }
3426 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3427 }
3428 else {
3429 switch(v) {
3430 case PY_PROTO_MAXIMUM_SUPPORTED:
3431 v = 0;
3432 break;
3433 case PY_PROTO_MINIMUM_SUPPORTED:
3434 /* Emulate max for set_min_proto_version */
3435 v = PY_PROTO_MINIMUM_AVAILABLE;
3436 break;
3437 default:
3438 break;
3439 }
3440 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3441 }
3442 if (result == 0) {
3443 PyErr_Format(PyExc_ValueError,
3444 "Unsupported protocol version 0x%x", v);
3445 return -1;
3446 }
3447 return 0;
3448}
3449
3450static PyObject *
3451get_minimum_version(PySSLContext *self, void *c)
3452{
3453 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3454 if (v == 0) {
3455 v = PY_PROTO_MINIMUM_SUPPORTED;
3456 }
3457 return PyLong_FromLong(v);
3458}
3459
3460static int
3461set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3462{
3463 return set_min_max_proto_version(self, arg, 0);
3464}
3465
3466static PyObject *
3467get_maximum_version(PySSLContext *self, void *c)
3468{
3469 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3470 if (v == 0) {
3471 v = PY_PROTO_MAXIMUM_SUPPORTED;
3472 }
3473 return PyLong_FromLong(v);
3474}
3475
3476static int
3477set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3478{
3479 return set_min_max_proto_version(self, arg, 1);
3480}
3481#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3482
Christian Heimes22587792013-11-21 23:56:13 +01003483static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003484get_options(PySSLContext *self, void *c)
3485{
3486 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3487}
3488
3489static int
3490set_options(PySSLContext *self, PyObject *arg, void *c)
3491{
3492 long new_opts, opts, set, clear;
3493 if (!PyArg_Parse(arg, "l", &new_opts))
3494 return -1;
3495 opts = SSL_CTX_get_options(self->ctx);
3496 clear = opts & ~new_opts;
3497 set = ~opts & new_opts;
3498 if (clear) {
3499#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3500 SSL_CTX_clear_options(self->ctx, clear);
3501#else
3502 PyErr_SetString(PyExc_ValueError,
3503 "can't clear options before OpenSSL 0.9.8m");
3504 return -1;
3505#endif
3506 }
3507 if (set)
3508 SSL_CTX_set_options(self->ctx, set);
3509 return 0;
3510}
3511
Christian Heimes1aa9a752013-12-02 02:41:19 +01003512static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003513get_host_flags(PySSLContext *self, void *c)
3514{
3515 return PyLong_FromUnsignedLong(self->hostflags);
3516}
3517
3518static int
3519set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3520{
3521 X509_VERIFY_PARAM *param;
3522 unsigned int new_flags = 0;
3523
3524 if (!PyArg_Parse(arg, "I", &new_flags))
3525 return -1;
3526
3527 param = SSL_CTX_get0_param(self->ctx);
3528 self->hostflags = new_flags;
3529 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3530 return 0;
3531}
3532
3533static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003534get_check_hostname(PySSLContext *self, void *c)
3535{
3536 return PyBool_FromLong(self->check_hostname);
3537}
3538
3539static int
3540set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3541{
3542 int check_hostname;
3543 if (!PyArg_Parse(arg, "p", &check_hostname))
3544 return -1;
3545 if (check_hostname &&
3546 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003547 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3548 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3549 return -1;
3550 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003551 }
3552 self->check_hostname = check_hostname;
3553 return 0;
3554}
3555
Christian Heimes11a14932018-02-24 02:35:08 +01003556static PyObject *
3557get_protocol(PySSLContext *self, void *c) {
3558 return PyLong_FromLong(self->protocol);
3559}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003560
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003561typedef struct {
3562 PyThreadState *thread_state;
3563 PyObject *callable;
3564 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003565 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003566 int error;
3567} _PySSLPasswordInfo;
3568
3569static int
3570_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3571 const char *bad_type_error)
3572{
3573 /* Set the password and size fields of a _PySSLPasswordInfo struct
3574 from a unicode, bytes, or byte array object.
3575 The password field will be dynamically allocated and must be freed
3576 by the caller */
3577 PyObject *password_bytes = NULL;
3578 const char *data = NULL;
3579 Py_ssize_t size;
3580
3581 if (PyUnicode_Check(password)) {
3582 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3583 if (!password_bytes) {
3584 goto error;
3585 }
3586 data = PyBytes_AS_STRING(password_bytes);
3587 size = PyBytes_GET_SIZE(password_bytes);
3588 } else if (PyBytes_Check(password)) {
3589 data = PyBytes_AS_STRING(password);
3590 size = PyBytes_GET_SIZE(password);
3591 } else if (PyByteArray_Check(password)) {
3592 data = PyByteArray_AS_STRING(password);
3593 size = PyByteArray_GET_SIZE(password);
3594 } else {
3595 PyErr_SetString(PyExc_TypeError, bad_type_error);
3596 goto error;
3597 }
3598
Victor Stinner9ee02032013-06-23 15:08:23 +02003599 if (size > (Py_ssize_t)INT_MAX) {
3600 PyErr_Format(PyExc_ValueError,
3601 "password cannot be longer than %d bytes", INT_MAX);
3602 goto error;
3603 }
3604
Victor Stinner11ebff22013-07-07 17:07:52 +02003605 PyMem_Free(pw_info->password);
3606 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003607 if (!pw_info->password) {
3608 PyErr_SetString(PyExc_MemoryError,
3609 "unable to allocate password buffer");
3610 goto error;
3611 }
3612 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003613 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003614
3615 Py_XDECREF(password_bytes);
3616 return 1;
3617
3618error:
3619 Py_XDECREF(password_bytes);
3620 return 0;
3621}
3622
3623static int
3624_password_callback(char *buf, int size, int rwflag, void *userdata)
3625{
3626 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3627 PyObject *fn_ret = NULL;
3628
3629 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3630
3631 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003632 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003633 if (!fn_ret) {
3634 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3635 core python API, so we could use it to add a frame here */
3636 goto error;
3637 }
3638
3639 if (!_pwinfo_set(pw_info, fn_ret,
3640 "password callback must return a string")) {
3641 goto error;
3642 }
3643 Py_CLEAR(fn_ret);
3644 }
3645
3646 if (pw_info->size > size) {
3647 PyErr_Format(PyExc_ValueError,
3648 "password cannot be longer than %d bytes", size);
3649 goto error;
3650 }
3651
3652 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3653 memcpy(buf, pw_info->password, pw_info->size);
3654 return pw_info->size;
3655
3656error:
3657 Py_XDECREF(fn_ret);
3658 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3659 pw_info->error = 1;
3660 return -1;
3661}
3662
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003663/*[clinic input]
3664_ssl._SSLContext.load_cert_chain
3665 certfile: object
3666 keyfile: object = NULL
3667 password: object = NULL
3668
3669[clinic start generated code]*/
3670
Antoine Pitroub5218772010-05-21 09:56:06 +00003671static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003672_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3673 PyObject *keyfile, PyObject *password)
3674/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003675{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003676 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003677 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3678 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003679 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003680 int r;
3681
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003682 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003683 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003684 if (keyfile == Py_None)
3685 keyfile = NULL;
3686 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3687 PyErr_SetString(PyExc_TypeError,
3688 "certfile should be a valid filesystem path");
3689 return NULL;
3690 }
3691 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3692 PyErr_SetString(PyExc_TypeError,
3693 "keyfile should be a valid filesystem path");
3694 goto error;
3695 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003696 if (password && password != Py_None) {
3697 if (PyCallable_Check(password)) {
3698 pw_info.callable = password;
3699 } else if (!_pwinfo_set(&pw_info, password,
3700 "password should be a string or callable")) {
3701 goto error;
3702 }
3703 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3704 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3705 }
3706 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003707 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3708 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003709 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003710 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003711 if (pw_info.error) {
3712 ERR_clear_error();
3713 /* the password callback has already set the error information */
3714 }
3715 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003716 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003717 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003718 }
3719 else {
3720 _setSSLError(NULL, 0, __FILE__, __LINE__);
3721 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003722 goto error;
3723 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003724 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003725 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003726 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3727 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003728 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3729 Py_CLEAR(keyfile_bytes);
3730 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003731 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003732 if (pw_info.error) {
3733 ERR_clear_error();
3734 /* the password callback has already set the error information */
3735 }
3736 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003737 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003738 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003739 }
3740 else {
3741 _setSSLError(NULL, 0, __FILE__, __LINE__);
3742 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003743 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003744 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003745 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003746 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003747 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003748 if (r != 1) {
3749 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003750 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003751 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003752 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3753 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003754 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003755 Py_RETURN_NONE;
3756
3757error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003758 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3759 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003760 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003761 Py_XDECREF(keyfile_bytes);
3762 Py_XDECREF(certfile_bytes);
3763 return NULL;
3764}
3765
Christian Heimesefff7062013-11-21 03:35:02 +01003766/* internal helper function, returns -1 on error
3767 */
3768static int
3769_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3770 int filetype)
3771{
3772 BIO *biobuf = NULL;
3773 X509_STORE *store;
3774 int retval = 0, err, loaded = 0;
3775
3776 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3777
3778 if (len <= 0) {
3779 PyErr_SetString(PyExc_ValueError,
3780 "Empty certificate data");
3781 return -1;
3782 } else if (len > INT_MAX) {
3783 PyErr_SetString(PyExc_OverflowError,
3784 "Certificate data is too long.");
3785 return -1;
3786 }
3787
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003788 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003789 if (biobuf == NULL) {
3790 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3791 return -1;
3792 }
3793
3794 store = SSL_CTX_get_cert_store(self->ctx);
3795 assert(store != NULL);
3796
3797 while (1) {
3798 X509 *cert = NULL;
3799 int r;
3800
3801 if (filetype == SSL_FILETYPE_ASN1) {
3802 cert = d2i_X509_bio(biobuf, NULL);
3803 } else {
3804 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003805 SSL_CTX_get_default_passwd_cb(self->ctx),
3806 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3807 );
Christian Heimesefff7062013-11-21 03:35:02 +01003808 }
3809 if (cert == NULL) {
3810 break;
3811 }
3812 r = X509_STORE_add_cert(store, cert);
3813 X509_free(cert);
3814 if (!r) {
3815 err = ERR_peek_last_error();
3816 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3817 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3818 /* cert already in hash table, not an error */
3819 ERR_clear_error();
3820 } else {
3821 break;
3822 }
3823 }
3824 loaded++;
3825 }
3826
3827 err = ERR_peek_last_error();
3828 if ((filetype == SSL_FILETYPE_ASN1) &&
3829 (loaded > 0) &&
3830 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3831 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3832 /* EOF ASN1 file, not an error */
3833 ERR_clear_error();
3834 retval = 0;
3835 } else if ((filetype == SSL_FILETYPE_PEM) &&
3836 (loaded > 0) &&
3837 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3838 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3839 /* EOF PEM file, not an error */
3840 ERR_clear_error();
3841 retval = 0;
3842 } else {
3843 _setSSLError(NULL, 0, __FILE__, __LINE__);
3844 retval = -1;
3845 }
3846
3847 BIO_free(biobuf);
3848 return retval;
3849}
3850
3851
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003852/*[clinic input]
3853_ssl._SSLContext.load_verify_locations
3854 cafile: object = NULL
3855 capath: object = NULL
3856 cadata: object = NULL
3857
3858[clinic start generated code]*/
3859
Antoine Pitrou152efa22010-05-16 18:19:27 +00003860static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003861_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3862 PyObject *cafile,
3863 PyObject *capath,
3864 PyObject *cadata)
3865/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003866{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003867 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3868 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003869 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003870
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003871 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003872 if (cafile == Py_None)
3873 cafile = NULL;
3874 if (capath == Py_None)
3875 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003876 if (cadata == Py_None)
3877 cadata = NULL;
3878
3879 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003880 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003881 "cafile, capath and cadata cannot be all omitted");
3882 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003883 }
3884 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3885 PyErr_SetString(PyExc_TypeError,
3886 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003887 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003888 }
3889 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003890 PyErr_SetString(PyExc_TypeError,
3891 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003892 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003893 }
Christian Heimesefff7062013-11-21 03:35:02 +01003894
3895 /* validata cadata type and load cadata */
3896 if (cadata) {
3897 Py_buffer buf;
3898 PyObject *cadata_ascii = NULL;
3899
3900 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3901 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3902 PyBuffer_Release(&buf);
3903 PyErr_SetString(PyExc_TypeError,
3904 "cadata should be a contiguous buffer with "
3905 "a single dimension");
3906 goto error;
3907 }
3908 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3909 PyBuffer_Release(&buf);
3910 if (r == -1) {
3911 goto error;
3912 }
3913 } else {
3914 PyErr_Clear();
3915 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3916 if (cadata_ascii == NULL) {
3917 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003918 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003919 "bytes-like object");
3920 goto error;
3921 }
3922 r = _add_ca_certs(self,
3923 PyBytes_AS_STRING(cadata_ascii),
3924 PyBytes_GET_SIZE(cadata_ascii),
3925 SSL_FILETYPE_PEM);
3926 Py_DECREF(cadata_ascii);
3927 if (r == -1) {
3928 goto error;
3929 }
3930 }
3931 }
3932
3933 /* load cafile or capath */
3934 if (cafile || capath) {
3935 if (cafile)
3936 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3937 if (capath)
3938 capath_buf = PyBytes_AS_STRING(capath_bytes);
3939 PySSL_BEGIN_ALLOW_THREADS
3940 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3941 PySSL_END_ALLOW_THREADS
3942 if (r != 1) {
3943 ok = 0;
3944 if (errno != 0) {
3945 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003946 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003947 }
3948 else {
3949 _setSSLError(NULL, 0, __FILE__, __LINE__);
3950 }
3951 goto error;
3952 }
3953 }
3954 goto end;
3955
3956 error:
3957 ok = 0;
3958 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003959 Py_XDECREF(cafile_bytes);
3960 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003961 if (ok) {
3962 Py_RETURN_NONE;
3963 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003964 return NULL;
3965 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003966}
3967
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003968/*[clinic input]
3969_ssl._SSLContext.load_dh_params
3970 path as filepath: object
3971 /
3972
3973[clinic start generated code]*/
3974
Antoine Pitrou152efa22010-05-16 18:19:27 +00003975static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003976_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3977/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003978{
3979 FILE *f;
3980 DH *dh;
3981
Victor Stinnerdaf45552013-08-28 00:53:59 +02003982 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003983 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003984 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003985
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003986 errno = 0;
3987 PySSL_BEGIN_ALLOW_THREADS
3988 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003989 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003990 PySSL_END_ALLOW_THREADS
3991 if (dh == NULL) {
3992 if (errno != 0) {
3993 ERR_clear_error();
3994 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3995 }
3996 else {
3997 _setSSLError(NULL, 0, __FILE__, __LINE__);
3998 }
3999 return NULL;
4000 }
4001 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4002 _setSSLError(NULL, 0, __FILE__, __LINE__);
4003 DH_free(dh);
4004 Py_RETURN_NONE;
4005}
4006
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004007/*[clinic input]
4008_ssl._SSLContext._wrap_socket
4009 sock: object(subclass_of="PySocketModule.Sock_Type")
4010 server_side: int
4011 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004012 *
4013 owner: object = None
4014 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004015
4016[clinic start generated code]*/
4017
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004018static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004019_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004020 int server_side, PyObject *hostname_obj,
4021 PyObject *owner, PyObject *session)
4022/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023{
Antoine Pitroud5323212010-10-22 18:19:07 +00004024 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004025 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004026
Antoine Pitroud5323212010-10-22 18:19:07 +00004027 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01004028 as IDN A-label (ASCII str). */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004029 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004030 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004031 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004032 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004033
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004034 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4035 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004036 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004037 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004038 if (hostname != NULL)
4039 PyMem_Free(hostname);
4040 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004041}
4042
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004043/*[clinic input]
4044_ssl._SSLContext._wrap_bio
4045 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4046 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4047 server_side: int
4048 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004049 *
4050 owner: object = None
4051 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004052
4053[clinic start generated code]*/
4054
Antoine Pitroub0182c82010-10-12 20:09:02 +00004055static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004056_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4057 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004058 PyObject *hostname_obj, PyObject *owner,
4059 PyObject *session)
4060/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004061{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004062 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004063 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004064
4065 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01004066 as IDN A-label (ASCII str). */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004068 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004069 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070 }
4071
4072 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004073 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004074 incoming, outgoing);
4075
4076 PyMem_Free(hostname);
4077 return res;
4078}
4079
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004080/*[clinic input]
4081_ssl._SSLContext.session_stats
4082[clinic start generated code]*/
4083
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004084static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004085_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4086/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004087{
4088 int r;
4089 PyObject *value, *stats = PyDict_New();
4090 if (!stats)
4091 return NULL;
4092
4093#define ADD_STATS(SSL_NAME, KEY_NAME) \
4094 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4095 if (value == NULL) \
4096 goto error; \
4097 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4098 Py_DECREF(value); \
4099 if (r < 0) \
4100 goto error;
4101
4102 ADD_STATS(number, "number");
4103 ADD_STATS(connect, "connect");
4104 ADD_STATS(connect_good, "connect_good");
4105 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4106 ADD_STATS(accept, "accept");
4107 ADD_STATS(accept_good, "accept_good");
4108 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4109 ADD_STATS(accept, "accept");
4110 ADD_STATS(hits, "hits");
4111 ADD_STATS(misses, "misses");
4112 ADD_STATS(timeouts, "timeouts");
4113 ADD_STATS(cache_full, "cache_full");
4114
4115#undef ADD_STATS
4116
4117 return stats;
4118
4119error:
4120 Py_DECREF(stats);
4121 return NULL;
4122}
4123
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004124/*[clinic input]
4125_ssl._SSLContext.set_default_verify_paths
4126[clinic start generated code]*/
4127
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004128static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004129_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4130/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004131{
4132 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4133 _setSSLError(NULL, 0, __FILE__, __LINE__);
4134 return NULL;
4135 }
4136 Py_RETURN_NONE;
4137}
4138
Antoine Pitrou501da612011-12-21 09:27:41 +01004139#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004140/*[clinic input]
4141_ssl._SSLContext.set_ecdh_curve
4142 name: object
4143 /
4144
4145[clinic start generated code]*/
4146
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004147static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004148_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4149/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004150{
4151 PyObject *name_bytes;
4152 int nid;
4153 EC_KEY *key;
4154
4155 if (!PyUnicode_FSConverter(name, &name_bytes))
4156 return NULL;
4157 assert(PyBytes_Check(name_bytes));
4158 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4159 Py_DECREF(name_bytes);
4160 if (nid == 0) {
4161 PyErr_Format(PyExc_ValueError,
4162 "unknown elliptic curve name %R", name);
4163 return NULL;
4164 }
4165 key = EC_KEY_new_by_curve_name(nid);
4166 if (key == NULL) {
4167 _setSSLError(NULL, 0, __FILE__, __LINE__);
4168 return NULL;
4169 }
4170 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4171 EC_KEY_free(key);
4172 Py_RETURN_NONE;
4173}
Antoine Pitrou501da612011-12-21 09:27:41 +01004174#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004175
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004176#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004177static int
4178_servername_callback(SSL *s, int *al, void *args)
4179{
4180 int ret;
4181 PySSLContext *ssl_ctx = (PySSLContext *) args;
4182 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004183 PyObject *result;
4184 /* The high-level ssl.SSLSocket object */
4185 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004186 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004187 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004188
Christian Heimes11a14932018-02-24 02:35:08 +01004189 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004190 /* remove race condition in this the call back while if removing the
4191 * callback is in progress */
4192 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004193 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004194 }
4195
4196 ssl = SSL_get_app_data(s);
4197 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004199 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004200 * SSL connection and that has a .context attribute that can be changed to
4201 * identify the requested hostname. Since the official API is the Python
4202 * level API we want to pass the callback a Python level object rather than
4203 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4204 * SSLObject) that will be passed. Otherwise if there's a socket then that
4205 * will be passed. If both do not exist only then the C-level object is
4206 * passed. */
4207 if (ssl->owner)
4208 ssl_socket = PyWeakref_GetObject(ssl->owner);
4209 else if (ssl->Socket)
4210 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4211 else
4212 ssl_socket = (PyObject *) ssl;
4213
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004214 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004215 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004216 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004217
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004218 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004219 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004220 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004221 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004222 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004223 PyObject *servername_bytes;
4224 PyObject *servername_str;
4225
4226 servername_bytes = PyBytes_FromString(servername);
4227 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004228 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4229 goto error;
4230 }
Christian Heimes11a14932018-02-24 02:35:08 +01004231 /* server_hostname was encoded to an A-label by our caller; put it
4232 * back into a str object, but still as an A-label (bpo-28414)
4233 */
4234 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4235 Py_DECREF(servername_bytes);
4236 if (servername_str == NULL) {
4237 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004238 goto error;
4239 }
Christian Heimes11a14932018-02-24 02:35:08 +01004240 result = PyObject_CallFunctionObjArgs(
4241 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4242 ssl_ctx, NULL);
4243 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004244 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004245 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004246
4247 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004248 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004249 *al = SSL_AD_HANDSHAKE_FAILURE;
4250 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4251 }
4252 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004253 /* Result may be None, a SSLContext or an integer
4254 * None and SSLContext are OK, integer or other values are an error.
4255 */
4256 if (result == Py_None) {
4257 ret = SSL_TLSEXT_ERR_OK;
4258 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004259 *al = (int) PyLong_AsLong(result);
4260 if (PyErr_Occurred()) {
4261 PyErr_WriteUnraisable(result);
4262 *al = SSL_AD_INTERNAL_ERROR;
4263 }
4264 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4265 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004266 Py_DECREF(result);
4267 }
4268
4269 PyGILState_Release(gstate);
4270 return ret;
4271
4272error:
4273 Py_DECREF(ssl_socket);
4274 *al = SSL_AD_INTERNAL_ERROR;
4275 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4276 PyGILState_Release(gstate);
4277 return ret;
4278}
Antoine Pitroua5963382013-03-30 16:39:00 +01004279#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004280
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004281static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004282get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004283{
Christian Heimes11a14932018-02-24 02:35:08 +01004284 PyObject *cb = self->set_sni_cb;
4285 if (cb == NULL) {
4286 Py_RETURN_NONE;
4287 }
4288 Py_INCREF(cb);
4289 return cb;
4290}
4291
4292static int
4293set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4294{
4295 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4296 PyErr_SetString(PyExc_ValueError,
4297 "sni_callback cannot be set on TLS_CLIENT context");
4298 return -1;
4299 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004300#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004301 Py_CLEAR(self->set_sni_cb);
4302 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004303 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4304 }
4305 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004306 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004307 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4308 PyErr_SetString(PyExc_TypeError,
4309 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004310 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004311 }
Christian Heimes11a14932018-02-24 02:35:08 +01004312 Py_INCREF(arg);
4313 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004314 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4315 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4316 }
Christian Heimes11a14932018-02-24 02:35:08 +01004317 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004318#else
4319 PyErr_SetString(PyExc_NotImplementedError,
4320 "The TLS extension servername callback, "
4321 "SSL_CTX_set_tlsext_servername_callback, "
4322 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004323 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004324#endif
4325}
4326
Christian Heimes11a14932018-02-24 02:35:08 +01004327PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4328"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4329\n\
4330If the argument is None then the callback is disabled. The method is called\n\
4331with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4332See RFC 6066 for details of the SNI extension.");
4333
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004334/*[clinic input]
4335_ssl._SSLContext.cert_store_stats
4336
4337Returns quantities of loaded X.509 certificates.
4338
4339X.509 certificates with a CA extension and certificate revocation lists
4340inside the context's cert store.
4341
4342NOTE: Certificates in a capath directory aren't loaded unless they have
4343been used at least once.
4344[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004345
4346static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004347_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4348/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004349{
4350 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004351 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004352 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004353 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004354
4355 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004356 objs = X509_STORE_get0_objects(store);
4357 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4358 obj = sk_X509_OBJECT_value(objs, i);
4359 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004360 case X509_LU_X509:
4361 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004362 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004363 ca++;
4364 }
4365 break;
4366 case X509_LU_CRL:
4367 crl++;
4368 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004369 default:
4370 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4371 * As far as I can tell they are internal states and never
4372 * stored in a cert store */
4373 break;
4374 }
4375 }
4376 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4377 "x509_ca", ca);
4378}
4379
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004380/*[clinic input]
4381_ssl._SSLContext.get_ca_certs
4382 binary_form: bool = False
4383
4384Returns a list of dicts with information of loaded CA certs.
4385
4386If the optional argument is True, returns a DER-encoded copy of the CA
4387certificate.
4388
4389NOTE: Certificates in a capath directory aren't loaded unless they have
4390been used at least once.
4391[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004392
4393static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004394_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4395/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004396{
4397 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004398 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004399 PyObject *ci = NULL, *rlist = NULL;
4400 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004401
4402 if ((rlist = PyList_New(0)) == NULL) {
4403 return NULL;
4404 }
4405
4406 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004407 objs = X509_STORE_get0_objects(store);
4408 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004409 X509_OBJECT *obj;
4410 X509 *cert;
4411
Christian Heimes598894f2016-09-05 23:19:05 +02004412 obj = sk_X509_OBJECT_value(objs, i);
4413 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004414 /* not a x509 cert */
4415 continue;
4416 }
4417 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004418 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004419 if (!X509_check_ca(cert)) {
4420 continue;
4421 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004422 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004423 ci = _certificate_to_der(cert);
4424 } else {
4425 ci = _decode_certificate(cert);
4426 }
4427 if (ci == NULL) {
4428 goto error;
4429 }
4430 if (PyList_Append(rlist, ci) == -1) {
4431 goto error;
4432 }
4433 Py_CLEAR(ci);
4434 }
4435 return rlist;
4436
4437 error:
4438 Py_XDECREF(ci);
4439 Py_XDECREF(rlist);
4440 return NULL;
4441}
4442
4443
Antoine Pitrou152efa22010-05-16 18:19:27 +00004444static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004445 {"check_hostname", (getter) get_check_hostname,
4446 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004447 {"_host_flags", (getter) get_host_flags,
4448 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004449#if SSL_CTRL_GET_MAX_PROTO_VERSION
4450 {"minimum_version", (getter) get_minimum_version,
4451 (setter) set_minimum_version, NULL},
4452 {"maximum_version", (getter) get_maximum_version,
4453 (setter) set_maximum_version, NULL},
4454#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004455 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004456 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004457 {"options", (getter) get_options,
4458 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004459 {"protocol", (getter) get_protocol,
4460 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004461 {"verify_flags", (getter) get_verify_flags,
4462 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004463 {"verify_mode", (getter) get_verify_mode,
4464 (setter) set_verify_mode, NULL},
4465 {NULL}, /* sentinel */
4466};
4467
4468static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004469 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4470 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4471 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4472 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4473 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4474 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4475 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4476 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4477 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4478 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4479 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4481 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004482 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004483 {NULL, NULL} /* sentinel */
4484};
4485
4486static PyTypeObject PySSLContext_Type = {
4487 PyVarObject_HEAD_INIT(NULL, 0)
4488 "_ssl._SSLContext", /*tp_name*/
4489 sizeof(PySSLContext), /*tp_basicsize*/
4490 0, /*tp_itemsize*/
4491 (destructor)context_dealloc, /*tp_dealloc*/
4492 0, /*tp_print*/
4493 0, /*tp_getattr*/
4494 0, /*tp_setattr*/
4495 0, /*tp_reserved*/
4496 0, /*tp_repr*/
4497 0, /*tp_as_number*/
4498 0, /*tp_as_sequence*/
4499 0, /*tp_as_mapping*/
4500 0, /*tp_hash*/
4501 0, /*tp_call*/
4502 0, /*tp_str*/
4503 0, /*tp_getattro*/
4504 0, /*tp_setattro*/
4505 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004506 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004507 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004508 (traverseproc) context_traverse, /*tp_traverse*/
4509 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004510 0, /*tp_richcompare*/
4511 0, /*tp_weaklistoffset*/
4512 0, /*tp_iter*/
4513 0, /*tp_iternext*/
4514 context_methods, /*tp_methods*/
4515 0, /*tp_members*/
4516 context_getsetlist, /*tp_getset*/
4517 0, /*tp_base*/
4518 0, /*tp_dict*/
4519 0, /*tp_descr_get*/
4520 0, /*tp_descr_set*/
4521 0, /*tp_dictoffset*/
4522 0, /*tp_init*/
4523 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004524 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004525};
4526
4527
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004528/*
4529 * MemoryBIO objects
4530 */
4531
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004532/*[clinic input]
4533@classmethod
4534_ssl.MemoryBIO.__new__
4535
4536[clinic start generated code]*/
4537
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004538static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004539_ssl_MemoryBIO_impl(PyTypeObject *type)
4540/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004541{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004542 BIO *bio;
4543 PySSLMemoryBIO *self;
4544
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004545 bio = BIO_new(BIO_s_mem());
4546 if (bio == NULL) {
4547 PyErr_SetString(PySSLErrorObject,
4548 "failed to allocate BIO");
4549 return NULL;
4550 }
4551 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4552 * just that no data is currently available. The SSL routines should retry
4553 * the read, which we can achieve by calling BIO_set_retry_read(). */
4554 BIO_set_retry_read(bio);
4555 BIO_set_mem_eof_return(bio, -1);
4556
4557 assert(type != NULL && type->tp_alloc != NULL);
4558 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4559 if (self == NULL) {
4560 BIO_free(bio);
4561 return NULL;
4562 }
4563 self->bio = bio;
4564 self->eof_written = 0;
4565
4566 return (PyObject *) self;
4567}
4568
4569static void
4570memory_bio_dealloc(PySSLMemoryBIO *self)
4571{
4572 BIO_free(self->bio);
4573 Py_TYPE(self)->tp_free(self);
4574}
4575
4576static PyObject *
4577memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4578{
Segev Finer5cff6372017-07-27 01:19:17 +03004579 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004580}
4581
4582PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4583"The number of bytes pending in the memory BIO.");
4584
4585static PyObject *
4586memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4587{
4588 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4589 && self->eof_written);
4590}
4591
4592PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4593"Whether the memory BIO is at EOF.");
4594
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004595/*[clinic input]
4596_ssl.MemoryBIO.read
4597 size as len: int = -1
4598 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004599
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004600Read up to size bytes from the memory BIO.
4601
4602If size is not specified, read the entire buffer.
4603If the return value is an empty bytes instance, this means either
4604EOF or that no data is available. Use the "eof" property to
4605distinguish between the two.
4606[clinic start generated code]*/
4607
4608static PyObject *
4609_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4610/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4611{
4612 int avail, nbytes;
4613 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004614
Segev Finer5cff6372017-07-27 01:19:17 +03004615 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004616 if ((len < 0) || (len > avail))
4617 len = avail;
4618
4619 result = PyBytes_FromStringAndSize(NULL, len);
4620 if ((result == NULL) || (len == 0))
4621 return result;
4622
4623 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4624 /* There should never be any short reads but check anyway. */
4625 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4626 Py_DECREF(result);
4627 return NULL;
4628 }
4629
4630 return result;
4631}
4632
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004633/*[clinic input]
4634_ssl.MemoryBIO.write
4635 b: Py_buffer
4636 /
4637
4638Writes the bytes b into the memory BIO.
4639
4640Returns the number of bytes written.
4641[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004642
4643static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004644_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4645/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004646{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004647 int nbytes;
4648
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004650 PyErr_Format(PyExc_OverflowError,
4651 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004652 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004653 }
4654
4655 if (self->eof_written) {
4656 PyErr_SetString(PySSLErrorObject,
4657 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004658 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004659 }
4660
Segev Finer5cff6372017-07-27 01:19:17 +03004661 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004662 if (nbytes < 0) {
4663 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004665 }
4666
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004667 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004668}
4669
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004670/*[clinic input]
4671_ssl.MemoryBIO.write_eof
4672
4673Write an EOF marker to the memory BIO.
4674
4675When all data has been read, the "eof" property will be True.
4676[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004677
4678static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004679_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4680/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004681{
4682 self->eof_written = 1;
4683 /* After an EOF is written, a zero return from read() should be a real EOF
4684 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4685 BIO_clear_retry_flags(self->bio);
4686 BIO_set_mem_eof_return(self->bio, 0);
4687
4688 Py_RETURN_NONE;
4689}
4690
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004691static PyGetSetDef memory_bio_getsetlist[] = {
4692 {"pending", (getter) memory_bio_get_pending, NULL,
4693 PySSL_memory_bio_pending_doc},
4694 {"eof", (getter) memory_bio_get_eof, NULL,
4695 PySSL_memory_bio_eof_doc},
4696 {NULL}, /* sentinel */
4697};
4698
4699static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004700 _SSL_MEMORYBIO_READ_METHODDEF
4701 _SSL_MEMORYBIO_WRITE_METHODDEF
4702 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004703 {NULL, NULL} /* sentinel */
4704};
4705
4706static PyTypeObject PySSLMemoryBIO_Type = {
4707 PyVarObject_HEAD_INIT(NULL, 0)
4708 "_ssl.MemoryBIO", /*tp_name*/
4709 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4710 0, /*tp_itemsize*/
4711 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4712 0, /*tp_print*/
4713 0, /*tp_getattr*/
4714 0, /*tp_setattr*/
4715 0, /*tp_reserved*/
4716 0, /*tp_repr*/
4717 0, /*tp_as_number*/
4718 0, /*tp_as_sequence*/
4719 0, /*tp_as_mapping*/
4720 0, /*tp_hash*/
4721 0, /*tp_call*/
4722 0, /*tp_str*/
4723 0, /*tp_getattro*/
4724 0, /*tp_setattro*/
4725 0, /*tp_as_buffer*/
4726 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4727 0, /*tp_doc*/
4728 0, /*tp_traverse*/
4729 0, /*tp_clear*/
4730 0, /*tp_richcompare*/
4731 0, /*tp_weaklistoffset*/
4732 0, /*tp_iter*/
4733 0, /*tp_iternext*/
4734 memory_bio_methods, /*tp_methods*/
4735 0, /*tp_members*/
4736 memory_bio_getsetlist, /*tp_getset*/
4737 0, /*tp_base*/
4738 0, /*tp_dict*/
4739 0, /*tp_descr_get*/
4740 0, /*tp_descr_set*/
4741 0, /*tp_dictoffset*/
4742 0, /*tp_init*/
4743 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004744 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004745};
4746
Antoine Pitrou152efa22010-05-16 18:19:27 +00004747
Christian Heimes99a65702016-09-10 23:44:53 +02004748/*
4749 * SSL Session object
4750 */
4751
4752static void
4753PySSLSession_dealloc(PySSLSession *self)
4754{
INADA Naokia6296d32017-08-24 14:55:17 +09004755 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004756 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004757 Py_XDECREF(self->ctx);
4758 if (self->session != NULL) {
4759 SSL_SESSION_free(self->session);
4760 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004761 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004762}
4763
4764static PyObject *
4765PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4766{
4767 int result;
4768
4769 if (left == NULL || right == NULL) {
4770 PyErr_BadInternalCall();
4771 return NULL;
4772 }
4773
4774 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4775 Py_RETURN_NOTIMPLEMENTED;
4776 }
4777
4778 if (left == right) {
4779 result = 0;
4780 } else {
4781 const unsigned char *left_id, *right_id;
4782 unsigned int left_len, right_len;
4783 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4784 &left_len);
4785 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4786 &right_len);
4787 if (left_len == right_len) {
4788 result = memcmp(left_id, right_id, left_len);
4789 } else {
4790 result = 1;
4791 }
4792 }
4793
4794 switch (op) {
4795 case Py_EQ:
4796 if (result == 0) {
4797 Py_RETURN_TRUE;
4798 } else {
4799 Py_RETURN_FALSE;
4800 }
4801 break;
4802 case Py_NE:
4803 if (result != 0) {
4804 Py_RETURN_TRUE;
4805 } else {
4806 Py_RETURN_FALSE;
4807 }
4808 break;
4809 case Py_LT:
4810 case Py_LE:
4811 case Py_GT:
4812 case Py_GE:
4813 Py_RETURN_NOTIMPLEMENTED;
4814 break;
4815 default:
4816 PyErr_BadArgument();
4817 return NULL;
4818 }
4819}
4820
4821static int
4822PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4823{
4824 Py_VISIT(self->ctx);
4825 return 0;
4826}
4827
4828static int
4829PySSLSession_clear(PySSLSession *self)
4830{
4831 Py_CLEAR(self->ctx);
4832 return 0;
4833}
4834
4835
4836static PyObject *
4837PySSLSession_get_time(PySSLSession *self, void *closure) {
4838 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4839}
4840
4841PyDoc_STRVAR(PySSLSession_get_time_doc,
4842"Session creation time (seconds since epoch).");
4843
4844
4845static PyObject *
4846PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4847 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4848}
4849
4850PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4851"Session timeout (delta in seconds).");
4852
4853
4854static PyObject *
4855PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4856 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4857 return PyLong_FromUnsignedLong(hint);
4858}
4859
4860PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4861"Ticket life time hint.");
4862
4863
4864static PyObject *
4865PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4866 const unsigned char *id;
4867 unsigned int len;
4868 id = SSL_SESSION_get_id(self->session, &len);
4869 return PyBytes_FromStringAndSize((const char *)id, len);
4870}
4871
4872PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4873"Session id");
4874
4875
4876static PyObject *
4877PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4878 if (SSL_SESSION_has_ticket(self->session)) {
4879 Py_RETURN_TRUE;
4880 } else {
4881 Py_RETURN_FALSE;
4882 }
4883}
4884
4885PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4886"Does the session contain a ticket?");
4887
4888
4889static PyGetSetDef PySSLSession_getsetlist[] = {
4890 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4891 PySSLSession_get_has_ticket_doc},
4892 {"id", (getter) PySSLSession_get_session_id, NULL,
4893 PySSLSession_get_session_id_doc},
4894 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4895 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4896 {"time", (getter) PySSLSession_get_time, NULL,
4897 PySSLSession_get_time_doc},
4898 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4899 PySSLSession_get_timeout_doc},
4900 {NULL}, /* sentinel */
4901};
4902
4903static PyTypeObject PySSLSession_Type = {
4904 PyVarObject_HEAD_INIT(NULL, 0)
4905 "_ssl.Session", /*tp_name*/
4906 sizeof(PySSLSession), /*tp_basicsize*/
4907 0, /*tp_itemsize*/
4908 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4909 0, /*tp_print*/
4910 0, /*tp_getattr*/
4911 0, /*tp_setattr*/
4912 0, /*tp_reserved*/
4913 0, /*tp_repr*/
4914 0, /*tp_as_number*/
4915 0, /*tp_as_sequence*/
4916 0, /*tp_as_mapping*/
4917 0, /*tp_hash*/
4918 0, /*tp_call*/
4919 0, /*tp_str*/
4920 0, /*tp_getattro*/
4921 0, /*tp_setattro*/
4922 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004923 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004924 0, /*tp_doc*/
4925 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4926 (inquiry)PySSLSession_clear, /*tp_clear*/
4927 PySSLSession_richcompare, /*tp_richcompare*/
4928 0, /*tp_weaklistoffset*/
4929 0, /*tp_iter*/
4930 0, /*tp_iternext*/
4931 0, /*tp_methods*/
4932 0, /*tp_members*/
4933 PySSLSession_getsetlist, /*tp_getset*/
4934};
4935
4936
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004937/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004938/*[clinic input]
4939_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004940 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004941 entropy: double
4942 /
4943
4944Mix string into the OpenSSL PRNG state.
4945
4946entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304947string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004948[clinic start generated code]*/
4949
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004950static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004951_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004952/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004953{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004954 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004955 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004956
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004957 buf = (const char *)view->buf;
4958 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004959 do {
4960 written = Py_MIN(len, INT_MAX);
4961 RAND_add(buf, (int)written, entropy);
4962 buf += written;
4963 len -= written;
4964 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004965 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004966}
4967
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004968static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004969PySSL_RAND(int len, int pseudo)
4970{
4971 int ok;
4972 PyObject *bytes;
4973 unsigned long err;
4974 const char *errstr;
4975 PyObject *v;
4976
Victor Stinner1e81a392013-12-19 16:47:04 +01004977 if (len < 0) {
4978 PyErr_SetString(PyExc_ValueError, "num must be positive");
4979 return NULL;
4980 }
4981
Victor Stinner99c8b162011-05-24 12:05:19 +02004982 bytes = PyBytes_FromStringAndSize(NULL, len);
4983 if (bytes == NULL)
4984 return NULL;
4985 if (pseudo) {
4986 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4987 if (ok == 0 || ok == 1)
4988 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4989 }
4990 else {
4991 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4992 if (ok == 1)
4993 return bytes;
4994 }
4995 Py_DECREF(bytes);
4996
4997 err = ERR_get_error();
4998 errstr = ERR_reason_error_string(err);
4999 v = Py_BuildValue("(ks)", err, errstr);
5000 if (v != NULL) {
5001 PyErr_SetObject(PySSLErrorObject, v);
5002 Py_DECREF(v);
5003 }
5004 return NULL;
5005}
5006
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005007/*[clinic input]
5008_ssl.RAND_bytes
5009 n: int
5010 /
5011
5012Generate n cryptographically strong pseudo-random bytes.
5013[clinic start generated code]*/
5014
Victor Stinner99c8b162011-05-24 12:05:19 +02005015static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005016_ssl_RAND_bytes_impl(PyObject *module, int n)
5017/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005018{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005019 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005020}
5021
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005022/*[clinic input]
5023_ssl.RAND_pseudo_bytes
5024 n: int
5025 /
5026
5027Generate n pseudo-random bytes.
5028
5029Return a pair (bytes, is_cryptographic). is_cryptographic is True
5030if the bytes generated are cryptographically strong.
5031[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005032
5033static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005034_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5035/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005036{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005037 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005038}
5039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005040/*[clinic input]
5041_ssl.RAND_status
5042
5043Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5044
5045It is necessary to seed the PRNG with RAND_add() on some platforms before
5046using the ssl() function.
5047[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005048
5049static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005050_ssl_RAND_status_impl(PyObject *module)
5051/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005052{
Christian Heimes217cfd12007-12-02 14:31:20 +00005053 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005054}
5055
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005056#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005057/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005058/*[clinic input]
5059_ssl.RAND_egd
5060 path: object(converter="PyUnicode_FSConverter")
5061 /
5062
5063Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5064
5065Returns number of bytes read. Raises SSLError if connection to EGD
5066fails or if it does not provide enough data to seed PRNG.
5067[clinic start generated code]*/
5068
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005069static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005070_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5071/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005072{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005073 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005074 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005075 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005076 PyErr_SetString(PySSLErrorObject,
5077 "EGD connection failed or EGD did not return "
5078 "enough data to seed the PRNG");
5079 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005080 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005081 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005082}
Christian Heimesa5d07652016-09-24 10:48:05 +02005083/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005084#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005085
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005086
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005087
5088/*[clinic input]
5089_ssl.get_default_verify_paths
5090
5091Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5092
5093The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5094[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005095
5096static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005097_ssl_get_default_verify_paths_impl(PyObject *module)
5098/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005099{
5100 PyObject *ofile_env = NULL;
5101 PyObject *ofile = NULL;
5102 PyObject *odir_env = NULL;
5103 PyObject *odir = NULL;
5104
Benjamin Petersond113c962015-07-18 10:59:13 -07005105#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005106 const char *tmp = (info); \
5107 target = NULL; \
5108 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5109 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5110 target = PyBytes_FromString(tmp); } \
5111 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005112 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005113
Benjamin Petersond113c962015-07-18 10:59:13 -07005114 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5115 CONVERT(X509_get_default_cert_file(), ofile);
5116 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5117 CONVERT(X509_get_default_cert_dir(), odir);
5118#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005119
Christian Heimes200bb1b2013-06-14 15:14:29 +02005120 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005121
5122 error:
5123 Py_XDECREF(ofile_env);
5124 Py_XDECREF(ofile);
5125 Py_XDECREF(odir_env);
5126 Py_XDECREF(odir);
5127 return NULL;
5128}
5129
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005130static PyObject*
5131asn1obj2py(ASN1_OBJECT *obj)
5132{
5133 int nid;
5134 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005135
5136 nid = OBJ_obj2nid(obj);
5137 if (nid == NID_undef) {
5138 PyErr_Format(PyExc_ValueError, "Unknown object");
5139 return NULL;
5140 }
5141 sn = OBJ_nid2sn(nid);
5142 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005143 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005144}
5145
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005146/*[clinic input]
5147_ssl.txt2obj
5148 txt: str
5149 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005151Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5152
5153By default objects are looked up by OID. With name=True short and
5154long name are also matched.
5155[clinic start generated code]*/
5156
5157static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005158_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5159/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005160{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005161 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005162 ASN1_OBJECT *obj;
5163
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005164 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5165 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005166 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005167 return NULL;
5168 }
5169 result = asn1obj2py(obj);
5170 ASN1_OBJECT_free(obj);
5171 return result;
5172}
5173
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005174/*[clinic input]
5175_ssl.nid2obj
5176 nid: int
5177 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005178
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005179Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5180[clinic start generated code]*/
5181
5182static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005183_ssl_nid2obj_impl(PyObject *module, int nid)
5184/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005185{
5186 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005187 ASN1_OBJECT *obj;
5188
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005189 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005190 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005191 return NULL;
5192 }
5193 obj = OBJ_nid2obj(nid);
5194 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005195 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005196 return NULL;
5197 }
5198 result = asn1obj2py(obj);
5199 ASN1_OBJECT_free(obj);
5200 return result;
5201}
5202
Christian Heimes46bebee2013-06-09 19:03:31 +02005203#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005204
5205static PyObject*
5206certEncodingType(DWORD encodingType)
5207{
5208 static PyObject *x509_asn = NULL;
5209 static PyObject *pkcs_7_asn = NULL;
5210
5211 if (x509_asn == NULL) {
5212 x509_asn = PyUnicode_InternFromString("x509_asn");
5213 if (x509_asn == NULL)
5214 return NULL;
5215 }
5216 if (pkcs_7_asn == NULL) {
5217 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5218 if (pkcs_7_asn == NULL)
5219 return NULL;
5220 }
5221 switch(encodingType) {
5222 case X509_ASN_ENCODING:
5223 Py_INCREF(x509_asn);
5224 return x509_asn;
5225 case PKCS_7_ASN_ENCODING:
5226 Py_INCREF(pkcs_7_asn);
5227 return pkcs_7_asn;
5228 default:
5229 return PyLong_FromLong(encodingType);
5230 }
5231}
5232
5233static PyObject*
5234parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5235{
5236 CERT_ENHKEY_USAGE *usage;
5237 DWORD size, error, i;
5238 PyObject *retval;
5239
5240 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5241 error = GetLastError();
5242 if (error == CRYPT_E_NOT_FOUND) {
5243 Py_RETURN_TRUE;
5244 }
5245 return PyErr_SetFromWindowsErr(error);
5246 }
5247
5248 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5249 if (usage == NULL) {
5250 return PyErr_NoMemory();
5251 }
5252
5253 /* Now get the actual enhanced usage property */
5254 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5255 PyMem_Free(usage);
5256 error = GetLastError();
5257 if (error == CRYPT_E_NOT_FOUND) {
5258 Py_RETURN_TRUE;
5259 }
5260 return PyErr_SetFromWindowsErr(error);
5261 }
5262 retval = PySet_New(NULL);
5263 if (retval == NULL) {
5264 goto error;
5265 }
5266 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5267 if (usage->rgpszUsageIdentifier[i]) {
5268 PyObject *oid;
5269 int err;
5270 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5271 if (oid == NULL) {
5272 Py_CLEAR(retval);
5273 goto error;
5274 }
5275 err = PySet_Add(retval, oid);
5276 Py_DECREF(oid);
5277 if (err == -1) {
5278 Py_CLEAR(retval);
5279 goto error;
5280 }
5281 }
5282 }
5283 error:
5284 PyMem_Free(usage);
5285 return retval;
5286}
5287
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005288/*[clinic input]
5289_ssl.enum_certificates
5290 store_name: str
5291
5292Retrieve certificates from Windows' cert store.
5293
5294store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5295more cert storages, too. The function returns a list of (bytes,
5296encoding_type, trust) tuples. The encoding_type flag can be interpreted
5297with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5298a set of OIDs or the boolean True.
5299[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005300
Christian Heimes46bebee2013-06-09 19:03:31 +02005301static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005302_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5303/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005304{
Christian Heimes46bebee2013-06-09 19:03:31 +02005305 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005306 PCCERT_CONTEXT pCertCtx = NULL;
5307 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005308 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005309
Christian Heimes44109d72013-11-22 01:51:30 +01005310 result = PyList_New(0);
5311 if (result == NULL) {
5312 return NULL;
5313 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005314 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5315 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5316 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005317 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005318 Py_DECREF(result);
5319 return PyErr_SetFromWindowsErr(GetLastError());
5320 }
5321
Christian Heimes44109d72013-11-22 01:51:30 +01005322 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5323 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5324 pCertCtx->cbCertEncoded);
5325 if (!cert) {
5326 Py_CLEAR(result);
5327 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005328 }
Christian Heimes44109d72013-11-22 01:51:30 +01005329 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5330 Py_CLEAR(result);
5331 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005332 }
Christian Heimes44109d72013-11-22 01:51:30 +01005333 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5334 if (keyusage == Py_True) {
5335 Py_DECREF(keyusage);
5336 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005337 }
Christian Heimes44109d72013-11-22 01:51:30 +01005338 if (keyusage == NULL) {
5339 Py_CLEAR(result);
5340 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005341 }
Christian Heimes44109d72013-11-22 01:51:30 +01005342 if ((tup = PyTuple_New(3)) == NULL) {
5343 Py_CLEAR(result);
5344 break;
5345 }
5346 PyTuple_SET_ITEM(tup, 0, cert);
5347 cert = NULL;
5348 PyTuple_SET_ITEM(tup, 1, enc);
5349 enc = NULL;
5350 PyTuple_SET_ITEM(tup, 2, keyusage);
5351 keyusage = NULL;
5352 if (PyList_Append(result, tup) < 0) {
5353 Py_CLEAR(result);
5354 break;
5355 }
5356 Py_CLEAR(tup);
5357 }
5358 if (pCertCtx) {
5359 /* loop ended with an error, need to clean up context manually */
5360 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005361 }
5362
5363 /* In error cases cert, enc and tup may not be NULL */
5364 Py_XDECREF(cert);
5365 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005366 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005367 Py_XDECREF(tup);
5368
5369 if (!CertCloseStore(hStore, 0)) {
5370 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005371 Py_XDECREF(result);
5372 return PyErr_SetFromWindowsErr(GetLastError());
5373 }
5374 return result;
5375}
5376
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005377/*[clinic input]
5378_ssl.enum_crls
5379 store_name: str
5380
5381Retrieve CRLs from Windows' cert store.
5382
5383store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5384more cert storages, too. The function returns a list of (bytes,
5385encoding_type) tuples. The encoding_type flag can be interpreted with
5386X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5387[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005388
5389static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005390_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5391/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005392{
Christian Heimes44109d72013-11-22 01:51:30 +01005393 HCERTSTORE hStore = NULL;
5394 PCCRL_CONTEXT pCrlCtx = NULL;
5395 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5396 PyObject *result = NULL;
5397
Christian Heimes44109d72013-11-22 01:51:30 +01005398 result = PyList_New(0);
5399 if (result == NULL) {
5400 return NULL;
5401 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005402 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5403 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5404 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005405 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005406 Py_DECREF(result);
5407 return PyErr_SetFromWindowsErr(GetLastError());
5408 }
Christian Heimes44109d72013-11-22 01:51:30 +01005409
5410 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5411 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5412 pCrlCtx->cbCrlEncoded);
5413 if (!crl) {
5414 Py_CLEAR(result);
5415 break;
5416 }
5417 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5418 Py_CLEAR(result);
5419 break;
5420 }
5421 if ((tup = PyTuple_New(2)) == NULL) {
5422 Py_CLEAR(result);
5423 break;
5424 }
5425 PyTuple_SET_ITEM(tup, 0, crl);
5426 crl = NULL;
5427 PyTuple_SET_ITEM(tup, 1, enc);
5428 enc = NULL;
5429
5430 if (PyList_Append(result, tup) < 0) {
5431 Py_CLEAR(result);
5432 break;
5433 }
5434 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005435 }
Christian Heimes44109d72013-11-22 01:51:30 +01005436 if (pCrlCtx) {
5437 /* loop ended with an error, need to clean up context manually */
5438 CertFreeCRLContext(pCrlCtx);
5439 }
5440
5441 /* In error cases cert, enc and tup may not be NULL */
5442 Py_XDECREF(crl);
5443 Py_XDECREF(enc);
5444 Py_XDECREF(tup);
5445
5446 if (!CertCloseStore(hStore, 0)) {
5447 /* This error case might shadow another exception.*/
5448 Py_XDECREF(result);
5449 return PyErr_SetFromWindowsErr(GetLastError());
5450 }
5451 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005452}
Christian Heimes44109d72013-11-22 01:51:30 +01005453
5454#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005455
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005456/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005457static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005458 _SSL__TEST_DECODE_CERT_METHODDEF
5459 _SSL_RAND_ADD_METHODDEF
5460 _SSL_RAND_BYTES_METHODDEF
5461 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5462 _SSL_RAND_EGD_METHODDEF
5463 _SSL_RAND_STATUS_METHODDEF
5464 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5465 _SSL_ENUM_CERTIFICATES_METHODDEF
5466 _SSL_ENUM_CRLS_METHODDEF
5467 _SSL_TXT2OBJ_METHODDEF
5468 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005469 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005470};
5471
5472
Christian Heimes598894f2016-09-05 23:19:05 +02005473#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005474
5475/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005476 * of the Python C thread library
5477 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5478 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005479
5480static PyThread_type_lock *_ssl_locks = NULL;
5481
Christian Heimes4d98ca92013-08-19 17:36:29 +02005482#if OPENSSL_VERSION_NUMBER >= 0x10000000
5483/* use new CRYPTO_THREADID API. */
5484static void
5485_ssl_threadid_callback(CRYPTO_THREADID *id)
5486{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005487 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005488}
5489#else
5490/* deprecated CRYPTO_set_id_callback() API. */
5491static unsigned long
5492_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005493 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005494}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005495#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005496
Bill Janssen6e027db2007-11-15 22:23:56 +00005497static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005498 (int mode, int n, const char *file, int line) {
5499 /* this function is needed to perform locking on shared data
5500 structures. (Note that OpenSSL uses a number of global data
5501 structures that will be implicitly shared whenever multiple
5502 threads use OpenSSL.) Multi-threaded applications will
5503 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005504
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005505 locking_function() must be able to handle up to
5506 CRYPTO_num_locks() different mutex locks. It sets the n-th
5507 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005508
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005509 file and line are the file number of the function setting the
5510 lock. They can be useful for debugging.
5511 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005512
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005513 if ((_ssl_locks == NULL) ||
5514 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5515 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005517 if (mode & CRYPTO_LOCK) {
5518 PyThread_acquire_lock(_ssl_locks[n], 1);
5519 } else {
5520 PyThread_release_lock(_ssl_locks[n]);
5521 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005522}
5523
5524static int _setup_ssl_threads(void) {
5525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005526 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005527
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005528 if (_ssl_locks == NULL) {
5529 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005530 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5531 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005532 if (_ssl_locks == NULL) {
5533 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005534 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005535 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005536 for (i = 0; i < _ssl_locks_count; i++) {
5537 _ssl_locks[i] = PyThread_allocate_lock();
5538 if (_ssl_locks[i] == NULL) {
5539 unsigned int j;
5540 for (j = 0; j < i; j++) {
5541 PyThread_free_lock(_ssl_locks[j]);
5542 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005543 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005544 return 0;
5545 }
5546 }
5547 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005548#if OPENSSL_VERSION_NUMBER >= 0x10000000
5549 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5550#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005551 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005552#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005553 }
5554 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005555}
5556
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005557#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005558
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005559PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005560"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005561for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005562
Martin v. Löwis1a214512008-06-11 05:26:20 +00005563
5564static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005565 PyModuleDef_HEAD_INIT,
5566 "_ssl",
5567 module_doc,
5568 -1,
5569 PySSL_methods,
5570 NULL,
5571 NULL,
5572 NULL,
5573 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005574};
5575
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005576
5577static void
5578parse_openssl_version(unsigned long libver,
5579 unsigned int *major, unsigned int *minor,
5580 unsigned int *fix, unsigned int *patch,
5581 unsigned int *status)
5582{
5583 *status = libver & 0xF;
5584 libver >>= 4;
5585 *patch = libver & 0xFF;
5586 libver >>= 8;
5587 *fix = libver & 0xFF;
5588 libver >>= 8;
5589 *minor = libver & 0xFF;
5590 libver >>= 8;
5591 *major = libver & 0xFF;
5592}
5593
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005594PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005595PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005596{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005597 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005598 unsigned long libver;
5599 unsigned int major, minor, fix, patch, status;
5600 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005601 struct py_ssl_error_code *errcode;
5602 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005603
Antoine Pitrou152efa22010-05-16 18:19:27 +00005604 if (PyType_Ready(&PySSLContext_Type) < 0)
5605 return NULL;
5606 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005607 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005608 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5609 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005610 if (PyType_Ready(&PySSLSession_Type) < 0)
5611 return NULL;
5612
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005614 m = PyModule_Create(&_sslmodule);
5615 if (m == NULL)
5616 return NULL;
5617 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005619 /* Load _socket module and its C API */
5620 socket_api = PySocketModule_ImportModuleAndAPI();
5621 if (!socket_api)
5622 return NULL;
5623 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005624
Christian Heimesc941e622017-09-05 15:47:11 +02005625#ifndef OPENSSL_VERSION_1_1
5626 /* Load all algorithms and initialize cpuid */
5627 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005628 /* Init OpenSSL */
5629 SSL_load_error_strings();
5630 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005631#endif
5632
Christian Heimes598894f2016-09-05 23:19:05 +02005633#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005634 /* note that this will start threading if not already started */
5635 if (!_setup_ssl_threads()) {
5636 return NULL;
5637 }
Christian Heimes598894f2016-09-05 23:19:05 +02005638#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5639 /* OpenSSL 1.1.0 builtin thread support is enabled */
5640 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005641#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005642
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005643 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005644 sslerror_type_slots[0].pfunc = PyExc_OSError;
5645 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005646 if (PySSLErrorObject == NULL)
5647 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005648
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005649 /* ssl.CertificateError used to be a subclass of ValueError */
5650 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5651 if (bases == NULL)
5652 return NULL;
5653 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5654 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5655 bases, NULL);
5656 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005657 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5658 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5659 PySSLErrorObject, NULL);
5660 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5661 "ssl.SSLWantReadError", SSLWantReadError_doc,
5662 PySSLErrorObject, NULL);
5663 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5664 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5665 PySSLErrorObject, NULL);
5666 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5667 "ssl.SSLSyscallError", SSLSyscallError_doc,
5668 PySSLErrorObject, NULL);
5669 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5670 "ssl.SSLEOFError", SSLEOFError_doc,
5671 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005672 if (PySSLCertVerificationErrorObject == NULL
5673 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005674 || PySSLWantReadErrorObject == NULL
5675 || PySSLWantWriteErrorObject == NULL
5676 || PySSLSyscallErrorObject == NULL
5677 || PySSLEOFErrorObject == NULL)
5678 return NULL;
5679 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005680 || PyDict_SetItemString(d, "SSLCertVerificationError",
5681 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005682 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5683 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5684 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5685 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5686 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005687 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005688 if (PyDict_SetItemString(d, "_SSLContext",
5689 (PyObject *)&PySSLContext_Type) != 0)
5690 return NULL;
5691 if (PyDict_SetItemString(d, "_SSLSocket",
5692 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005693 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005694 if (PyDict_SetItemString(d, "MemoryBIO",
5695 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5696 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005697 if (PyDict_SetItemString(d, "SSLSession",
5698 (PyObject *)&PySSLSession_Type) != 0)
5699 return NULL;
5700
Christian Heimes892d66e2018-01-29 14:10:18 +01005701 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5702 PY_SSL_DEFAULT_CIPHER_STRING);
5703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005704 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5705 PY_SSL_ERROR_ZERO_RETURN);
5706 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5707 PY_SSL_ERROR_WANT_READ);
5708 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5709 PY_SSL_ERROR_WANT_WRITE);
5710 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5711 PY_SSL_ERROR_WANT_X509_LOOKUP);
5712 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5713 PY_SSL_ERROR_SYSCALL);
5714 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5715 PY_SSL_ERROR_SSL);
5716 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5717 PY_SSL_ERROR_WANT_CONNECT);
5718 /* non ssl.h errorcodes */
5719 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5720 PY_SSL_ERROR_EOF);
5721 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5722 PY_SSL_ERROR_INVALID_ERROR_CODE);
5723 /* cert requirements */
5724 PyModule_AddIntConstant(m, "CERT_NONE",
5725 PY_SSL_CERT_NONE);
5726 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5727 PY_SSL_CERT_OPTIONAL);
5728 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5729 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005730 /* CRL verification for verification_flags */
5731 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5732 0);
5733 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5734 X509_V_FLAG_CRL_CHECK);
5735 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5736 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5737 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5738 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005739#ifdef X509_V_FLAG_TRUSTED_FIRST
5740 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5741 X509_V_FLAG_TRUSTED_FIRST);
5742#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005743
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005744 /* Alert Descriptions from ssl.h */
5745 /* note RESERVED constants no longer intended for use have been removed */
5746 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5747
5748#define ADD_AD_CONSTANT(s) \
5749 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5750 SSL_AD_##s)
5751
5752 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5753 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5754 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5755 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5756 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5757 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5758 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5759 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5760 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5761 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5762 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5763 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5764 ADD_AD_CONSTANT(UNKNOWN_CA);
5765 ADD_AD_CONSTANT(ACCESS_DENIED);
5766 ADD_AD_CONSTANT(DECODE_ERROR);
5767 ADD_AD_CONSTANT(DECRYPT_ERROR);
5768 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5769 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5770 ADD_AD_CONSTANT(INTERNAL_ERROR);
5771 ADD_AD_CONSTANT(USER_CANCELLED);
5772 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005773 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005774#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5775 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5776#endif
5777#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5778 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5779#endif
5780#ifdef SSL_AD_UNRECOGNIZED_NAME
5781 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5782#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005783#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5784 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5785#endif
5786#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5787 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5788#endif
5789#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5790 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5791#endif
5792
5793#undef ADD_AD_CONSTANT
5794
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005795 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005796#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005797 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5798 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005799#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005800#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005801 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5802 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005803#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005804 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005805 PY_SSL_VERSION_TLS);
5806 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5807 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005808 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5809 PY_SSL_VERSION_TLS_CLIENT);
5810 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5811 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005812 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5813 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005814#if HAVE_TLSv1_2
5815 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5816 PY_SSL_VERSION_TLS1_1);
5817 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5818 PY_SSL_VERSION_TLS1_2);
5819#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005820
Antoine Pitroub5218772010-05-21 09:56:06 +00005821 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005822 PyModule_AddIntConstant(m, "OP_ALL",
5823 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005824 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5825 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5826 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005827#if HAVE_TLSv1_2
5828 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5829 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5830#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005831#ifdef SSL_OP_NO_TLSv1_3
5832 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5833#else
5834 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5835#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005836 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5837 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005838 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005839 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005840#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005841 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005842#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005843#ifdef SSL_OP_NO_COMPRESSION
5844 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5845 SSL_OP_NO_COMPRESSION);
5846#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005847#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5848 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5849 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5850#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005851
Christian Heimes61d478c2018-01-27 15:51:38 +01005852#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5853 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5854 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5855#endif
5856#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5857 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5858 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5859#endif
5860#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5861 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5862 X509_CHECK_FLAG_NO_WILDCARDS);
5863#endif
5864#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5865 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5866 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5867#endif
5868#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5869 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5870 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5871#endif
5872#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5873 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5874 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5875#endif
5876
Christian Heimes698dde12018-02-27 11:54:43 +01005877 /* protocol versions */
5878 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5879 PY_PROTO_MINIMUM_SUPPORTED);
5880 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5881 PY_PROTO_MAXIMUM_SUPPORTED);
5882 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5883 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5884 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5885 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5886 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005887
Christian Heimes698dde12018-02-27 11:54:43 +01005888#define addbool(m, v, b) \
5889 Py_INCREF((b) ? Py_True : Py_False); \
5890 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5891
5892#if HAVE_SNI
5893 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005894#else
Christian Heimes698dde12018-02-27 11:54:43 +01005895 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005896#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005897
5898 addbool(m, "HAS_TLS_UNIQUE", 1);
5899
5900#ifndef OPENSSL_NO_ECDH
5901 addbool(m, "HAS_ECDH", 1);
5902#else
5903 addbool(m, "HAS_ECDH", 0);
5904#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005905
Christian Heimes29eab552018-02-25 12:31:33 +01005906#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005907 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005908#else
Christian Heimes698dde12018-02-27 11:54:43 +01005909 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005910#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005911
Christian Heimes29eab552018-02-25 12:31:33 +01005912#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005913 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005914#else
Christian Heimes698dde12018-02-27 11:54:43 +01005915 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005916#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005917
5918#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5919 addbool(m, "HAS_SSLv2", 1);
5920#else
5921 addbool(m, "HAS_SSLv2", 0);
5922#endif
5923
5924#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5925 addbool(m, "HAS_SSLv3", 1);
5926#else
5927 addbool(m, "HAS_SSLv3", 0);
5928#endif
5929
5930#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5931 addbool(m, "HAS_TLSv1", 1);
5932#else
5933 addbool(m, "HAS_TLSv1", 0);
5934#endif
5935
5936#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5937 addbool(m, "HAS_TLSv1_1", 1);
5938#else
5939 addbool(m, "HAS_TLSv1_1", 0);
5940#endif
5941
5942#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5943 addbool(m, "HAS_TLSv1_2", 1);
5944#else
5945 addbool(m, "HAS_TLSv1_2", 0);
5946#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005947
Christian Heimescb5b68a2017-09-07 18:07:00 -07005948#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005949 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005950#else
Christian Heimes698dde12018-02-27 11:54:43 +01005951 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005952#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005953
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005954 /* Mappings for error codes */
5955 err_codes_to_names = PyDict_New();
5956 err_names_to_codes = PyDict_New();
5957 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5958 return NULL;
5959 errcode = error_codes;
5960 while (errcode->mnemonic != NULL) {
5961 PyObject *mnemo, *key;
5962 mnemo = PyUnicode_FromString(errcode->mnemonic);
5963 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5964 if (mnemo == NULL || key == NULL)
5965 return NULL;
5966 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5967 return NULL;
5968 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5969 return NULL;
5970 Py_DECREF(key);
5971 Py_DECREF(mnemo);
5972 errcode++;
5973 }
5974 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5975 return NULL;
5976 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5977 return NULL;
5978
5979 lib_codes_to_names = PyDict_New();
5980 if (lib_codes_to_names == NULL)
5981 return NULL;
5982 libcode = library_codes;
5983 while (libcode->library != NULL) {
5984 PyObject *mnemo, *key;
5985 key = PyLong_FromLong(libcode->code);
5986 mnemo = PyUnicode_FromString(libcode->library);
5987 if (key == NULL || mnemo == NULL)
5988 return NULL;
5989 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5990 return NULL;
5991 Py_DECREF(key);
5992 Py_DECREF(mnemo);
5993 libcode++;
5994 }
5995 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5996 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005997
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005998 /* OpenSSL version */
5999 /* SSLeay() gives us the version of the library linked against,
6000 which could be different from the headers version.
6001 */
6002 libver = SSLeay();
6003 r = PyLong_FromUnsignedLong(libver);
6004 if (r == NULL)
6005 return NULL;
6006 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6007 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006008 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006009 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6010 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6011 return NULL;
6012 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6013 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6014 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006015
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006016 libver = OPENSSL_VERSION_NUMBER;
6017 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6018 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6019 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6020 return NULL;
6021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006022 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006023}