blob: f9e061dfe01d7fa9d08c93ec8a9766274a596168 [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
139#endif
140
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100141/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
142 http://www.openssl.org/news/changelog.html
143 */
144#if OPENSSL_VERSION_NUMBER >= 0x10001000L
145# define HAVE_TLSv1_2 1
146#else
147# define HAVE_TLSv1_2 0
148#endif
149
Christian Heimes470fba12013-11-28 15:12:15 +0100150/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100151 * This includes the SSL_set_SSL_CTX() function.
152 */
153#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
154# define HAVE_SNI 1
155#else
156# define HAVE_SNI 0
157#endif
158
Benjamin Petersond3308222015-09-27 00:09:02 -0700159#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100160# define HAVE_ALPN 1
161#else
162# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500163#endif
164
Christian Heimes6cdb7952018-02-24 22:12:40 +0100165/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
166 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
167 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
168 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100169 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100170 */
171#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100172# define HAVE_NPN 0
173#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
174# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100175#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100176# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100177#else
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_NPN 0
179#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100180
Victor Stinner524714e2016-07-22 17:43:59 +0200181#ifndef INVALID_SOCKET /* MS defines this */
182#define INVALID_SOCKET (-1)
183#endif
184
Christian Heimes598894f2016-09-05 23:19:05 +0200185#ifdef OPENSSL_VERSION_1_1
186/* OpenSSL 1.1.0+ */
187#ifndef OPENSSL_NO_SSL2
188#define OPENSSL_NO_SSL2
189#endif
190#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200191#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200192
193#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200194#define TLS_client_method SSLv23_client_method
195#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200196
197static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
198{
199 return ne->set;
200}
201
202#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200203/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200204static int COMP_get_type(const COMP_METHOD *meth)
205{
206 return meth->type;
207}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200208/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200209#endif
210
211static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
212{
213 return ctx->default_passwd_callback;
214}
215
216static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
217{
218 return ctx->default_passwd_callback_userdata;
219}
220
221static int X509_OBJECT_get_type(X509_OBJECT *x)
222{
223 return x->type;
224}
225
226static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
227{
228 return x->data.x509;
229}
230
231static int BIO_up_ref(BIO *b)
232{
233 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
234 return 1;
235}
236
237static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
238 return store->objs;
239}
240
Christian Heimes99a65702016-09-10 23:44:53 +0200241static int
242SSL_SESSION_has_ticket(const SSL_SESSION *s)
243{
244 return (s->tlsext_ticklen > 0) ? 1 : 0;
245}
246
247static unsigned long
248SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
249{
250 return s->tlsext_tick_lifetime_hint;
251}
252
Christian Heimes598894f2016-09-05 23:19:05 +0200253#endif /* OpenSSL < 1.1.0 or LibreSSL */
254
Christian Heimes892d66e2018-01-29 14:10:18 +0100255/* Default cipher suites */
256#ifndef PY_SSL_DEFAULT_CIPHERS
257#define PY_SSL_DEFAULT_CIPHERS 1
258#endif
259
260#if PY_SSL_DEFAULT_CIPHERS == 0
261 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
262 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
263 #endif
264#elif PY_SSL_DEFAULT_CIPHERS == 1
265/* Python custom selection of sensible ciper suites
266 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
267 * !aNULL:!eNULL: really no NULL ciphers
268 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
269 * !aDSS: no authentication with discrete logarithm DSA algorithm
270 * !SRP:!PSK: no secure remote password or pre-shared key authentication
271 */
272 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
273#elif PY_SSL_DEFAULT_CIPHERS == 2
274/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
275 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
276#else
277 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
278#endif
279
Christian Heimes598894f2016-09-05 23:19:05 +0200280
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000281enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000282 /* these mirror ssl.h */
283 PY_SSL_ERROR_NONE,
284 PY_SSL_ERROR_SSL,
285 PY_SSL_ERROR_WANT_READ,
286 PY_SSL_ERROR_WANT_WRITE,
287 PY_SSL_ERROR_WANT_X509_LOOKUP,
288 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
289 PY_SSL_ERROR_ZERO_RETURN,
290 PY_SSL_ERROR_WANT_CONNECT,
291 /* start of non ssl.h errorcodes */
292 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
293 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
294 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000295};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000296
Thomas Woutersed03b412007-08-28 21:37:11 +0000297enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PY_SSL_CLIENT,
299 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000300};
301
302enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000303 PY_SSL_CERT_NONE,
304 PY_SSL_CERT_OPTIONAL,
305 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000306};
307
308enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000309 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200310 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200311 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100312#if HAVE_TLSv1_2
313 PY_SSL_VERSION_TLS1,
314 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200315 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100316#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200317 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000318#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200319 PY_SSL_VERSION_TLS_CLIENT=0x10,
320 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100321};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200322
Christian Heimes698dde12018-02-27 11:54:43 +0100323enum py_proto_version {
324 PY_PROTO_MINIMUM_SUPPORTED = -2,
325 PY_PROTO_SSLv3 = SSL3_VERSION,
326 PY_PROTO_TLSv1 = TLS1_VERSION,
327 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
328 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
329#ifdef TLS1_3_VERSION
330 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
331#else
332 PY_PROTO_TLSv1_3 = 0x304,
333#endif
334 PY_PROTO_MAXIMUM_SUPPORTED = -1,
335
336/* OpenSSL has no dedicated API to set the minimum version to the maximum
337 * available version, and the other way around. We have to figure out the
338 * minimum and maximum available version on our own and hope for the best.
339 */
340#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
341 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
342#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
343 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
344#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
345 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
346#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
347 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
348#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
349 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
350#else
351 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
352#endif
353
354#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
355 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
356#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
357 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
358#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
359 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
360#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
361 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
362#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
363 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
364#else
365 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
366#endif
367};
368
369
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000370/* serves as a flag to see whether we've initialized the SSL thread support. */
371/* 0 means no, greater than 0 means yes */
372
373static unsigned int _ssl_locks_count = 0;
374
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375/* SSL socket object */
376
377#define X509_NAME_MAXLEN 256
378
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000379/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
380 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
381 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
382#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000383# define HAVE_SSL_CTX_CLEAR_OPTIONS
384#else
385# undef HAVE_SSL_CTX_CLEAR_OPTIONS
386#endif
387
Antoine Pitroud6494802011-07-21 01:11:30 +0200388/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
389 * older SSL, but let's be safe */
390#define PySSL_CB_MAXLEN 128
391
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100392
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000393typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000394 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000395 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100396#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500397 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100398 int npn_protocols_len;
399#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100400#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500401 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300402 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500403#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100404#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100405 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100406#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100407 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100408 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
409 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
410 */
411 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100412 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000413} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000414
Antoine Pitrou152efa22010-05-16 18:19:27 +0000415typedef struct {
416 PyObject_HEAD
417 PyObject *Socket; /* weakref to socket on which we're layered */
418 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100419 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200420 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200421 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200422 PyObject *owner; /* Python level "owner" passed to servername callback */
423 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700424 int ssl_errno; /* last seen error from SSL */
425 int c_errno; /* last seen error from libc */
426#ifdef MS_WINDOWS
427 int ws_errno; /* last seen error from winsock */
428#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000429} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000430
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200431typedef struct {
432 PyObject_HEAD
433 BIO *bio;
434 int eof_written;
435} PySSLMemoryBIO;
436
Christian Heimes99a65702016-09-10 23:44:53 +0200437typedef struct {
438 PyObject_HEAD
439 SSL_SESSION *session;
440 PySSLContext *ctx;
441} PySSLSession;
442
Antoine Pitrou152efa22010-05-16 18:19:27 +0000443static PyTypeObject PySSLContext_Type;
444static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200445static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200446static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000447
Steve Dowere6eb48c2017-09-08 15:16:15 -0700448#ifdef MS_WINDOWS
449#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
450 (sock)->ws_errno = WSAGetLastError(); \
451 _PySSL_FIX_ERRNO; \
452 (sock)->c_errno = errno; \
453 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
454 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
455#else
456#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
457 (sock)->c_errno = errno; \
458 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
459 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
460#endif
461#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
462
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300463/*[clinic input]
464module _ssl
465class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
466class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
467class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200468class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300469[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200470/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300471
472#include "clinic/_ssl.c.h"
473
Victor Stinner14690702015-04-06 22:46:13 +0200474static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000475
Christian Heimes141c5e82018-02-24 21:10:57 +0100476static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
477static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000478#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200479#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200480#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000481
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000482typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000483 SOCKET_IS_NONBLOCKING,
484 SOCKET_IS_BLOCKING,
485 SOCKET_HAS_TIMED_OUT,
486 SOCKET_HAS_BEEN_CLOSED,
487 SOCKET_TOO_LARGE_FOR_SELECT,
488 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000489} timeout_state;
490
Thomas Woutersed03b412007-08-28 21:37:11 +0000491/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000492#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200493#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000494
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200495/* Get the socket from a PySSLSocket, if it has one */
496#define GET_SOCKET(obj) ((obj)->Socket ? \
497 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200498
Victor Stinner14690702015-04-06 22:46:13 +0200499/* If sock is NULL, use a timeout of 0 second */
500#define GET_SOCKET_TIMEOUT(sock) \
501 ((sock != NULL) ? (sock)->sock_timeout : 0)
502
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200503/*
504 * SSL errors.
505 */
506
507PyDoc_STRVAR(SSLError_doc,
508"An error occurred in the SSL implementation.");
509
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700510PyDoc_STRVAR(SSLCertVerificationError_doc,
511"A certificate could not be verified.");
512
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200513PyDoc_STRVAR(SSLZeroReturnError_doc,
514"SSL/TLS session closed cleanly.");
515
516PyDoc_STRVAR(SSLWantReadError_doc,
517"Non-blocking SSL socket needs to read more data\n"
518"before the requested operation can be completed.");
519
520PyDoc_STRVAR(SSLWantWriteError_doc,
521"Non-blocking SSL socket needs to write more data\n"
522"before the requested operation can be completed.");
523
524PyDoc_STRVAR(SSLSyscallError_doc,
525"System error when attempting SSL operation.");
526
527PyDoc_STRVAR(SSLEOFError_doc,
528"SSL/TLS connection terminated abruptly.");
529
530static PyObject *
531SSLError_str(PyOSErrorObject *self)
532{
533 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
534 Py_INCREF(self->strerror);
535 return self->strerror;
536 }
537 else
538 return PyObject_Str(self->args);
539}
540
541static PyType_Slot sslerror_type_slots[] = {
542 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
543 {Py_tp_doc, SSLError_doc},
544 {Py_tp_str, SSLError_str},
545 {0, 0},
546};
547
548static PyType_Spec sslerror_type_spec = {
549 "ssl.SSLError",
550 sizeof(PyOSErrorObject),
551 0,
552 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
553 sslerror_type_slots
554};
555
556static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700557fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
558 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200559{
560 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700561 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200562 PyObject *init_value, *msg, *key;
563 _Py_IDENTIFIER(reason);
564 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700565 _Py_IDENTIFIER(verify_message);
566 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200567
568 if (errcode != 0) {
569 int lib, reason;
570
571 lib = ERR_GET_LIB(errcode);
572 reason = ERR_GET_REASON(errcode);
573 key = Py_BuildValue("ii", lib, reason);
574 if (key == NULL)
575 goto fail;
576 reason_obj = PyDict_GetItem(err_codes_to_names, key);
577 Py_DECREF(key);
578 if (reason_obj == NULL) {
579 /* XXX if reason < 100, it might reflect a library number (!!) */
580 PyErr_Clear();
581 }
582 key = PyLong_FromLong(lib);
583 if (key == NULL)
584 goto fail;
585 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
586 Py_DECREF(key);
587 if (lib_obj == NULL) {
588 PyErr_Clear();
589 }
590 if (errstr == NULL)
591 errstr = ERR_reason_error_string(errcode);
592 }
593 if (errstr == NULL)
594 errstr = "unknown error";
595
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700596 /* verify code for cert validation error */
597 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
598 const char *verify_str = NULL;
599 long verify_code;
600
601 verify_code = SSL_get_verify_result(sslsock->ssl);
602 verify_code_obj = PyLong_FromLong(verify_code);
603 if (verify_code_obj == NULL) {
604 goto fail;
605 }
606
607 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700608#ifdef X509_V_ERR_HOSTNAME_MISMATCH
609 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700610 case X509_V_ERR_HOSTNAME_MISMATCH:
611 verify_obj = PyUnicode_FromFormat(
612 "Hostname mismatch, certificate is not valid for '%S'.",
613 sslsock->server_hostname
614 );
615 break;
Christian Heimes09153602017-09-08 14:47:58 -0700616#endif
617#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700618 case X509_V_ERR_IP_ADDRESS_MISMATCH:
619 verify_obj = PyUnicode_FromFormat(
620 "IP address mismatch, certificate is not valid for '%S'.",
621 sslsock->server_hostname
622 );
623 break;
Christian Heimes09153602017-09-08 14:47:58 -0700624#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700625 default:
626 verify_str = X509_verify_cert_error_string(verify_code);
627 if (verify_str != NULL) {
628 verify_obj = PyUnicode_FromString(verify_str);
629 } else {
630 verify_obj = Py_None;
631 Py_INCREF(verify_obj);
632 }
633 break;
634 }
635 if (verify_obj == NULL) {
636 goto fail;
637 }
638 }
639
640 if (verify_obj && reason_obj && lib_obj)
641 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
642 lib_obj, reason_obj, errstr, verify_obj,
643 lineno);
644 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200645 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
646 lib_obj, reason_obj, errstr, lineno);
647 else if (lib_obj)
648 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
649 lib_obj, errstr, lineno);
650 else
651 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200652 if (msg == NULL)
653 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100654
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200655 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100656 if (init_value == NULL)
657 goto fail;
658
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200659 err_value = PyObject_CallObject(type, init_value);
660 Py_DECREF(init_value);
661 if (err_value == NULL)
662 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100663
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200664 if (reason_obj == NULL)
665 reason_obj = Py_None;
666 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
667 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700668
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200669 if (lib_obj == NULL)
670 lib_obj = Py_None;
671 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
672 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700673
674 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
675 /* Only set verify code / message for SSLCertVerificationError */
676 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
677 verify_code_obj))
678 goto fail;
679 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
680 goto fail;
681 }
682
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200683 PyErr_SetObject(type, err_value);
684fail:
685 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700686 Py_XDECREF(verify_code_obj);
687 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200688}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000689
690static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700691PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000692{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200693 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200694 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000695 int err;
696 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200697 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200700 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000701
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700702 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700703 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000704
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 switch (err) {
706 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200707 errstr = "TLS/SSL connection has been closed (EOF)";
708 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 p = PY_SSL_ERROR_ZERO_RETURN;
710 break;
711 case SSL_ERROR_WANT_READ:
712 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200713 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 p = PY_SSL_ERROR_WANT_READ;
715 break;
716 case SSL_ERROR_WANT_WRITE:
717 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200718 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 errstr = "The operation did not complete (write)";
720 break;
721 case SSL_ERROR_WANT_X509_LOOKUP:
722 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000723 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 break;
725 case SSL_ERROR_WANT_CONNECT:
726 p = PY_SSL_ERROR_WANT_CONNECT;
727 errstr = "The operation did not complete (connect)";
728 break;
729 case SSL_ERROR_SYSCALL:
730 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700732 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000734 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200735 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000736 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200737 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000738 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000739 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700740#ifdef MS_WINDOWS
741 if (sslsock->ws_errno)
742 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
743#endif
744 if (sslsock->c_errno) {
745 errno = sslsock->c_errno;
746 return PyErr_SetFromErrno(PyExc_OSError);
747 }
748 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200749 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000750 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200751 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000753 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200754 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000755 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 }
757 } else {
758 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 }
760 break;
761 }
762 case SSL_ERROR_SSL:
763 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700765 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200766 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000767 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700768 }
769 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
770 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
771 type = PySSLCertVerificationErrorObject;
772 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000773 break;
774 }
775 default:
776 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
777 errstr = "Invalid error code";
778 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700780 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000781 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000782 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000783}
784
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000785static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200786_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000787
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200788 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200790 else
791 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700792 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000793 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795}
796
Christian Heimes61d478c2018-01-27 15:51:38 +0100797/*
798 * SSL objects
799 */
800
801static int
802_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
803{
804 int retval = -1;
805 ASN1_OCTET_STRING *ip;
806 PyObject *hostname;
807 size_t len;
808
809 assert(server_hostname);
810
811 /* Disable OpenSSL's special mode with leading dot in hostname:
812 * When name starts with a dot (e.g ".example.com"), it will be
813 * matched by a certificate valid for any sub-domain of name.
814 */
815 len = strlen(server_hostname);
816 if (len == 0 || *server_hostname == '.') {
817 PyErr_SetString(
818 PyExc_ValueError,
819 "server_hostname cannot be an empty string or start with a "
820 "leading dot.");
821 return retval;
822 }
823
824 /* inet_pton is not available on all platforms. */
825 ip = a2i_IPADDRESS(server_hostname);
826 if (ip == NULL) {
827 ERR_clear_error();
828 }
829
Christian Heimes11a14932018-02-24 02:35:08 +0100830 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100831 if (hostname == NULL) {
832 goto error;
833 }
834 self->server_hostname = hostname;
835
836 /* Only send SNI extension for non-IP hostnames */
837 if (ip == NULL) {
838 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
839 _setSSLError(NULL, 0, __FILE__, __LINE__);
840 }
841 }
842 if (self->ctx->check_hostname) {
843 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
844 if (ip == NULL) {
845 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
846 _setSSLError(NULL, 0, __FILE__, __LINE__);
847 goto error;
848 }
849 } else {
850 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
851 ASN1_STRING_length(ip))) {
852 _setSSLError(NULL, 0, __FILE__, __LINE__);
853 goto error;
854 }
855 }
856 }
857 retval = 0;
858 error:
859 if (ip != NULL) {
860 ASN1_OCTET_STRING_free(ip);
861 }
862 return retval;
863}
864
Antoine Pitrou152efa22010-05-16 18:19:27 +0000865static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100866newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000867 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200868 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100869 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200870 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000871{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000872 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100873 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200874 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000875
Antoine Pitrou152efa22010-05-16 18:19:27 +0000876 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000877 if (self == NULL)
878 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000880 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000881 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100882 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700883 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200884 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200885 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700886 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700887 self->ssl_errno = 0;
888 self->c_errno = 0;
889#ifdef MS_WINDOWS
890 self->ws_errno = 0;
891#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 /* Make sure the SSL error state is initialized */
894 (void) ERR_get_state();
895 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000897 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000898 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000899 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200900 SSL_set_app_data(self->ssl, self);
901 if (sock) {
902 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
903 } else {
904 /* BIOs are reference counted and SSL_set_bio borrows our reference.
905 * To prevent a double free in memory_bio_dealloc() we need to take an
906 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200907 BIO_up_ref(inbio->bio);
908 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200909 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
910 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200911 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000912#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200913 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000914#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200915 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000916
Christian Heimes61d478c2018-01-27 15:51:38 +0100917 if (server_hostname != NULL) {
918 if (_ssl_configure_hostname(self, server_hostname) < 0) {
919 Py_DECREF(self);
920 return NULL;
921 }
922 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 /* If the socket is in non-blocking mode or timeout mode, set the BIO
924 * to non-blocking mode (blocking is the default)
925 */
Victor Stinnere2452312015-03-28 03:00:46 +0100926 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
928 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
929 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 PySSL_BEGIN_ALLOW_THREADS
932 if (socket_type == PY_SSL_CLIENT)
933 SSL_set_connect_state(self->ssl);
934 else
935 SSL_set_accept_state(self->ssl);
936 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000937
Antoine Pitroud6494802011-07-21 01:11:30 +0200938 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200939 if (sock != NULL) {
940 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
941 if (self->Socket == NULL) {
942 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200943 return NULL;
944 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100945 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100946 if (owner && owner != Py_None) {
947 if (PySSL_set_owner(self, owner, NULL) == -1) {
948 Py_DECREF(self);
949 return NULL;
950 }
951 }
952 if (session && session != Py_None) {
953 if (PySSL_set_session(self, session, NULL) == -1) {
954 Py_DECREF(self);
955 return NULL;
956 }
957 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000959}
960
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000961/* SSL object methods */
962
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300963/*[clinic input]
964_ssl._SSLSocket.do_handshake
965[clinic start generated code]*/
966
967static PyObject *
968_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
969/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000970{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 int ret;
972 int err;
973 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200974 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200975 _PyTime_t timeout, deadline = 0;
976 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000977
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200978 if (sock) {
979 if (((PyObject*)sock) == Py_None) {
980 _setSSLError("Underlying socket connection gone",
981 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
982 return NULL;
983 }
984 Py_INCREF(sock);
985
986 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100987 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200988 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
989 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000991
Victor Stinner14690702015-04-06 22:46:13 +0200992 timeout = GET_SOCKET_TIMEOUT(sock);
993 has_timeout = (timeout > 0);
994 if (has_timeout)
995 deadline = _PyTime_GetMonotonicClock() + timeout;
996
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 /* Actually negotiate SSL connection */
998 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000999 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001000 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001001 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07001002 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001003 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07001004 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001005
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001006 if (PyErr_CheckSignals())
1007 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001008
Victor Stinner14690702015-04-06 22:46:13 +02001009 if (has_timeout)
1010 timeout = deadline - _PyTime_GetMonotonicClock();
1011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001012 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001013 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001014 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001015 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 } else {
1017 sockstate = SOCKET_OPERATION_OK;
1018 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001021 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001022 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001023 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1025 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001026 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001027 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1029 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001030 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001031 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1033 break;
1034 }
1035 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001036 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 if (ret < 1)
1038 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001039
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001040 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001041
1042error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001043 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001044 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001045}
1046
Thomas Woutersed03b412007-08-28 21:37:11 +00001047static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001048_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1049{
1050 char buf[X509_NAME_MAXLEN];
1051 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001053 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001054
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001055 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001056 if (buflen < 0) {
1057 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001058 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001060 /* initial buffer is too small for oid + terminating null byte */
1061 if (buflen > X509_NAME_MAXLEN - 1) {
1062 /* make OBJ_obj2txt() calculate the required buflen */
1063 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1064 /* allocate len + 1 for terminating NULL byte */
1065 namebuf = PyMem_Malloc(buflen + 1);
1066 if (namebuf == NULL) {
1067 PyErr_NoMemory();
1068 return NULL;
1069 }
1070 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1071 if (buflen < 0) {
1072 _setSSLError(NULL, 0, __FILE__, __LINE__);
1073 goto done;
1074 }
1075 }
1076 if (!buflen && no_name) {
1077 Py_INCREF(Py_None);
1078 name_obj = Py_None;
1079 }
1080 else {
1081 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1082 }
1083
1084 done:
1085 if (buf != namebuf) {
1086 PyMem_Free(namebuf);
1087 }
1088 return name_obj;
1089}
1090
1091static PyObject *
1092_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1093{
1094 Py_ssize_t buflen;
1095 unsigned char *valuebuf = NULL;
1096 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1099 if (buflen < 0) {
1100 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001101 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001102 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001103 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001104 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001105 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001106}
1107
1108static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001109_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001110{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1112 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1113 PyObject *rdnt;
1114 PyObject *attr = NULL; /* tuple to hold an attribute */
1115 int entry_count = X509_NAME_entry_count(xname);
1116 X509_NAME_ENTRY *entry;
1117 ASN1_OBJECT *name;
1118 ASN1_STRING *value;
1119 int index_counter;
1120 int rdn_level = -1;
1121 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 dn = PyList_New(0);
1124 if (dn == NULL)
1125 return NULL;
1126 /* now create another tuple to hold the top-level RDN */
1127 rdn = PyList_New(0);
1128 if (rdn == NULL)
1129 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 for (index_counter = 0;
1132 index_counter < entry_count;
1133 index_counter++)
1134 {
1135 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 /* check to see if we've gotten to a new RDN */
1138 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001139 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 /* yes, new RDN */
1141 /* add old RDN to DN */
1142 rdnt = PyList_AsTuple(rdn);
1143 Py_DECREF(rdn);
1144 if (rdnt == NULL)
1145 goto fail0;
1146 retcode = PyList_Append(dn, rdnt);
1147 Py_DECREF(rdnt);
1148 if (retcode < 0)
1149 goto fail0;
1150 /* create new RDN */
1151 rdn = PyList_New(0);
1152 if (rdn == NULL)
1153 goto fail0;
1154 }
1155 }
Christian Heimes598894f2016-09-05 23:19:05 +02001156 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001158 /* now add this attribute to the current RDN */
1159 name = X509_NAME_ENTRY_get_object(entry);
1160 value = X509_NAME_ENTRY_get_data(entry);
1161 attr = _create_tuple_for_attribute(name, value);
1162 /*
1163 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1164 entry->set,
1165 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1166 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1167 */
1168 if (attr == NULL)
1169 goto fail1;
1170 retcode = PyList_Append(rdn, attr);
1171 Py_DECREF(attr);
1172 if (retcode < 0)
1173 goto fail1;
1174 }
1175 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001176 if (rdn != NULL) {
1177 if (PyList_GET_SIZE(rdn) > 0) {
1178 rdnt = PyList_AsTuple(rdn);
1179 Py_DECREF(rdn);
1180 if (rdnt == NULL)
1181 goto fail0;
1182 retcode = PyList_Append(dn, rdnt);
1183 Py_DECREF(rdnt);
1184 if (retcode < 0)
1185 goto fail0;
1186 }
1187 else {
1188 Py_DECREF(rdn);
1189 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001192 /* convert list to tuple */
1193 rdnt = PyList_AsTuple(dn);
1194 Py_DECREF(dn);
1195 if (rdnt == NULL)
1196 return NULL;
1197 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001198
1199 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001201
1202 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 Py_XDECREF(dn);
1204 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205}
1206
1207static PyObject *
1208_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001209
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001210 /* this code follows the procedure outlined in
1211 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1212 function to extract the STACK_OF(GENERAL_NAME),
1213 then iterates through the stack to add the
1214 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001215
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001216 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001218 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001219 GENERAL_NAMES *names = NULL;
1220 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001221 BIO *biobuf = NULL;
1222 char buf[2048];
1223 char *vptr;
1224 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001226 if (certificate == NULL)
1227 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 /* get a memory buffer */
1230 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001231
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001232 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1233 certificate, NID_subject_alt_name, NULL, NULL);
1234 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001235 if (peer_alt_names == Py_None) {
1236 peer_alt_names = PyList_New(0);
1237 if (peer_alt_names == NULL)
1238 goto fail;
1239 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001241 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001242 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001243 int gntype;
1244 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001247 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001248 switch (gntype) {
1249 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 /* we special-case DirName as a tuple of
1251 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001252
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001253 t = PyTuple_New(2);
1254 if (t == NULL) {
1255 goto fail;
1256 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001257
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 v = PyUnicode_FromString("DirName");
1259 if (v == NULL) {
1260 Py_DECREF(t);
1261 goto fail;
1262 }
1263 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001265 v = _create_tuple_for_X509_NAME (name->d.dirn);
1266 if (v == NULL) {
1267 Py_DECREF(t);
1268 goto fail;
1269 }
1270 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001271 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001272
Christian Heimes824f7f32013-08-17 00:54:47 +02001273 case GEN_EMAIL:
1274 case GEN_DNS:
1275 case GEN_URI:
1276 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1277 correctly, CVE-2013-4238 */
1278 t = PyTuple_New(2);
1279 if (t == NULL)
1280 goto fail;
1281 switch (gntype) {
1282 case GEN_EMAIL:
1283 v = PyUnicode_FromString("email");
1284 as = name->d.rfc822Name;
1285 break;
1286 case GEN_DNS:
1287 v = PyUnicode_FromString("DNS");
1288 as = name->d.dNSName;
1289 break;
1290 case GEN_URI:
1291 v = PyUnicode_FromString("URI");
1292 as = name->d.uniformResourceIdentifier;
1293 break;
1294 }
1295 if (v == NULL) {
1296 Py_DECREF(t);
1297 goto fail;
1298 }
1299 PyTuple_SET_ITEM(t, 0, v);
1300 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1301 ASN1_STRING_length(as));
1302 if (v == NULL) {
1303 Py_DECREF(t);
1304 goto fail;
1305 }
1306 PyTuple_SET_ITEM(t, 1, v);
1307 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308
Christian Heimes1c03abd2016-09-06 23:25:35 +02001309 case GEN_RID:
1310 t = PyTuple_New(2);
1311 if (t == NULL)
1312 goto fail;
1313
1314 v = PyUnicode_FromString("Registered ID");
1315 if (v == NULL) {
1316 Py_DECREF(t);
1317 goto fail;
1318 }
1319 PyTuple_SET_ITEM(t, 0, v);
1320
1321 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1322 if (len < 0) {
1323 Py_DECREF(t);
1324 _setSSLError(NULL, 0, __FILE__, __LINE__);
1325 goto fail;
1326 } else if (len >= (int)sizeof(buf)) {
1327 v = PyUnicode_FromString("<INVALID>");
1328 } else {
1329 v = PyUnicode_FromStringAndSize(buf, len);
1330 }
1331 if (v == NULL) {
1332 Py_DECREF(t);
1333 goto fail;
1334 }
1335 PyTuple_SET_ITEM(t, 1, v);
1336 break;
1337
Christian Heimes824f7f32013-08-17 00:54:47 +02001338 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001340 switch (gntype) {
1341 /* check for new general name type */
1342 case GEN_OTHERNAME:
1343 case GEN_X400:
1344 case GEN_EDIPARTY:
1345 case GEN_IPADD:
1346 case GEN_RID:
1347 break;
1348 default:
1349 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1350 "Unknown general name type %d",
1351 gntype) == -1) {
1352 goto fail;
1353 }
1354 break;
1355 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 (void) BIO_reset(biobuf);
1357 GENERAL_NAME_print(biobuf, name);
1358 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1359 if (len < 0) {
1360 _setSSLError(NULL, 0, __FILE__, __LINE__);
1361 goto fail;
1362 }
1363 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001364 if (vptr == NULL) {
1365 PyErr_Format(PyExc_ValueError,
1366 "Invalid value %.200s",
1367 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001369 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001370 t = PyTuple_New(2);
1371 if (t == NULL)
1372 goto fail;
1373 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1374 if (v == NULL) {
1375 Py_DECREF(t);
1376 goto fail;
1377 }
1378 PyTuple_SET_ITEM(t, 0, v);
1379 v = PyUnicode_FromStringAndSize((vptr + 1),
1380 (len - (vptr - buf + 1)));
1381 if (v == NULL) {
1382 Py_DECREF(t);
1383 goto fail;
1384 }
1385 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001386 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001387 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001388
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001389 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001391 if (PyList_Append(peer_alt_names, t) < 0) {
1392 Py_DECREF(t);
1393 goto fail;
1394 }
1395 Py_DECREF(t);
1396 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001397 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001398 }
1399 BIO_free(biobuf);
1400 if (peer_alt_names != Py_None) {
1401 v = PyList_AsTuple(peer_alt_names);
1402 Py_DECREF(peer_alt_names);
1403 return v;
1404 } else {
1405 return peer_alt_names;
1406 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001407
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001408
1409 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001410 if (biobuf != NULL)
1411 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001412
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 if (peer_alt_names != Py_None) {
1414 Py_XDECREF(peer_alt_names);
1415 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001417 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001418}
1419
1420static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001421_get_aia_uri(X509 *certificate, int nid) {
1422 PyObject *lst = NULL, *ostr = NULL;
1423 int i, result;
1424 AUTHORITY_INFO_ACCESS *info;
1425
1426 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001427 if (info == NULL)
1428 return Py_None;
1429 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1430 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001431 return Py_None;
1432 }
1433
1434 if ((lst = PyList_New(0)) == NULL) {
1435 goto fail;
1436 }
1437
1438 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1439 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1440 ASN1_IA5STRING *uri;
1441
1442 if ((OBJ_obj2nid(ad->method) != nid) ||
1443 (ad->location->type != GEN_URI)) {
1444 continue;
1445 }
1446 uri = ad->location->d.uniformResourceIdentifier;
1447 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1448 uri->length);
1449 if (ostr == NULL) {
1450 goto fail;
1451 }
1452 result = PyList_Append(lst, ostr);
1453 Py_DECREF(ostr);
1454 if (result < 0) {
1455 goto fail;
1456 }
1457 }
1458 AUTHORITY_INFO_ACCESS_free(info);
1459
1460 /* convert to tuple or None */
1461 if (PyList_Size(lst) == 0) {
1462 Py_DECREF(lst);
1463 return Py_None;
1464 } else {
1465 PyObject *tup;
1466 tup = PyList_AsTuple(lst);
1467 Py_DECREF(lst);
1468 return tup;
1469 }
1470
1471 fail:
1472 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001473 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001474 return NULL;
1475}
1476
1477static PyObject *
1478_get_crl_dp(X509 *certificate) {
1479 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001480 int i, j;
1481 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001482
Christian Heimes598894f2016-09-05 23:19:05 +02001483 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001484
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001485 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001486 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001487
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001488 lst = PyList_New(0);
1489 if (lst == NULL)
1490 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001491
1492 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1493 DIST_POINT *dp;
1494 STACK_OF(GENERAL_NAME) *gns;
1495
1496 dp = sk_DIST_POINT_value(dps, i);
1497 gns = dp->distpoint->name.fullname;
1498
1499 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1500 GENERAL_NAME *gn;
1501 ASN1_IA5STRING *uri;
1502 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001503 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001504
1505 gn = sk_GENERAL_NAME_value(gns, j);
1506 if (gn->type != GEN_URI) {
1507 continue;
1508 }
1509 uri = gn->d.uniformResourceIdentifier;
1510 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1511 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001512 if (ouri == NULL)
1513 goto done;
1514
1515 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001516 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001517 if (err < 0)
1518 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001519 }
1520 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001521
1522 /* Convert to tuple. */
1523 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1524
1525 done:
1526 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001527 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001528 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001529}
1530
1531static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001532_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 PyObject *retval = NULL;
1535 BIO *biobuf = NULL;
1536 PyObject *peer;
1537 PyObject *peer_alt_names = NULL;
1538 PyObject *issuer;
1539 PyObject *version;
1540 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001541 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 ASN1_INTEGER *serialNumber;
1543 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001544 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001545 ASN1_TIME *notBefore, *notAfter;
1546 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001547
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001548 retval = PyDict_New();
1549 if (retval == NULL)
1550 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 peer = _create_tuple_for_X509_NAME(
1553 X509_get_subject_name(certificate));
1554 if (peer == NULL)
1555 goto fail0;
1556 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1557 Py_DECREF(peer);
1558 goto fail0;
1559 }
1560 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001561
Antoine Pitroufb046912010-11-09 20:21:19 +00001562 issuer = _create_tuple_for_X509_NAME(
1563 X509_get_issuer_name(certificate));
1564 if (issuer == NULL)
1565 goto fail0;
1566 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001567 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001568 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001569 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001570 Py_DECREF(issuer);
1571
1572 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001573 if (version == NULL)
1574 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001575 if (PyDict_SetItemString(retval, "version", version) < 0) {
1576 Py_DECREF(version);
1577 goto fail0;
1578 }
1579 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001580
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001581 /* get a memory buffer */
1582 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001583
Antoine Pitroufb046912010-11-09 20:21:19 +00001584 (void) BIO_reset(biobuf);
1585 serialNumber = X509_get_serialNumber(certificate);
1586 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1587 i2a_ASN1_INTEGER(biobuf, serialNumber);
1588 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1589 if (len < 0) {
1590 _setSSLError(NULL, 0, __FILE__, __LINE__);
1591 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001592 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001593 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1594 if (sn_obj == NULL)
1595 goto fail1;
1596 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1597 Py_DECREF(sn_obj);
1598 goto fail1;
1599 }
1600 Py_DECREF(sn_obj);
1601
1602 (void) BIO_reset(biobuf);
1603 notBefore = X509_get_notBefore(certificate);
1604 ASN1_TIME_print(biobuf, notBefore);
1605 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1606 if (len < 0) {
1607 _setSSLError(NULL, 0, __FILE__, __LINE__);
1608 goto fail1;
1609 }
1610 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1611 if (pnotBefore == NULL)
1612 goto fail1;
1613 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1614 Py_DECREF(pnotBefore);
1615 goto fail1;
1616 }
1617 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001618
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 (void) BIO_reset(biobuf);
1620 notAfter = X509_get_notAfter(certificate);
1621 ASN1_TIME_print(biobuf, notAfter);
1622 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1623 if (len < 0) {
1624 _setSSLError(NULL, 0, __FILE__, __LINE__);
1625 goto fail1;
1626 }
1627 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1628 if (pnotAfter == NULL)
1629 goto fail1;
1630 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1631 Py_DECREF(pnotAfter);
1632 goto fail1;
1633 }
1634 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001638 peer_alt_names = _get_peer_alt_names(certificate);
1639 if (peer_alt_names == NULL)
1640 goto fail1;
1641 else if (peer_alt_names != Py_None) {
1642 if (PyDict_SetItemString(retval, "subjectAltName",
1643 peer_alt_names) < 0) {
1644 Py_DECREF(peer_alt_names);
1645 goto fail1;
1646 }
1647 Py_DECREF(peer_alt_names);
1648 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001649
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001650 /* Authority Information Access: OCSP URIs */
1651 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1652 if (obj == NULL) {
1653 goto fail1;
1654 } else if (obj != Py_None) {
1655 result = PyDict_SetItemString(retval, "OCSP", obj);
1656 Py_DECREF(obj);
1657 if (result < 0) {
1658 goto fail1;
1659 }
1660 }
1661
1662 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1663 if (obj == NULL) {
1664 goto fail1;
1665 } else if (obj != Py_None) {
1666 result = PyDict_SetItemString(retval, "caIssuers", obj);
1667 Py_DECREF(obj);
1668 if (result < 0) {
1669 goto fail1;
1670 }
1671 }
1672
1673 /* CDP (CRL distribution points) */
1674 obj = _get_crl_dp(certificate);
1675 if (obj == NULL) {
1676 goto fail1;
1677 } else if (obj != Py_None) {
1678 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1679 Py_DECREF(obj);
1680 if (result < 0) {
1681 goto fail1;
1682 }
1683 }
1684
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001685 BIO_free(biobuf);
1686 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001687
1688 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 if (biobuf != NULL)
1690 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001691 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001692 Py_XDECREF(retval);
1693 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001694}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001695
Christian Heimes9a5395a2013-06-17 15:44:12 +02001696static PyObject *
1697_certificate_to_der(X509 *certificate)
1698{
1699 unsigned char *bytes_buf = NULL;
1700 int len;
1701 PyObject *retval;
1702
1703 bytes_buf = NULL;
1704 len = i2d_X509(certificate, &bytes_buf);
1705 if (len < 0) {
1706 _setSSLError(NULL, 0, __FILE__, __LINE__);
1707 return NULL;
1708 }
1709 /* this is actually an immutable bytes sequence */
1710 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1711 OPENSSL_free(bytes_buf);
1712 return retval;
1713}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001714
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001715/*[clinic input]
1716_ssl._test_decode_cert
1717 path: object(converter="PyUnicode_FSConverter")
1718 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001719
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001720[clinic start generated code]*/
1721
1722static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001723_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1724/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001725{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001726 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001727 X509 *x=NULL;
1728 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001729
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1731 PyErr_SetString(PySSLErrorObject,
1732 "Can't malloc memory to read file");
1733 goto fail0;
1734 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001735
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001736 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PyErr_SetString(PySSLErrorObject,
1738 "Can't open file");
1739 goto fail0;
1740 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001741
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1743 if (x == NULL) {
1744 PyErr_SetString(PySSLErrorObject,
1745 "Error decoding PEM-encoded file");
1746 goto fail0;
1747 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
Antoine Pitroufb046912010-11-09 20:21:19 +00001749 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001750 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001751
1752 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001753 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001754 if (cert != NULL) BIO_free(cert);
1755 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756}
1757
1758
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001759/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001760_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001761 der as binary_mode: bool = False
1762 /
1763
1764Returns the certificate for the peer.
1765
1766If no certificate was provided, returns None. If a certificate was
1767provided, but not validated, returns an empty dictionary. Otherwise
1768returns a dict containing information about the peer certificate.
1769
1770If the optional argument is True, returns a DER-encoded copy of the
1771peer certificate, or None if no certificate was provided. This will
1772return the certificate even if it wasn't validated.
1773[clinic start generated code]*/
1774
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001775static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001776_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1777/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001778{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001780 X509 *peer_cert;
1781 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001782
Christian Heimes66dc33b2017-05-23 16:02:02 -07001783 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001784 PyErr_SetString(PyExc_ValueError,
1785 "handshake not done yet");
1786 return NULL;
1787 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001788 peer_cert = SSL_get_peer_certificate(self->ssl);
1789 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001790 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001791
Antoine Pitrou721738f2012-08-15 23:20:39 +02001792 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001793 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001794 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001795 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001796 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001797 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001798 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001799 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001800 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001802 X509_free(peer_cert);
1803 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001804}
1805
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001806static PyObject *
1807cipher_to_tuple(const SSL_CIPHER *cipher)
1808{
1809 const char *cipher_name, *cipher_protocol;
1810 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001811 if (retval == NULL)
1812 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001813
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001814 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001815 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001816 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001817 PyTuple_SET_ITEM(retval, 0, Py_None);
1818 } else {
1819 v = PyUnicode_FromString(cipher_name);
1820 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001821 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001822 PyTuple_SET_ITEM(retval, 0, v);
1823 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001824
1825 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001826 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001827 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001828 PyTuple_SET_ITEM(retval, 1, Py_None);
1829 } else {
1830 v = PyUnicode_FromString(cipher_protocol);
1831 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001832 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001833 PyTuple_SET_ITEM(retval, 1, v);
1834 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001835
1836 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001837 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001838 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001839 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001840
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001842
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001843 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001844 Py_DECREF(retval);
1845 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001846}
1847
Christian Heimes25bfcd52016-09-06 00:04:45 +02001848#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1849static PyObject *
1850cipher_to_dict(const SSL_CIPHER *cipher)
1851{
1852 const char *cipher_name, *cipher_protocol;
1853
1854 unsigned long cipher_id;
1855 int alg_bits, strength_bits, len;
1856 char buf[512] = {0};
1857#if OPENSSL_VERSION_1_1
1858 int aead, nid;
1859 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1860#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001861
1862 /* can be NULL */
1863 cipher_name = SSL_CIPHER_get_name(cipher);
1864 cipher_protocol = SSL_CIPHER_get_version(cipher);
1865 cipher_id = SSL_CIPHER_get_id(cipher);
1866 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001867 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1868 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001869 if (len > 1 && buf[len-1] == '\n')
1870 buf[len-1] = '\0';
1871 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1872
1873#if OPENSSL_VERSION_1_1
1874 aead = SSL_CIPHER_is_aead(cipher);
1875 nid = SSL_CIPHER_get_cipher_nid(cipher);
1876 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1877 nid = SSL_CIPHER_get_digest_nid(cipher);
1878 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1879 nid = SSL_CIPHER_get_kx_nid(cipher);
1880 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1881 nid = SSL_CIPHER_get_auth_nid(cipher);
1882 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1883#endif
1884
Victor Stinner410b9882016-09-12 12:00:23 +02001885 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001886 "{sksssssssisi"
1887#if OPENSSL_VERSION_1_1
1888 "sOssssssss"
1889#endif
1890 "}",
1891 "id", cipher_id,
1892 "name", cipher_name,
1893 "protocol", cipher_protocol,
1894 "description", buf,
1895 "strength_bits", strength_bits,
1896 "alg_bits", alg_bits
1897#if OPENSSL_VERSION_1_1
1898 ,"aead", aead ? Py_True : Py_False,
1899 "symmetric", skcipher,
1900 "digest", digest,
1901 "kea", kx,
1902 "auth", auth
1903#endif
1904 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001905}
1906#endif
1907
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001908/*[clinic input]
1909_ssl._SSLSocket.shared_ciphers
1910[clinic start generated code]*/
1911
1912static PyObject *
1913_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1914/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001915{
1916 STACK_OF(SSL_CIPHER) *ciphers;
1917 int i;
1918 PyObject *res;
1919
Christian Heimes598894f2016-09-05 23:19:05 +02001920 ciphers = SSL_get_ciphers(self->ssl);
1921 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001922 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001923 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1924 if (!res)
1925 return NULL;
1926 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1927 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1928 if (!tup) {
1929 Py_DECREF(res);
1930 return NULL;
1931 }
1932 PyList_SET_ITEM(res, i, tup);
1933 }
1934 return res;
1935}
1936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001937/*[clinic input]
1938_ssl._SSLSocket.cipher
1939[clinic start generated code]*/
1940
1941static PyObject *
1942_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1943/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001944{
1945 const SSL_CIPHER *current;
1946
1947 if (self->ssl == NULL)
1948 Py_RETURN_NONE;
1949 current = SSL_get_current_cipher(self->ssl);
1950 if (current == NULL)
1951 Py_RETURN_NONE;
1952 return cipher_to_tuple(current);
1953}
1954
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001955/*[clinic input]
1956_ssl._SSLSocket.version
1957[clinic start generated code]*/
1958
1959static PyObject *
1960_ssl__SSLSocket_version_impl(PySSLSocket *self)
1961/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001962{
1963 const char *version;
1964
1965 if (self->ssl == NULL)
1966 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001967 if (!SSL_is_init_finished(self->ssl)) {
1968 /* handshake not finished */
1969 Py_RETURN_NONE;
1970 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001971 version = SSL_get_version(self->ssl);
1972 if (!strcmp(version, "unknown"))
1973 Py_RETURN_NONE;
1974 return PyUnicode_FromString(version);
1975}
1976
Christian Heimes29eab552018-02-25 12:31:33 +01001977#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001978/*[clinic input]
1979_ssl._SSLSocket.selected_npn_protocol
1980[clinic start generated code]*/
1981
1982static PyObject *
1983_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1984/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1985{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001986 const unsigned char *out;
1987 unsigned int outlen;
1988
Victor Stinner4569cd52013-06-23 14:58:43 +02001989 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001990 &out, &outlen);
1991
1992 if (out == NULL)
1993 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001994 return PyUnicode_FromStringAndSize((char *)out, outlen);
1995}
1996#endif
1997
Christian Heimes29eab552018-02-25 12:31:33 +01001998#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001999/*[clinic input]
2000_ssl._SSLSocket.selected_alpn_protocol
2001[clinic start generated code]*/
2002
2003static PyObject *
2004_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2005/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2006{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002007 const unsigned char *out;
2008 unsigned int outlen;
2009
2010 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2011
2012 if (out == NULL)
2013 Py_RETURN_NONE;
2014 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002015}
2016#endif
2017
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002018/*[clinic input]
2019_ssl._SSLSocket.compression
2020[clinic start generated code]*/
2021
2022static PyObject *
2023_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2024/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2025{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002026#ifdef OPENSSL_NO_COMP
2027 Py_RETURN_NONE;
2028#else
2029 const COMP_METHOD *comp_method;
2030 const char *short_name;
2031
2032 if (self->ssl == NULL)
2033 Py_RETURN_NONE;
2034 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002035 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002036 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002037 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002038 if (short_name == NULL)
2039 Py_RETURN_NONE;
2040 return PyUnicode_DecodeFSDefault(short_name);
2041#endif
2042}
2043
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002044static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2045 Py_INCREF(self->ctx);
2046 return self->ctx;
2047}
2048
2049static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2050 void *closure) {
2051
2052 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002053#if !HAVE_SNI
2054 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2055 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002056 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002057#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002058 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002059 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002060 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002061#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002062 } else {
2063 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2064 return -1;
2065 }
2066
2067 return 0;
2068}
2069
2070PyDoc_STRVAR(PySSL_set_context_doc,
2071"_setter_context(ctx)\n\
2072\
2073This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002074used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002075on the SSLContext to change the certificate information associated with the\n\
2076SSLSocket before the cryptographic exchange handshake messages\n");
2077
2078
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002079static PyObject *
2080PySSL_get_server_side(PySSLSocket *self, void *c)
2081{
2082 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2083}
2084
2085PyDoc_STRVAR(PySSL_get_server_side_doc,
2086"Whether this is a server-side socket.");
2087
2088static PyObject *
2089PySSL_get_server_hostname(PySSLSocket *self, void *c)
2090{
2091 if (self->server_hostname == NULL)
2092 Py_RETURN_NONE;
2093 Py_INCREF(self->server_hostname);
2094 return self->server_hostname;
2095}
2096
2097PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2098"The currently set server hostname (for SNI).");
2099
2100static PyObject *
2101PySSL_get_owner(PySSLSocket *self, void *c)
2102{
2103 PyObject *owner;
2104
2105 if (self->owner == NULL)
2106 Py_RETURN_NONE;
2107
2108 owner = PyWeakref_GetObject(self->owner);
2109 Py_INCREF(owner);
2110 return owner;
2111}
2112
2113static int
2114PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2115{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002116 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002117 if (self->owner == NULL)
2118 return -1;
2119 return 0;
2120}
2121
2122PyDoc_STRVAR(PySSL_get_owner_doc,
2123"The Python-level owner of this object.\
2124Passed as \"self\" in servername callback.");
2125
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002126
Antoine Pitrou152efa22010-05-16 18:19:27 +00002127static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002128{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002129 if (self->ssl)
2130 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002131 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002132 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002133 Py_XDECREF(self->server_hostname);
2134 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002136}
2137
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002138/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002139 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002140 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002141 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002142
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002143static int
Victor Stinner14690702015-04-06 22:46:13 +02002144PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002145{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002146 int rc;
2147#ifdef HAVE_POLL
2148 struct pollfd pollfd;
2149 _PyTime_t ms;
2150#else
2151 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002152 fd_set fds;
2153 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002154#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002157 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002159 else if (timeout < 0) {
2160 if (s->sock_timeout > 0)
2161 return SOCKET_HAS_TIMED_OUT;
2162 else
2163 return SOCKET_IS_BLOCKING;
2164 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002167 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002168 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002170 /* Prefer poll, if available, since you can poll() any fd
2171 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002172#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002173 pollfd.fd = s->sock_fd;
2174 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002175
Victor Stinner14690702015-04-06 22:46:13 +02002176 /* timeout is in seconds, poll() uses milliseconds */
2177 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002178 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002179
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002180 PySSL_BEGIN_ALLOW_THREADS
2181 rc = poll(&pollfd, 1, (int)ms);
2182 PySSL_END_ALLOW_THREADS
2183#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002185 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002187
Victor Stinner14690702015-04-06 22:46:13 +02002188 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002189
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002190 FD_ZERO(&fds);
2191 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002192
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002193 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002195 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002197 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002199 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002201#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002202
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2204 (when we are able to write or when there's something to read) */
2205 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002206}
2207
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002208/*[clinic input]
2209_ssl._SSLSocket.write
2210 b: Py_buffer
2211 /
2212
2213Writes the bytes-like object b into the SSL object.
2214
2215Returns the number of bytes written.
2216[clinic start generated code]*/
2217
2218static PyObject *
2219_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2220/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002221{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 int len;
2223 int sockstate;
2224 int err;
2225 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002226 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002227 _PyTime_t timeout, deadline = 0;
2228 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002229
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002230 if (sock != NULL) {
2231 if (((PyObject*)sock) == Py_None) {
2232 _setSSLError("Underlying socket connection gone",
2233 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2234 return NULL;
2235 }
2236 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237 }
2238
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002239 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002240 PyErr_Format(PyExc_OverflowError,
2241 "string longer than %d bytes", INT_MAX);
2242 goto error;
2243 }
2244
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002245 if (sock != NULL) {
2246 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002247 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002248 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2249 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2250 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251
Victor Stinner14690702015-04-06 22:46:13 +02002252 timeout = GET_SOCKET_TIMEOUT(sock);
2253 has_timeout = (timeout > 0);
2254 if (has_timeout)
2255 deadline = _PyTime_GetMonotonicClock() + timeout;
2256
2257 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002259 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 "The write operation timed out");
2261 goto error;
2262 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2263 PyErr_SetString(PySSLErrorObject,
2264 "Underlying socket has been closed.");
2265 goto error;
2266 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2267 PyErr_SetString(PySSLErrorObject,
2268 "Underlying socket too large for select().");
2269 goto error;
2270 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002274 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002275 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002277 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002278
2279 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002281
Victor Stinner14690702015-04-06 22:46:13 +02002282 if (has_timeout)
2283 timeout = deadline - _PyTime_GetMonotonicClock();
2284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002286 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002288 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 } else {
2290 sockstate = SOCKET_OPERATION_OK;
2291 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002294 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 "The write operation timed out");
2296 goto error;
2297 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2298 PyErr_SetString(PySSLErrorObject,
2299 "Underlying socket has been closed.");
2300 goto error;
2301 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2302 break;
2303 }
2304 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002305
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002306 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002307 if (len > 0)
2308 return PyLong_FromLong(len);
2309 else
2310 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002311
2312error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002313 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002314 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002315}
2316
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002317/*[clinic input]
2318_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002319
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002320Returns the number of already decrypted bytes available for read, pending on the connection.
2321[clinic start generated code]*/
2322
2323static PyObject *
2324_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2325/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002326{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002327 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002329 PySSL_BEGIN_ALLOW_THREADS
2330 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002331 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 PySSL_END_ALLOW_THREADS
2333 if (count < 0)
2334 return PySSL_SetError(self, count, __FILE__, __LINE__);
2335 else
2336 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002337}
2338
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002339/*[clinic input]
2340_ssl._SSLSocket.read
2341 size as len: int
2342 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002343 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002344 ]
2345 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002346
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002347Read up to size bytes from the SSL socket.
2348[clinic start generated code]*/
2349
2350static PyObject *
2351_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2352 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002353/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002354{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002357 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 int sockstate;
2359 int err;
2360 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002361 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002362 _PyTime_t timeout, deadline = 0;
2363 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002364
Martin Panter5503d472016-03-27 05:35:19 +00002365 if (!group_right_1 && len < 0) {
2366 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2367 return NULL;
2368 }
2369
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002370 if (sock != NULL) {
2371 if (((PyObject*)sock) == Py_None) {
2372 _setSSLError("Underlying socket connection gone",
2373 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2374 return NULL;
2375 }
2376 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 }
2378
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002379 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002380 dest = PyBytes_FromStringAndSize(NULL, len);
2381 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002382 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002383 if (len == 0) {
2384 Py_XDECREF(sock);
2385 return dest;
2386 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002387 mem = PyBytes_AS_STRING(dest);
2388 }
2389 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002390 mem = buffer->buf;
2391 if (len <= 0 || len > buffer->len) {
2392 len = (int) buffer->len;
2393 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002394 PyErr_SetString(PyExc_OverflowError,
2395 "maximum length can't fit in a C 'int'");
2396 goto error;
2397 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002398 if (len == 0) {
2399 count = 0;
2400 goto done;
2401 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002402 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002403 }
2404
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002405 if (sock != NULL) {
2406 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002407 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002408 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2409 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2410 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002411
Victor Stinner14690702015-04-06 22:46:13 +02002412 timeout = GET_SOCKET_TIMEOUT(sock);
2413 has_timeout = (timeout > 0);
2414 if (has_timeout)
2415 deadline = _PyTime_GetMonotonicClock() + timeout;
2416
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002417 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002418 PySSL_BEGIN_ALLOW_THREADS
2419 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002420 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002421 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002423 if (PyErr_CheckSignals())
2424 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002425
Victor Stinner14690702015-04-06 22:46:13 +02002426 if (has_timeout)
2427 timeout = deadline - _PyTime_GetMonotonicClock();
2428
Steve Dowere6eb48c2017-09-08 15:16:15 -07002429 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002430 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002431 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002433 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002434 } else if (err == SSL_ERROR_ZERO_RETURN &&
2435 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002436 {
2437 count = 0;
2438 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002440 else
2441 sockstate = SOCKET_OPERATION_OK;
2442
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002443 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002444 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 "The read operation timed out");
2446 goto error;
2447 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2448 break;
2449 }
2450 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 if (count <= 0) {
2453 PySSL_SetError(self, count, __FILE__, __LINE__);
2454 goto error;
2455 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002456
2457done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002458 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002459 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002460 _PyBytes_Resize(&dest, count);
2461 return dest;
2462 }
2463 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002464 return PyLong_FromLong(count);
2465 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002466
2467error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002468 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002469 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002470 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002472}
2473
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002474/*[clinic input]
2475_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002476
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002477Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002478[clinic start generated code]*/
2479
2480static PyObject *
2481_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002482/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002483{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002484 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002485 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002486 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002487 _PyTime_t timeout, deadline = 0;
2488 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002489
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002490 if (sock != NULL) {
2491 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002492 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002493 _setSSLError("Underlying socket connection gone",
2494 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2495 return NULL;
2496 }
2497 Py_INCREF(sock);
2498
2499 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002500 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002501 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2502 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002503 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002504
Victor Stinner14690702015-04-06 22:46:13 +02002505 timeout = GET_SOCKET_TIMEOUT(sock);
2506 has_timeout = (timeout > 0);
2507 if (has_timeout)
2508 deadline = _PyTime_GetMonotonicClock() + timeout;
2509
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002510 while (1) {
2511 PySSL_BEGIN_ALLOW_THREADS
2512 /* Disable read-ahead so that unwrap can work correctly.
2513 * Otherwise OpenSSL might read in too much data,
2514 * eating clear text data that happens to be
2515 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002516 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517 * function is used and the shutdown_seen_zero != 0
2518 * condition is met.
2519 */
2520 if (self->shutdown_seen_zero)
2521 SSL_set_read_ahead(self->ssl, 0);
2522 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002523 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002526 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2527 if (err > 0)
2528 break;
2529 if (err == 0) {
2530 /* Don't loop endlessly; instead preserve legacy
2531 behaviour of trying SSL_shutdown() only twice.
2532 This looks necessary for OpenSSL < 0.9.8m */
2533 if (++zeros > 1)
2534 break;
2535 /* Shutdown was sent, now try receiving */
2536 self->shutdown_seen_zero = 1;
2537 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002538 }
2539
Victor Stinner14690702015-04-06 22:46:13 +02002540 if (has_timeout)
2541 timeout = deadline - _PyTime_GetMonotonicClock();
2542
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002543 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002544 _PySSL_UPDATE_ERRNO(self, err);
2545 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002546 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002547 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002548 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002549 else
2550 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002551
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002552 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002553 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002554 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002555 "The read operation timed out");
2556 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002557 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002558 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002559 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 }
2561 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2562 PyErr_SetString(PySSLErrorObject,
2563 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002564 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002565 }
2566 else if (sockstate != SOCKET_OPERATION_OK)
2567 /* Retain the SSL error code */
2568 break;
2569 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002570
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002571 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002572 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002574 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002575 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002576 /* It's already INCREF'ed */
2577 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002578 else
2579 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002580
2581error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002582 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002583 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002584}
2585
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002586/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002587_ssl._SSLSocket.get_channel_binding
2588 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002589
Christian Heimes141c5e82018-02-24 21:10:57 +01002590Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002591
Christian Heimes141c5e82018-02-24 21:10:57 +01002592Raise ValueError if the requested `cb_type` is not supported. Return bytes
2593of the data or None if the data is not available (e.g. before the handshake).
2594Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002595[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002596
Antoine Pitroud6494802011-07-21 01:11:30 +02002597static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002598_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2599 const char *cb_type)
2600/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002601{
Antoine Pitroud6494802011-07-21 01:11:30 +02002602 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002603 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002604
Christian Heimes141c5e82018-02-24 21:10:57 +01002605 if (strcmp(cb_type, "tls-unique") == 0) {
2606 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2607 /* if session is resumed XOR we are the client */
2608 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2609 }
2610 else {
2611 /* if a new session XOR we are the server */
2612 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2613 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002614 }
2615 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002616 PyErr_Format(
2617 PyExc_ValueError,
2618 "'%s' channel binding type not implemented",
2619 cb_type
2620 );
2621 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002622 }
2623
2624 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002625 if (len == 0)
2626 Py_RETURN_NONE;
2627
Christian Heimes141c5e82018-02-24 21:10:57 +01002628 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002629}
2630
Christian Heimes99a65702016-09-10 23:44:53 +02002631#ifdef OPENSSL_VERSION_1_1
2632
2633static SSL_SESSION*
2634_ssl_session_dup(SSL_SESSION *session) {
2635 SSL_SESSION *newsession = NULL;
2636 int slen;
2637 unsigned char *senc = NULL, *p;
2638 const unsigned char *const_p;
2639
2640 if (session == NULL) {
2641 PyErr_SetString(PyExc_ValueError, "Invalid session");
2642 goto error;
2643 }
2644
2645 /* get length */
2646 slen = i2d_SSL_SESSION(session, NULL);
2647 if (slen == 0 || slen > 0xFF00) {
2648 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2649 goto error;
2650 }
2651 if ((senc = PyMem_Malloc(slen)) == NULL) {
2652 PyErr_NoMemory();
2653 goto error;
2654 }
2655 p = senc;
2656 if (!i2d_SSL_SESSION(session, &p)) {
2657 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2658 goto error;
2659 }
2660 const_p = senc;
2661 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2662 if (session == NULL) {
2663 goto error;
2664 }
2665 PyMem_Free(senc);
2666 return newsession;
2667 error:
2668 if (senc != NULL) {
2669 PyMem_Free(senc);
2670 }
2671 return NULL;
2672}
2673#endif
2674
2675static PyObject *
2676PySSL_get_session(PySSLSocket *self, void *closure) {
2677 /* get_session can return sessions from a server-side connection,
2678 * it does not check for handshake done or client socket. */
2679 PySSLSession *pysess;
2680 SSL_SESSION *session;
2681
2682#ifdef OPENSSL_VERSION_1_1
2683 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2684 * https://github.com/openssl/openssl/issues/1550 */
2685 session = SSL_get0_session(self->ssl); /* borrowed reference */
2686 if (session == NULL) {
2687 Py_RETURN_NONE;
2688 }
2689 if ((session = _ssl_session_dup(session)) == NULL) {
2690 return NULL;
2691 }
2692#else
2693 session = SSL_get1_session(self->ssl);
2694 if (session == NULL) {
2695 Py_RETURN_NONE;
2696 }
2697#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002698 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002699 if (pysess == NULL) {
2700 SSL_SESSION_free(session);
2701 return NULL;
2702 }
2703
2704 assert(self->ctx);
2705 pysess->ctx = self->ctx;
2706 Py_INCREF(pysess->ctx);
2707 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002708 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002709 return (PyObject *)pysess;
2710}
2711
2712static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2713 void *closure)
2714 {
2715 PySSLSession *pysess;
2716#ifdef OPENSSL_VERSION_1_1
2717 SSL_SESSION *session;
2718#endif
2719 int result;
2720
2721 if (!PySSLSession_Check(value)) {
2722 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2723 return -1;
2724 }
2725 pysess = (PySSLSession *)value;
2726
2727 if (self->ctx->ctx != pysess->ctx->ctx) {
2728 PyErr_SetString(PyExc_ValueError,
2729 "Session refers to a different SSLContext.");
2730 return -1;
2731 }
2732 if (self->socket_type != PY_SSL_CLIENT) {
2733 PyErr_SetString(PyExc_ValueError,
2734 "Cannot set session for server-side SSLSocket.");
2735 return -1;
2736 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002737 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002738 PyErr_SetString(PyExc_ValueError,
2739 "Cannot set session after handshake.");
2740 return -1;
2741 }
2742#ifdef OPENSSL_VERSION_1_1
2743 /* duplicate session */
2744 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2745 return -1;
2746 }
2747 result = SSL_set_session(self->ssl, session);
2748 /* free duplicate, SSL_set_session() bumps ref count */
2749 SSL_SESSION_free(session);
2750#else
2751 result = SSL_set_session(self->ssl, pysess->session);
2752#endif
2753 if (result == 0) {
2754 _setSSLError(NULL, 0, __FILE__, __LINE__);
2755 return -1;
2756 }
2757 return 0;
2758}
2759
2760PyDoc_STRVAR(PySSL_set_session_doc,
2761"_setter_session(session)\n\
2762\
2763Get / set SSLSession.");
2764
2765static PyObject *
2766PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2767 if (SSL_session_reused(self->ssl)) {
2768 Py_RETURN_TRUE;
2769 } else {
2770 Py_RETURN_FALSE;
2771 }
2772}
2773
2774PyDoc_STRVAR(PySSL_get_session_reused_doc,
2775"Was the client session reused during handshake?");
2776
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002777static PyGetSetDef ssl_getsetlist[] = {
2778 {"context", (getter) PySSL_get_context,
2779 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002780 {"server_side", (getter) PySSL_get_server_side, NULL,
2781 PySSL_get_server_side_doc},
2782 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2783 PySSL_get_server_hostname_doc},
2784 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2785 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002786 {"session", (getter) PySSL_get_session,
2787 (setter) PySSL_set_session, PySSL_set_session_doc},
2788 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2789 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002790 {NULL}, /* sentinel */
2791};
2792
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002793static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002794 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2795 _SSL__SSLSOCKET_WRITE_METHODDEF
2796 _SSL__SSLSOCKET_READ_METHODDEF
2797 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002798 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2799 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002800 _SSL__SSLSOCKET_CIPHER_METHODDEF
2801 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2802 _SSL__SSLSOCKET_VERSION_METHODDEF
2803 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2804 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2805 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2806 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002807 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002808};
2809
Antoine Pitrou152efa22010-05-16 18:19:27 +00002810static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002811 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002812 "_ssl._SSLSocket", /*tp_name*/
2813 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002814 0, /*tp_itemsize*/
2815 /* methods */
2816 (destructor)PySSL_dealloc, /*tp_dealloc*/
2817 0, /*tp_print*/
2818 0, /*tp_getattr*/
2819 0, /*tp_setattr*/
2820 0, /*tp_reserved*/
2821 0, /*tp_repr*/
2822 0, /*tp_as_number*/
2823 0, /*tp_as_sequence*/
2824 0, /*tp_as_mapping*/
2825 0, /*tp_hash*/
2826 0, /*tp_call*/
2827 0, /*tp_str*/
2828 0, /*tp_getattro*/
2829 0, /*tp_setattro*/
2830 0, /*tp_as_buffer*/
2831 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2832 0, /*tp_doc*/
2833 0, /*tp_traverse*/
2834 0, /*tp_clear*/
2835 0, /*tp_richcompare*/
2836 0, /*tp_weaklistoffset*/
2837 0, /*tp_iter*/
2838 0, /*tp_iternext*/
2839 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002840 0, /*tp_members*/
2841 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002842};
2843
Antoine Pitrou152efa22010-05-16 18:19:27 +00002844
2845/*
2846 * _SSLContext objects
2847 */
2848
Christian Heimes5fe668c2016-09-12 00:01:11 +02002849static int
2850_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2851{
2852 int mode;
2853 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2854
2855 switch(n) {
2856 case PY_SSL_CERT_NONE:
2857 mode = SSL_VERIFY_NONE;
2858 break;
2859 case PY_SSL_CERT_OPTIONAL:
2860 mode = SSL_VERIFY_PEER;
2861 break;
2862 case PY_SSL_CERT_REQUIRED:
2863 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2864 break;
2865 default:
2866 PyErr_SetString(PyExc_ValueError,
2867 "invalid value for verify_mode");
2868 return -1;
2869 }
2870 /* keep current verify cb */
2871 verify_cb = SSL_CTX_get_verify_callback(ctx);
2872 SSL_CTX_set_verify(ctx, mode, verify_cb);
2873 return 0;
2874}
2875
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002876/*[clinic input]
2877@classmethod
2878_ssl._SSLContext.__new__
2879 protocol as proto_version: int
2880 /
2881[clinic start generated code]*/
2882
Antoine Pitrou152efa22010-05-16 18:19:27 +00002883static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002884_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2885/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002886{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002887 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002888 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002889 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002890 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002891 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002892#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002893 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002894#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002895
Antoine Pitrou152efa22010-05-16 18:19:27 +00002896 PySSL_BEGIN_ALLOW_THREADS
2897 if (proto_version == PY_SSL_VERSION_TLS1)
2898 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002899#if HAVE_TLSv1_2
2900 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2901 ctx = SSL_CTX_new(TLSv1_1_method());
2902 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2903 ctx = SSL_CTX_new(TLSv1_2_method());
2904#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002905#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002906 else if (proto_version == PY_SSL_VERSION_SSL3)
2907 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002908#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002909#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002910 else if (proto_version == PY_SSL_VERSION_SSL2)
2911 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002912#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002913 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002914 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002915 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2916 ctx = SSL_CTX_new(TLS_client_method());
2917 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2918 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002919 else
2920 proto_version = -1;
2921 PySSL_END_ALLOW_THREADS
2922
2923 if (proto_version == -1) {
2924 PyErr_SetString(PyExc_ValueError,
2925 "invalid protocol version");
2926 return NULL;
2927 }
2928 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002929 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002930 return NULL;
2931 }
2932
2933 assert(type != NULL && type->tp_alloc != NULL);
2934 self = (PySSLContext *) type->tp_alloc(type, 0);
2935 if (self == NULL) {
2936 SSL_CTX_free(ctx);
2937 return NULL;
2938 }
2939 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002940 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002941 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002942#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002943 self->npn_protocols = NULL;
2944#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002945#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002946 self->alpn_protocols = NULL;
2947#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002948#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002949 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002950#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002951 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002952 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2953 self->check_hostname = 1;
2954 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2955 Py_DECREF(self);
2956 return NULL;
2957 }
2958 } else {
2959 self->check_hostname = 0;
2960 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2961 Py_DECREF(self);
2962 return NULL;
2963 }
2964 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002965 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002966 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2967 if (proto_version != PY_SSL_VERSION_SSL2)
2968 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002969 if (proto_version != PY_SSL_VERSION_SSL3)
2970 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002971 /* Minimal security flags for server and client side context.
2972 * Client sockets ignore server-side parameters. */
2973#ifdef SSL_OP_NO_COMPRESSION
2974 options |= SSL_OP_NO_COMPRESSION;
2975#endif
2976#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2977 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2978#endif
2979#ifdef SSL_OP_SINGLE_DH_USE
2980 options |= SSL_OP_SINGLE_DH_USE;
2981#endif
2982#ifdef SSL_OP_SINGLE_ECDH_USE
2983 options |= SSL_OP_SINGLE_ECDH_USE;
2984#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002985 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002986
Semen Zhydenko1295e112017-10-15 21:28:31 +02002987 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002988 * It's far from perfect but gives users a better head start. */
2989 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002990#if PY_SSL_DEFAULT_CIPHERS == 2
2991 /* stick to OpenSSL's default settings */
2992 result = 1;
2993#else
2994 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2995#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002996 } else {
2997 /* SSLv2 needs MD5 */
2998 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2999 }
3000 if (result == 0) {
3001 Py_DECREF(self);
3002 ERR_clear_error();
3003 PyErr_SetString(PySSLErrorObject,
3004 "No cipher can be selected.");
3005 return NULL;
3006 }
3007
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003008#if defined(SSL_MODE_RELEASE_BUFFERS)
3009 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3010 usage for no cost at all. However, don't do this for OpenSSL versions
3011 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3012 2014-0198. I can't find exactly which beta fixed this CVE, so be
3013 conservative and assume it wasn't fixed until release. We do this check
3014 at runtime to avoid problems from the dynamic linker.
3015 See #25672 for more on this. */
3016 libver = SSLeay();
3017 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3018 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3019 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3020 }
3021#endif
3022
3023
Donald Stufft8ae264c2017-03-02 11:45:29 -05003024#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003025 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3026 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003027 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3028 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003029#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003030 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3031#else
3032 {
3033 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3034 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3035 EC_KEY_free(key);
3036 }
3037#endif
3038#endif
3039
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003040#define SID_CTX "Python"
3041 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3042 sizeof(SID_CTX));
3043#undef SID_CTX
3044
Christian Heimes61d478c2018-01-27 15:51:38 +01003045 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003046#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003047 /* Improve trust chain building when cross-signed intermediate
3048 certificates are present. See https://bugs.python.org/issue23476. */
3049 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003050#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003051 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003052
Antoine Pitrou152efa22010-05-16 18:19:27 +00003053 return (PyObject *)self;
3054}
3055
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003056static int
3057context_traverse(PySSLContext *self, visitproc visit, void *arg)
3058{
3059#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003060 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003061#endif
3062 return 0;
3063}
3064
3065static int
3066context_clear(PySSLContext *self)
3067{
3068#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003069 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003070#endif
3071 return 0;
3072}
3073
Antoine Pitrou152efa22010-05-16 18:19:27 +00003074static void
3075context_dealloc(PySSLContext *self)
3076{
INADA Naokia6296d32017-08-24 14:55:17 +09003077 /* bpo-31095: UnTrack is needed before calling any callbacks */
3078 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003079 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003080 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003081#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003082 PyMem_FREE(self->npn_protocols);
3083#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003084#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003085 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003086#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003087 Py_TYPE(self)->tp_free(self);
3088}
3089
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003090/*[clinic input]
3091_ssl._SSLContext.set_ciphers
3092 cipherlist: str
3093 /
3094[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003096static PyObject *
3097_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3098/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3099{
3100 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003101 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003102 /* Clearing the error queue is necessary on some OpenSSL versions,
3103 otherwise the error will be reported again when another SSL call
3104 is done. */
3105 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003106 PyErr_SetString(PySSLErrorObject,
3107 "No cipher can be selected.");
3108 return NULL;
3109 }
3110 Py_RETURN_NONE;
3111}
3112
Christian Heimes25bfcd52016-09-06 00:04:45 +02003113#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3114/*[clinic input]
3115_ssl._SSLContext.get_ciphers
3116[clinic start generated code]*/
3117
3118static PyObject *
3119_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3120/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3121{
3122 SSL *ssl = NULL;
3123 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003124 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003125 int i=0;
3126 PyObject *result = NULL, *dct;
3127
3128 ssl = SSL_new(self->ctx);
3129 if (ssl == NULL) {
3130 _setSSLError(NULL, 0, __FILE__, __LINE__);
3131 goto exit;
3132 }
3133 sk = SSL_get_ciphers(ssl);
3134
3135 result = PyList_New(sk_SSL_CIPHER_num(sk));
3136 if (result == NULL) {
3137 goto exit;
3138 }
3139
3140 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3141 cipher = sk_SSL_CIPHER_value(sk, i);
3142 dct = cipher_to_dict(cipher);
3143 if (dct == NULL) {
3144 Py_CLEAR(result);
3145 goto exit;
3146 }
3147 PyList_SET_ITEM(result, i, dct);
3148 }
3149
3150 exit:
3151 if (ssl != NULL)
3152 SSL_free(ssl);
3153 return result;
3154
3155}
3156#endif
3157
3158
Christian Heimes29eab552018-02-25 12:31:33 +01003159#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003160static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003161do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3162 const unsigned char *server_protocols, unsigned int server_protocols_len,
3163 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003164{
Benjamin Peterson88615022015-01-23 17:30:26 -05003165 int ret;
3166 if (client_protocols == NULL) {
3167 client_protocols = (unsigned char *)"";
3168 client_protocols_len = 0;
3169 }
3170 if (server_protocols == NULL) {
3171 server_protocols = (unsigned char *)"";
3172 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003173 }
3174
Benjamin Peterson88615022015-01-23 17:30:26 -05003175 ret = SSL_select_next_proto(out, outlen,
3176 server_protocols, server_protocols_len,
3177 client_protocols, client_protocols_len);
3178 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3179 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003180
3181 return SSL_TLSEXT_ERR_OK;
3182}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003183#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003184
Christian Heimes29eab552018-02-25 12:31:33 +01003185#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003186/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3187static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003188_advertiseNPN_cb(SSL *s,
3189 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003190 void *args)
3191{
3192 PySSLContext *ssl_ctx = (PySSLContext *) args;
3193
3194 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003195 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003196 *len = 0;
3197 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003198 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003199 *len = ssl_ctx->npn_protocols_len;
3200 }
3201
3202 return SSL_TLSEXT_ERR_OK;
3203}
3204/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3205static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003206_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003207 unsigned char **out, unsigned char *outlen,
3208 const unsigned char *server, unsigned int server_len,
3209 void *args)
3210{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003211 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003212 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003213 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003214}
3215#endif
3216
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003217/*[clinic input]
3218_ssl._SSLContext._set_npn_protocols
3219 protos: Py_buffer
3220 /
3221[clinic start generated code]*/
3222
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003223static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003224_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3225 Py_buffer *protos)
3226/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003227{
Christian Heimes29eab552018-02-25 12:31:33 +01003228#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003229 PyMem_Free(self->npn_protocols);
3230 self->npn_protocols = PyMem_Malloc(protos->len);
3231 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003232 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003233 memcpy(self->npn_protocols, protos->buf, protos->len);
3234 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003235
3236 /* set both server and client callbacks, because the context can
3237 * be used to create both types of sockets */
3238 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3239 _advertiseNPN_cb,
3240 self);
3241 SSL_CTX_set_next_proto_select_cb(self->ctx,
3242 _selectNPN_cb,
3243 self);
3244
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003245 Py_RETURN_NONE;
3246#else
3247 PyErr_SetString(PyExc_NotImplementedError,
3248 "The NPN extension requires OpenSSL 1.0.1 or later.");
3249 return NULL;
3250#endif
3251}
3252
Christian Heimes29eab552018-02-25 12:31:33 +01003253#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003254static int
3255_selectALPN_cb(SSL *s,
3256 const unsigned char **out, unsigned char *outlen,
3257 const unsigned char *client_protocols, unsigned int client_protocols_len,
3258 void *args)
3259{
3260 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003261 return do_protocol_selection(1, (unsigned char **)out, outlen,
3262 ctx->alpn_protocols, ctx->alpn_protocols_len,
3263 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003264}
3265#endif
3266
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003267/*[clinic input]
3268_ssl._SSLContext._set_alpn_protocols
3269 protos: Py_buffer
3270 /
3271[clinic start generated code]*/
3272
Benjamin Petersoncca27322015-01-23 16:35:37 -05003273static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003274_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3275 Py_buffer *protos)
3276/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003277{
Christian Heimes29eab552018-02-25 12:31:33 +01003278#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003279 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003280 PyErr_Format(PyExc_OverflowError,
3281 "protocols longer than %d bytes", UINT_MAX);
3282 return NULL;
3283 }
3284
Benjamin Petersoncca27322015-01-23 16:35:37 -05003285 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003286 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003287 if (!self->alpn_protocols)
3288 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003289 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003290 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003291
3292 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3293 return PyErr_NoMemory();
3294 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3295
Benjamin Petersoncca27322015-01-23 16:35:37 -05003296 Py_RETURN_NONE;
3297#else
3298 PyErr_SetString(PyExc_NotImplementedError,
3299 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3300 return NULL;
3301#endif
3302}
3303
Antoine Pitrou152efa22010-05-16 18:19:27 +00003304static PyObject *
3305get_verify_mode(PySSLContext *self, void *c)
3306{
3307 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3308 case SSL_VERIFY_NONE:
3309 return PyLong_FromLong(PY_SSL_CERT_NONE);
3310 case SSL_VERIFY_PEER:
3311 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3312 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3313 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3314 }
3315 PyErr_SetString(PySSLErrorObject,
3316 "invalid return value from SSL_CTX_get_verify_mode");
3317 return NULL;
3318}
3319
3320static int
3321set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3322{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003323 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003324 if (!PyArg_Parse(arg, "i", &n))
3325 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003326 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003327 PyErr_SetString(PyExc_ValueError,
3328 "Cannot set verify_mode to CERT_NONE when "
3329 "check_hostname is enabled.");
3330 return -1;
3331 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003332 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003333}
3334
3335static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003336get_verify_flags(PySSLContext *self, void *c)
3337{
Christian Heimes598894f2016-09-05 23:19:05 +02003338 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003339 unsigned long flags;
3340
Christian Heimes61d478c2018-01-27 15:51:38 +01003341 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003342 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003343 return PyLong_FromUnsignedLong(flags);
3344}
3345
3346static int
3347set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3348{
Christian Heimes598894f2016-09-05 23:19:05 +02003349 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003350 unsigned long new_flags, flags, set, clear;
3351
3352 if (!PyArg_Parse(arg, "k", &new_flags))
3353 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003354 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003355 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003356 clear = flags & ~new_flags;
3357 set = ~flags & new_flags;
3358 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003359 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003360 _setSSLError(NULL, 0, __FILE__, __LINE__);
3361 return -1;
3362 }
3363 }
3364 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003365 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003366 _setSSLError(NULL, 0, __FILE__, __LINE__);
3367 return -1;
3368 }
3369 }
3370 return 0;
3371}
3372
Christian Heimes698dde12018-02-27 11:54:43 +01003373/* Getter and setter for protocol version */
3374#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3375
3376
3377static int
3378set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3379{
3380 long v;
3381 int result;
3382
3383 if (!PyArg_Parse(arg, "l", &v))
3384 return -1;
3385 if (v > INT_MAX) {
3386 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3387 return -1;
3388 }
3389
3390 switch(self->protocol) {
3391 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3392 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3393 case PY_SSL_VERSION_TLS:
3394 break;
3395 default:
3396 PyErr_SetString(
3397 PyExc_ValueError,
3398 "The context's protocol doesn't support modification of "
3399 "highest and lowest version."
3400 );
3401 return -1;
3402 }
3403
3404 if (what == 0) {
3405 switch(v) {
3406 case PY_PROTO_MINIMUM_SUPPORTED:
3407 v = 0;
3408 break;
3409 case PY_PROTO_MAXIMUM_SUPPORTED:
3410 /* Emulate max for set_min_proto_version */
3411 v = PY_PROTO_MAXIMUM_AVAILABLE;
3412 break;
3413 default:
3414 break;
3415 }
3416 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3417 }
3418 else {
3419 switch(v) {
3420 case PY_PROTO_MAXIMUM_SUPPORTED:
3421 v = 0;
3422 break;
3423 case PY_PROTO_MINIMUM_SUPPORTED:
3424 /* Emulate max for set_min_proto_version */
3425 v = PY_PROTO_MINIMUM_AVAILABLE;
3426 break;
3427 default:
3428 break;
3429 }
3430 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3431 }
3432 if (result == 0) {
3433 PyErr_Format(PyExc_ValueError,
3434 "Unsupported protocol version 0x%x", v);
3435 return -1;
3436 }
3437 return 0;
3438}
3439
3440static PyObject *
3441get_minimum_version(PySSLContext *self, void *c)
3442{
3443 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3444 if (v == 0) {
3445 v = PY_PROTO_MINIMUM_SUPPORTED;
3446 }
3447 return PyLong_FromLong(v);
3448}
3449
3450static int
3451set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3452{
3453 return set_min_max_proto_version(self, arg, 0);
3454}
3455
3456static PyObject *
3457get_maximum_version(PySSLContext *self, void *c)
3458{
3459 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3460 if (v == 0) {
3461 v = PY_PROTO_MAXIMUM_SUPPORTED;
3462 }
3463 return PyLong_FromLong(v);
3464}
3465
3466static int
3467set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3468{
3469 return set_min_max_proto_version(self, arg, 1);
3470}
3471#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3472
Christian Heimes22587792013-11-21 23:56:13 +01003473static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003474get_options(PySSLContext *self, void *c)
3475{
3476 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3477}
3478
3479static int
3480set_options(PySSLContext *self, PyObject *arg, void *c)
3481{
3482 long new_opts, opts, set, clear;
3483 if (!PyArg_Parse(arg, "l", &new_opts))
3484 return -1;
3485 opts = SSL_CTX_get_options(self->ctx);
3486 clear = opts & ~new_opts;
3487 set = ~opts & new_opts;
3488 if (clear) {
3489#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3490 SSL_CTX_clear_options(self->ctx, clear);
3491#else
3492 PyErr_SetString(PyExc_ValueError,
3493 "can't clear options before OpenSSL 0.9.8m");
3494 return -1;
3495#endif
3496 }
3497 if (set)
3498 SSL_CTX_set_options(self->ctx, set);
3499 return 0;
3500}
3501
Christian Heimes1aa9a752013-12-02 02:41:19 +01003502static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003503get_host_flags(PySSLContext *self, void *c)
3504{
3505 return PyLong_FromUnsignedLong(self->hostflags);
3506}
3507
3508static int
3509set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3510{
3511 X509_VERIFY_PARAM *param;
3512 unsigned int new_flags = 0;
3513
3514 if (!PyArg_Parse(arg, "I", &new_flags))
3515 return -1;
3516
3517 param = SSL_CTX_get0_param(self->ctx);
3518 self->hostflags = new_flags;
3519 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3520 return 0;
3521}
3522
3523static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003524get_check_hostname(PySSLContext *self, void *c)
3525{
3526 return PyBool_FromLong(self->check_hostname);
3527}
3528
3529static int
3530set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3531{
3532 int check_hostname;
3533 if (!PyArg_Parse(arg, "p", &check_hostname))
3534 return -1;
3535 if (check_hostname &&
3536 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003537 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3538 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3539 return -1;
3540 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003541 }
3542 self->check_hostname = check_hostname;
3543 return 0;
3544}
3545
Christian Heimes11a14932018-02-24 02:35:08 +01003546static PyObject *
3547get_protocol(PySSLContext *self, void *c) {
3548 return PyLong_FromLong(self->protocol);
3549}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003550
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003551typedef struct {
3552 PyThreadState *thread_state;
3553 PyObject *callable;
3554 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003555 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003556 int error;
3557} _PySSLPasswordInfo;
3558
3559static int
3560_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3561 const char *bad_type_error)
3562{
3563 /* Set the password and size fields of a _PySSLPasswordInfo struct
3564 from a unicode, bytes, or byte array object.
3565 The password field will be dynamically allocated and must be freed
3566 by the caller */
3567 PyObject *password_bytes = NULL;
3568 const char *data = NULL;
3569 Py_ssize_t size;
3570
3571 if (PyUnicode_Check(password)) {
3572 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3573 if (!password_bytes) {
3574 goto error;
3575 }
3576 data = PyBytes_AS_STRING(password_bytes);
3577 size = PyBytes_GET_SIZE(password_bytes);
3578 } else if (PyBytes_Check(password)) {
3579 data = PyBytes_AS_STRING(password);
3580 size = PyBytes_GET_SIZE(password);
3581 } else if (PyByteArray_Check(password)) {
3582 data = PyByteArray_AS_STRING(password);
3583 size = PyByteArray_GET_SIZE(password);
3584 } else {
3585 PyErr_SetString(PyExc_TypeError, bad_type_error);
3586 goto error;
3587 }
3588
Victor Stinner9ee02032013-06-23 15:08:23 +02003589 if (size > (Py_ssize_t)INT_MAX) {
3590 PyErr_Format(PyExc_ValueError,
3591 "password cannot be longer than %d bytes", INT_MAX);
3592 goto error;
3593 }
3594
Victor Stinner11ebff22013-07-07 17:07:52 +02003595 PyMem_Free(pw_info->password);
3596 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003597 if (!pw_info->password) {
3598 PyErr_SetString(PyExc_MemoryError,
3599 "unable to allocate password buffer");
3600 goto error;
3601 }
3602 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003603 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003604
3605 Py_XDECREF(password_bytes);
3606 return 1;
3607
3608error:
3609 Py_XDECREF(password_bytes);
3610 return 0;
3611}
3612
3613static int
3614_password_callback(char *buf, int size, int rwflag, void *userdata)
3615{
3616 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3617 PyObject *fn_ret = NULL;
3618
3619 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3620
3621 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003622 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003623 if (!fn_ret) {
3624 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3625 core python API, so we could use it to add a frame here */
3626 goto error;
3627 }
3628
3629 if (!_pwinfo_set(pw_info, fn_ret,
3630 "password callback must return a string")) {
3631 goto error;
3632 }
3633 Py_CLEAR(fn_ret);
3634 }
3635
3636 if (pw_info->size > size) {
3637 PyErr_Format(PyExc_ValueError,
3638 "password cannot be longer than %d bytes", size);
3639 goto error;
3640 }
3641
3642 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3643 memcpy(buf, pw_info->password, pw_info->size);
3644 return pw_info->size;
3645
3646error:
3647 Py_XDECREF(fn_ret);
3648 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3649 pw_info->error = 1;
3650 return -1;
3651}
3652
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003653/*[clinic input]
3654_ssl._SSLContext.load_cert_chain
3655 certfile: object
3656 keyfile: object = NULL
3657 password: object = NULL
3658
3659[clinic start generated code]*/
3660
Antoine Pitroub5218772010-05-21 09:56:06 +00003661static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003662_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3663 PyObject *keyfile, PyObject *password)
3664/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003665{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003666 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003667 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3668 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003669 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003670 int r;
3671
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003672 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003673 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003674 if (keyfile == Py_None)
3675 keyfile = NULL;
3676 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3677 PyErr_SetString(PyExc_TypeError,
3678 "certfile should be a valid filesystem path");
3679 return NULL;
3680 }
3681 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3682 PyErr_SetString(PyExc_TypeError,
3683 "keyfile should be a valid filesystem path");
3684 goto error;
3685 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003686 if (password && password != Py_None) {
3687 if (PyCallable_Check(password)) {
3688 pw_info.callable = password;
3689 } else if (!_pwinfo_set(&pw_info, password,
3690 "password should be a string or callable")) {
3691 goto error;
3692 }
3693 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3694 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3695 }
3696 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003697 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3698 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003699 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003700 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003701 if (pw_info.error) {
3702 ERR_clear_error();
3703 /* the password callback has already set the error information */
3704 }
3705 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003706 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003707 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003708 }
3709 else {
3710 _setSSLError(NULL, 0, __FILE__, __LINE__);
3711 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003712 goto error;
3713 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003714 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003715 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003716 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3717 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003718 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3719 Py_CLEAR(keyfile_bytes);
3720 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003721 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003722 if (pw_info.error) {
3723 ERR_clear_error();
3724 /* the password callback has already set the error information */
3725 }
3726 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003727 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003728 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003729 }
3730 else {
3731 _setSSLError(NULL, 0, __FILE__, __LINE__);
3732 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003733 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003734 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003735 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003736 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003737 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003738 if (r != 1) {
3739 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003740 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003741 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003742 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3743 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003744 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003745 Py_RETURN_NONE;
3746
3747error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003748 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3749 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003750 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003751 Py_XDECREF(keyfile_bytes);
3752 Py_XDECREF(certfile_bytes);
3753 return NULL;
3754}
3755
Christian Heimesefff7062013-11-21 03:35:02 +01003756/* internal helper function, returns -1 on error
3757 */
3758static int
3759_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3760 int filetype)
3761{
3762 BIO *biobuf = NULL;
3763 X509_STORE *store;
3764 int retval = 0, err, loaded = 0;
3765
3766 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3767
3768 if (len <= 0) {
3769 PyErr_SetString(PyExc_ValueError,
3770 "Empty certificate data");
3771 return -1;
3772 } else if (len > INT_MAX) {
3773 PyErr_SetString(PyExc_OverflowError,
3774 "Certificate data is too long.");
3775 return -1;
3776 }
3777
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003778 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003779 if (biobuf == NULL) {
3780 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3781 return -1;
3782 }
3783
3784 store = SSL_CTX_get_cert_store(self->ctx);
3785 assert(store != NULL);
3786
3787 while (1) {
3788 X509 *cert = NULL;
3789 int r;
3790
3791 if (filetype == SSL_FILETYPE_ASN1) {
3792 cert = d2i_X509_bio(biobuf, NULL);
3793 } else {
3794 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003795 SSL_CTX_get_default_passwd_cb(self->ctx),
3796 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3797 );
Christian Heimesefff7062013-11-21 03:35:02 +01003798 }
3799 if (cert == NULL) {
3800 break;
3801 }
3802 r = X509_STORE_add_cert(store, cert);
3803 X509_free(cert);
3804 if (!r) {
3805 err = ERR_peek_last_error();
3806 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3807 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3808 /* cert already in hash table, not an error */
3809 ERR_clear_error();
3810 } else {
3811 break;
3812 }
3813 }
3814 loaded++;
3815 }
3816
3817 err = ERR_peek_last_error();
3818 if ((filetype == SSL_FILETYPE_ASN1) &&
3819 (loaded > 0) &&
3820 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3821 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3822 /* EOF ASN1 file, not an error */
3823 ERR_clear_error();
3824 retval = 0;
3825 } else if ((filetype == SSL_FILETYPE_PEM) &&
3826 (loaded > 0) &&
3827 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3828 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3829 /* EOF PEM file, not an error */
3830 ERR_clear_error();
3831 retval = 0;
3832 } else {
3833 _setSSLError(NULL, 0, __FILE__, __LINE__);
3834 retval = -1;
3835 }
3836
3837 BIO_free(biobuf);
3838 return retval;
3839}
3840
3841
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003842/*[clinic input]
3843_ssl._SSLContext.load_verify_locations
3844 cafile: object = NULL
3845 capath: object = NULL
3846 cadata: object = NULL
3847
3848[clinic start generated code]*/
3849
Antoine Pitrou152efa22010-05-16 18:19:27 +00003850static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003851_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3852 PyObject *cafile,
3853 PyObject *capath,
3854 PyObject *cadata)
3855/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003856{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003857 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3858 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003859 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003860
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003861 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003862 if (cafile == Py_None)
3863 cafile = NULL;
3864 if (capath == Py_None)
3865 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003866 if (cadata == Py_None)
3867 cadata = NULL;
3868
3869 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003870 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003871 "cafile, capath and cadata cannot be all omitted");
3872 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003873 }
3874 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3875 PyErr_SetString(PyExc_TypeError,
3876 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003877 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003878 }
3879 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003880 PyErr_SetString(PyExc_TypeError,
3881 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003882 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003883 }
Christian Heimesefff7062013-11-21 03:35:02 +01003884
3885 /* validata cadata type and load cadata */
3886 if (cadata) {
3887 Py_buffer buf;
3888 PyObject *cadata_ascii = NULL;
3889
3890 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3891 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3892 PyBuffer_Release(&buf);
3893 PyErr_SetString(PyExc_TypeError,
3894 "cadata should be a contiguous buffer with "
3895 "a single dimension");
3896 goto error;
3897 }
3898 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3899 PyBuffer_Release(&buf);
3900 if (r == -1) {
3901 goto error;
3902 }
3903 } else {
3904 PyErr_Clear();
3905 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3906 if (cadata_ascii == NULL) {
3907 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003908 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003909 "bytes-like object");
3910 goto error;
3911 }
3912 r = _add_ca_certs(self,
3913 PyBytes_AS_STRING(cadata_ascii),
3914 PyBytes_GET_SIZE(cadata_ascii),
3915 SSL_FILETYPE_PEM);
3916 Py_DECREF(cadata_ascii);
3917 if (r == -1) {
3918 goto error;
3919 }
3920 }
3921 }
3922
3923 /* load cafile or capath */
3924 if (cafile || capath) {
3925 if (cafile)
3926 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3927 if (capath)
3928 capath_buf = PyBytes_AS_STRING(capath_bytes);
3929 PySSL_BEGIN_ALLOW_THREADS
3930 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3931 PySSL_END_ALLOW_THREADS
3932 if (r != 1) {
3933 ok = 0;
3934 if (errno != 0) {
3935 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003936 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003937 }
3938 else {
3939 _setSSLError(NULL, 0, __FILE__, __LINE__);
3940 }
3941 goto error;
3942 }
3943 }
3944 goto end;
3945
3946 error:
3947 ok = 0;
3948 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003949 Py_XDECREF(cafile_bytes);
3950 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003951 if (ok) {
3952 Py_RETURN_NONE;
3953 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003954 return NULL;
3955 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003956}
3957
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003958/*[clinic input]
3959_ssl._SSLContext.load_dh_params
3960 path as filepath: object
3961 /
3962
3963[clinic start generated code]*/
3964
Antoine Pitrou152efa22010-05-16 18:19:27 +00003965static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003966_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3967/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003968{
3969 FILE *f;
3970 DH *dh;
3971
Victor Stinnerdaf45552013-08-28 00:53:59 +02003972 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003973 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003974 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003975
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003976 errno = 0;
3977 PySSL_BEGIN_ALLOW_THREADS
3978 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003979 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003980 PySSL_END_ALLOW_THREADS
3981 if (dh == NULL) {
3982 if (errno != 0) {
3983 ERR_clear_error();
3984 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3985 }
3986 else {
3987 _setSSLError(NULL, 0, __FILE__, __LINE__);
3988 }
3989 return NULL;
3990 }
3991 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3992 _setSSLError(NULL, 0, __FILE__, __LINE__);
3993 DH_free(dh);
3994 Py_RETURN_NONE;
3995}
3996
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003997/*[clinic input]
3998_ssl._SSLContext._wrap_socket
3999 sock: object(subclass_of="PySocketModule.Sock_Type")
4000 server_side: int
4001 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004002 *
4003 owner: object = None
4004 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004005
4006[clinic start generated code]*/
4007
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004008static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004009_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004010 int server_side, PyObject *hostname_obj,
4011 PyObject *owner, PyObject *session)
4012/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004013{
Antoine Pitroud5323212010-10-22 18:19:07 +00004014 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004015 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004016
Antoine Pitroud5323212010-10-22 18:19:07 +00004017 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01004018 as IDN A-label (ASCII str). */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004019 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004020 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004021 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004022 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004024 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4025 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004026 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004027 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004028 if (hostname != NULL)
4029 PyMem_Free(hostname);
4030 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031}
4032
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004033/*[clinic input]
4034_ssl._SSLContext._wrap_bio
4035 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4036 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4037 server_side: int
4038 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004039 *
4040 owner: object = None
4041 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004042
4043[clinic start generated code]*/
4044
Antoine Pitroub0182c82010-10-12 20:09:02 +00004045static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004046_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4047 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004048 PyObject *hostname_obj, PyObject *owner,
4049 PyObject *session)
4050/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004051{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004052 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004053 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004054
4055 /* server_hostname is either None (or absent), or to be encoded
Christian Heimes11a14932018-02-24 02:35:08 +01004056 as IDN A-label (ASCII str). */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004057 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004058 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004059 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004060 }
4061
4062 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004063 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004064 incoming, outgoing);
4065
4066 PyMem_Free(hostname);
4067 return res;
4068}
4069
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004070/*[clinic input]
4071_ssl._SSLContext.session_stats
4072[clinic start generated code]*/
4073
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004074static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004075_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4076/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004077{
4078 int r;
4079 PyObject *value, *stats = PyDict_New();
4080 if (!stats)
4081 return NULL;
4082
4083#define ADD_STATS(SSL_NAME, KEY_NAME) \
4084 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4085 if (value == NULL) \
4086 goto error; \
4087 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4088 Py_DECREF(value); \
4089 if (r < 0) \
4090 goto error;
4091
4092 ADD_STATS(number, "number");
4093 ADD_STATS(connect, "connect");
4094 ADD_STATS(connect_good, "connect_good");
4095 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4096 ADD_STATS(accept, "accept");
4097 ADD_STATS(accept_good, "accept_good");
4098 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4099 ADD_STATS(accept, "accept");
4100 ADD_STATS(hits, "hits");
4101 ADD_STATS(misses, "misses");
4102 ADD_STATS(timeouts, "timeouts");
4103 ADD_STATS(cache_full, "cache_full");
4104
4105#undef ADD_STATS
4106
4107 return stats;
4108
4109error:
4110 Py_DECREF(stats);
4111 return NULL;
4112}
4113
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004114/*[clinic input]
4115_ssl._SSLContext.set_default_verify_paths
4116[clinic start generated code]*/
4117
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004118static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004119_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4120/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004121{
4122 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4123 _setSSLError(NULL, 0, __FILE__, __LINE__);
4124 return NULL;
4125 }
4126 Py_RETURN_NONE;
4127}
4128
Antoine Pitrou501da612011-12-21 09:27:41 +01004129#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004130/*[clinic input]
4131_ssl._SSLContext.set_ecdh_curve
4132 name: object
4133 /
4134
4135[clinic start generated code]*/
4136
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004137static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4139/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004140{
4141 PyObject *name_bytes;
4142 int nid;
4143 EC_KEY *key;
4144
4145 if (!PyUnicode_FSConverter(name, &name_bytes))
4146 return NULL;
4147 assert(PyBytes_Check(name_bytes));
4148 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4149 Py_DECREF(name_bytes);
4150 if (nid == 0) {
4151 PyErr_Format(PyExc_ValueError,
4152 "unknown elliptic curve name %R", name);
4153 return NULL;
4154 }
4155 key = EC_KEY_new_by_curve_name(nid);
4156 if (key == NULL) {
4157 _setSSLError(NULL, 0, __FILE__, __LINE__);
4158 return NULL;
4159 }
4160 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4161 EC_KEY_free(key);
4162 Py_RETURN_NONE;
4163}
Antoine Pitrou501da612011-12-21 09:27:41 +01004164#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004165
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004166#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004167static int
4168_servername_callback(SSL *s, int *al, void *args)
4169{
4170 int ret;
4171 PySSLContext *ssl_ctx = (PySSLContext *) args;
4172 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004173 PyObject *result;
4174 /* The high-level ssl.SSLSocket object */
4175 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004176 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004177 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004178
Christian Heimes11a14932018-02-24 02:35:08 +01004179 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004180 /* remove race condition in this the call back while if removing the
4181 * callback is in progress */
4182 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004183 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004184 }
4185
4186 ssl = SSL_get_app_data(s);
4187 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004189 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004190 * SSL connection and that has a .context attribute that can be changed to
4191 * identify the requested hostname. Since the official API is the Python
4192 * level API we want to pass the callback a Python level object rather than
4193 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4194 * SSLObject) that will be passed. Otherwise if there's a socket then that
4195 * will be passed. If both do not exist only then the C-level object is
4196 * passed. */
4197 if (ssl->owner)
4198 ssl_socket = PyWeakref_GetObject(ssl->owner);
4199 else if (ssl->Socket)
4200 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4201 else
4202 ssl_socket = (PyObject *) ssl;
4203
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004204 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004206 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004207
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004208 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004209 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004210 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004211 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004212 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004213 PyObject *servername_bytes;
4214 PyObject *servername_str;
4215
4216 servername_bytes = PyBytes_FromString(servername);
4217 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004218 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4219 goto error;
4220 }
Christian Heimes11a14932018-02-24 02:35:08 +01004221 /* server_hostname was encoded to an A-label by our caller; put it
4222 * back into a str object, but still as an A-label (bpo-28414)
4223 */
4224 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4225 Py_DECREF(servername_bytes);
4226 if (servername_str == NULL) {
4227 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004228 goto error;
4229 }
Christian Heimes11a14932018-02-24 02:35:08 +01004230 result = PyObject_CallFunctionObjArgs(
4231 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4232 ssl_ctx, NULL);
4233 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004234 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004235 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004236
4237 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004238 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004239 *al = SSL_AD_HANDSHAKE_FAILURE;
4240 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4241 }
4242 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004243 /* Result may be None, a SSLContext or an integer
4244 * None and SSLContext are OK, integer or other values are an error.
4245 */
4246 if (result == Py_None) {
4247 ret = SSL_TLSEXT_ERR_OK;
4248 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004249 *al = (int) PyLong_AsLong(result);
4250 if (PyErr_Occurred()) {
4251 PyErr_WriteUnraisable(result);
4252 *al = SSL_AD_INTERNAL_ERROR;
4253 }
4254 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4255 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004256 Py_DECREF(result);
4257 }
4258
4259 PyGILState_Release(gstate);
4260 return ret;
4261
4262error:
4263 Py_DECREF(ssl_socket);
4264 *al = SSL_AD_INTERNAL_ERROR;
4265 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4266 PyGILState_Release(gstate);
4267 return ret;
4268}
Antoine Pitroua5963382013-03-30 16:39:00 +01004269#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004270
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004271static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004272get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004273{
Christian Heimes11a14932018-02-24 02:35:08 +01004274 PyObject *cb = self->set_sni_cb;
4275 if (cb == NULL) {
4276 Py_RETURN_NONE;
4277 }
4278 Py_INCREF(cb);
4279 return cb;
4280}
4281
4282static int
4283set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4284{
4285 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4286 PyErr_SetString(PyExc_ValueError,
4287 "sni_callback cannot be set on TLS_CLIENT context");
4288 return -1;
4289 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004290#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004291 Py_CLEAR(self->set_sni_cb);
4292 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004293 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4294 }
4295 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004296 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004297 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4298 PyErr_SetString(PyExc_TypeError,
4299 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004300 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004301 }
Christian Heimes11a14932018-02-24 02:35:08 +01004302 Py_INCREF(arg);
4303 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004304 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4305 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4306 }
Christian Heimes11a14932018-02-24 02:35:08 +01004307 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004308#else
4309 PyErr_SetString(PyExc_NotImplementedError,
4310 "The TLS extension servername callback, "
4311 "SSL_CTX_set_tlsext_servername_callback, "
4312 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004313 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004314#endif
4315}
4316
Christian Heimes11a14932018-02-24 02:35:08 +01004317PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4318"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4319\n\
4320If the argument is None then the callback is disabled. The method is called\n\
4321with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4322See RFC 6066 for details of the SNI extension.");
4323
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004324/*[clinic input]
4325_ssl._SSLContext.cert_store_stats
4326
4327Returns quantities of loaded X.509 certificates.
4328
4329X.509 certificates with a CA extension and certificate revocation lists
4330inside the context's cert store.
4331
4332NOTE: Certificates in a capath directory aren't loaded unless they have
4333been used at least once.
4334[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004335
4336static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004337_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4338/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004339{
4340 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004341 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004342 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004343 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004344
4345 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004346 objs = X509_STORE_get0_objects(store);
4347 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4348 obj = sk_X509_OBJECT_value(objs, i);
4349 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004350 case X509_LU_X509:
4351 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004352 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004353 ca++;
4354 }
4355 break;
4356 case X509_LU_CRL:
4357 crl++;
4358 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004359 default:
4360 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4361 * As far as I can tell they are internal states and never
4362 * stored in a cert store */
4363 break;
4364 }
4365 }
4366 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4367 "x509_ca", ca);
4368}
4369
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004370/*[clinic input]
4371_ssl._SSLContext.get_ca_certs
4372 binary_form: bool = False
4373
4374Returns a list of dicts with information of loaded CA certs.
4375
4376If the optional argument is True, returns a DER-encoded copy of the CA
4377certificate.
4378
4379NOTE: Certificates in a capath directory aren't loaded unless they have
4380been used at least once.
4381[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004382
4383static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004384_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4385/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004386{
4387 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004388 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004389 PyObject *ci = NULL, *rlist = NULL;
4390 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004391
4392 if ((rlist = PyList_New(0)) == NULL) {
4393 return NULL;
4394 }
4395
4396 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004397 objs = X509_STORE_get0_objects(store);
4398 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004399 X509_OBJECT *obj;
4400 X509 *cert;
4401
Christian Heimes598894f2016-09-05 23:19:05 +02004402 obj = sk_X509_OBJECT_value(objs, i);
4403 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004404 /* not a x509 cert */
4405 continue;
4406 }
4407 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004408 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004409 if (!X509_check_ca(cert)) {
4410 continue;
4411 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004412 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004413 ci = _certificate_to_der(cert);
4414 } else {
4415 ci = _decode_certificate(cert);
4416 }
4417 if (ci == NULL) {
4418 goto error;
4419 }
4420 if (PyList_Append(rlist, ci) == -1) {
4421 goto error;
4422 }
4423 Py_CLEAR(ci);
4424 }
4425 return rlist;
4426
4427 error:
4428 Py_XDECREF(ci);
4429 Py_XDECREF(rlist);
4430 return NULL;
4431}
4432
4433
Antoine Pitrou152efa22010-05-16 18:19:27 +00004434static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004435 {"check_hostname", (getter) get_check_hostname,
4436 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004437 {"_host_flags", (getter) get_host_flags,
4438 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004439#if SSL_CTRL_GET_MAX_PROTO_VERSION
4440 {"minimum_version", (getter) get_minimum_version,
4441 (setter) set_minimum_version, NULL},
4442 {"maximum_version", (getter) get_maximum_version,
4443 (setter) set_maximum_version, NULL},
4444#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004445 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004446 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004447 {"options", (getter) get_options,
4448 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004449 {"protocol", (getter) get_protocol,
4450 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004451 {"verify_flags", (getter) get_verify_flags,
4452 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004453 {"verify_mode", (getter) get_verify_mode,
4454 (setter) set_verify_mode, NULL},
4455 {NULL}, /* sentinel */
4456};
4457
4458static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004459 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4460 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4461 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4462 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4463 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4464 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4465 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4466 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4467 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4468 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4469 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004470 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4471 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004472 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004473 {NULL, NULL} /* sentinel */
4474};
4475
4476static PyTypeObject PySSLContext_Type = {
4477 PyVarObject_HEAD_INIT(NULL, 0)
4478 "_ssl._SSLContext", /*tp_name*/
4479 sizeof(PySSLContext), /*tp_basicsize*/
4480 0, /*tp_itemsize*/
4481 (destructor)context_dealloc, /*tp_dealloc*/
4482 0, /*tp_print*/
4483 0, /*tp_getattr*/
4484 0, /*tp_setattr*/
4485 0, /*tp_reserved*/
4486 0, /*tp_repr*/
4487 0, /*tp_as_number*/
4488 0, /*tp_as_sequence*/
4489 0, /*tp_as_mapping*/
4490 0, /*tp_hash*/
4491 0, /*tp_call*/
4492 0, /*tp_str*/
4493 0, /*tp_getattro*/
4494 0, /*tp_setattro*/
4495 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004496 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004497 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004498 (traverseproc) context_traverse, /*tp_traverse*/
4499 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004500 0, /*tp_richcompare*/
4501 0, /*tp_weaklistoffset*/
4502 0, /*tp_iter*/
4503 0, /*tp_iternext*/
4504 context_methods, /*tp_methods*/
4505 0, /*tp_members*/
4506 context_getsetlist, /*tp_getset*/
4507 0, /*tp_base*/
4508 0, /*tp_dict*/
4509 0, /*tp_descr_get*/
4510 0, /*tp_descr_set*/
4511 0, /*tp_dictoffset*/
4512 0, /*tp_init*/
4513 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004514 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004515};
4516
4517
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004518/*
4519 * MemoryBIO objects
4520 */
4521
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004522/*[clinic input]
4523@classmethod
4524_ssl.MemoryBIO.__new__
4525
4526[clinic start generated code]*/
4527
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004528static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004529_ssl_MemoryBIO_impl(PyTypeObject *type)
4530/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004531{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004532 BIO *bio;
4533 PySSLMemoryBIO *self;
4534
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004535 bio = BIO_new(BIO_s_mem());
4536 if (bio == NULL) {
4537 PyErr_SetString(PySSLErrorObject,
4538 "failed to allocate BIO");
4539 return NULL;
4540 }
4541 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4542 * just that no data is currently available. The SSL routines should retry
4543 * the read, which we can achieve by calling BIO_set_retry_read(). */
4544 BIO_set_retry_read(bio);
4545 BIO_set_mem_eof_return(bio, -1);
4546
4547 assert(type != NULL && type->tp_alloc != NULL);
4548 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4549 if (self == NULL) {
4550 BIO_free(bio);
4551 return NULL;
4552 }
4553 self->bio = bio;
4554 self->eof_written = 0;
4555
4556 return (PyObject *) self;
4557}
4558
4559static void
4560memory_bio_dealloc(PySSLMemoryBIO *self)
4561{
4562 BIO_free(self->bio);
4563 Py_TYPE(self)->tp_free(self);
4564}
4565
4566static PyObject *
4567memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4568{
Segev Finer5cff6372017-07-27 01:19:17 +03004569 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004570}
4571
4572PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4573"The number of bytes pending in the memory BIO.");
4574
4575static PyObject *
4576memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4577{
4578 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4579 && self->eof_written);
4580}
4581
4582PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4583"Whether the memory BIO is at EOF.");
4584
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004585/*[clinic input]
4586_ssl.MemoryBIO.read
4587 size as len: int = -1
4588 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004589
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004590Read up to size bytes from the memory BIO.
4591
4592If size is not specified, read the entire buffer.
4593If the return value is an empty bytes instance, this means either
4594EOF or that no data is available. Use the "eof" property to
4595distinguish between the two.
4596[clinic start generated code]*/
4597
4598static PyObject *
4599_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4600/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4601{
4602 int avail, nbytes;
4603 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004604
Segev Finer5cff6372017-07-27 01:19:17 +03004605 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004606 if ((len < 0) || (len > avail))
4607 len = avail;
4608
4609 result = PyBytes_FromStringAndSize(NULL, len);
4610 if ((result == NULL) || (len == 0))
4611 return result;
4612
4613 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4614 /* There should never be any short reads but check anyway. */
4615 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4616 Py_DECREF(result);
4617 return NULL;
4618 }
4619
4620 return result;
4621}
4622
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623/*[clinic input]
4624_ssl.MemoryBIO.write
4625 b: Py_buffer
4626 /
4627
4628Writes the bytes b into the memory BIO.
4629
4630Returns the number of bytes written.
4631[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004632
4633static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004634_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4635/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004636{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004637 int nbytes;
4638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004639 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004640 PyErr_Format(PyExc_OverflowError,
4641 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004642 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004643 }
4644
4645 if (self->eof_written) {
4646 PyErr_SetString(PySSLErrorObject,
4647 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004648 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004649 }
4650
Segev Finer5cff6372017-07-27 01:19:17 +03004651 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004652 if (nbytes < 0) {
4653 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004654 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004655 }
4656
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004657 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004658}
4659
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004660/*[clinic input]
4661_ssl.MemoryBIO.write_eof
4662
4663Write an EOF marker to the memory BIO.
4664
4665When all data has been read, the "eof" property will be True.
4666[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004667
4668static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004669_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4670/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004671{
4672 self->eof_written = 1;
4673 /* After an EOF is written, a zero return from read() should be a real EOF
4674 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4675 BIO_clear_retry_flags(self->bio);
4676 BIO_set_mem_eof_return(self->bio, 0);
4677
4678 Py_RETURN_NONE;
4679}
4680
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004681static PyGetSetDef memory_bio_getsetlist[] = {
4682 {"pending", (getter) memory_bio_get_pending, NULL,
4683 PySSL_memory_bio_pending_doc},
4684 {"eof", (getter) memory_bio_get_eof, NULL,
4685 PySSL_memory_bio_eof_doc},
4686 {NULL}, /* sentinel */
4687};
4688
4689static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004690 _SSL_MEMORYBIO_READ_METHODDEF
4691 _SSL_MEMORYBIO_WRITE_METHODDEF
4692 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004693 {NULL, NULL} /* sentinel */
4694};
4695
4696static PyTypeObject PySSLMemoryBIO_Type = {
4697 PyVarObject_HEAD_INIT(NULL, 0)
4698 "_ssl.MemoryBIO", /*tp_name*/
4699 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4700 0, /*tp_itemsize*/
4701 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4702 0, /*tp_print*/
4703 0, /*tp_getattr*/
4704 0, /*tp_setattr*/
4705 0, /*tp_reserved*/
4706 0, /*tp_repr*/
4707 0, /*tp_as_number*/
4708 0, /*tp_as_sequence*/
4709 0, /*tp_as_mapping*/
4710 0, /*tp_hash*/
4711 0, /*tp_call*/
4712 0, /*tp_str*/
4713 0, /*tp_getattro*/
4714 0, /*tp_setattro*/
4715 0, /*tp_as_buffer*/
4716 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4717 0, /*tp_doc*/
4718 0, /*tp_traverse*/
4719 0, /*tp_clear*/
4720 0, /*tp_richcompare*/
4721 0, /*tp_weaklistoffset*/
4722 0, /*tp_iter*/
4723 0, /*tp_iternext*/
4724 memory_bio_methods, /*tp_methods*/
4725 0, /*tp_members*/
4726 memory_bio_getsetlist, /*tp_getset*/
4727 0, /*tp_base*/
4728 0, /*tp_dict*/
4729 0, /*tp_descr_get*/
4730 0, /*tp_descr_set*/
4731 0, /*tp_dictoffset*/
4732 0, /*tp_init*/
4733 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004734 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004735};
4736
Antoine Pitrou152efa22010-05-16 18:19:27 +00004737
Christian Heimes99a65702016-09-10 23:44:53 +02004738/*
4739 * SSL Session object
4740 */
4741
4742static void
4743PySSLSession_dealloc(PySSLSession *self)
4744{
INADA Naokia6296d32017-08-24 14:55:17 +09004745 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004746 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004747 Py_XDECREF(self->ctx);
4748 if (self->session != NULL) {
4749 SSL_SESSION_free(self->session);
4750 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004751 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004752}
4753
4754static PyObject *
4755PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4756{
4757 int result;
4758
4759 if (left == NULL || right == NULL) {
4760 PyErr_BadInternalCall();
4761 return NULL;
4762 }
4763
4764 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4765 Py_RETURN_NOTIMPLEMENTED;
4766 }
4767
4768 if (left == right) {
4769 result = 0;
4770 } else {
4771 const unsigned char *left_id, *right_id;
4772 unsigned int left_len, right_len;
4773 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4774 &left_len);
4775 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4776 &right_len);
4777 if (left_len == right_len) {
4778 result = memcmp(left_id, right_id, left_len);
4779 } else {
4780 result = 1;
4781 }
4782 }
4783
4784 switch (op) {
4785 case Py_EQ:
4786 if (result == 0) {
4787 Py_RETURN_TRUE;
4788 } else {
4789 Py_RETURN_FALSE;
4790 }
4791 break;
4792 case Py_NE:
4793 if (result != 0) {
4794 Py_RETURN_TRUE;
4795 } else {
4796 Py_RETURN_FALSE;
4797 }
4798 break;
4799 case Py_LT:
4800 case Py_LE:
4801 case Py_GT:
4802 case Py_GE:
4803 Py_RETURN_NOTIMPLEMENTED;
4804 break;
4805 default:
4806 PyErr_BadArgument();
4807 return NULL;
4808 }
4809}
4810
4811static int
4812PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4813{
4814 Py_VISIT(self->ctx);
4815 return 0;
4816}
4817
4818static int
4819PySSLSession_clear(PySSLSession *self)
4820{
4821 Py_CLEAR(self->ctx);
4822 return 0;
4823}
4824
4825
4826static PyObject *
4827PySSLSession_get_time(PySSLSession *self, void *closure) {
4828 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4829}
4830
4831PyDoc_STRVAR(PySSLSession_get_time_doc,
4832"Session creation time (seconds since epoch).");
4833
4834
4835static PyObject *
4836PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4837 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4838}
4839
4840PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4841"Session timeout (delta in seconds).");
4842
4843
4844static PyObject *
4845PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4846 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4847 return PyLong_FromUnsignedLong(hint);
4848}
4849
4850PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4851"Ticket life time hint.");
4852
4853
4854static PyObject *
4855PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4856 const unsigned char *id;
4857 unsigned int len;
4858 id = SSL_SESSION_get_id(self->session, &len);
4859 return PyBytes_FromStringAndSize((const char *)id, len);
4860}
4861
4862PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4863"Session id");
4864
4865
4866static PyObject *
4867PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4868 if (SSL_SESSION_has_ticket(self->session)) {
4869 Py_RETURN_TRUE;
4870 } else {
4871 Py_RETURN_FALSE;
4872 }
4873}
4874
4875PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4876"Does the session contain a ticket?");
4877
4878
4879static PyGetSetDef PySSLSession_getsetlist[] = {
4880 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4881 PySSLSession_get_has_ticket_doc},
4882 {"id", (getter) PySSLSession_get_session_id, NULL,
4883 PySSLSession_get_session_id_doc},
4884 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4885 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4886 {"time", (getter) PySSLSession_get_time, NULL,
4887 PySSLSession_get_time_doc},
4888 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4889 PySSLSession_get_timeout_doc},
4890 {NULL}, /* sentinel */
4891};
4892
4893static PyTypeObject PySSLSession_Type = {
4894 PyVarObject_HEAD_INIT(NULL, 0)
4895 "_ssl.Session", /*tp_name*/
4896 sizeof(PySSLSession), /*tp_basicsize*/
4897 0, /*tp_itemsize*/
4898 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4899 0, /*tp_print*/
4900 0, /*tp_getattr*/
4901 0, /*tp_setattr*/
4902 0, /*tp_reserved*/
4903 0, /*tp_repr*/
4904 0, /*tp_as_number*/
4905 0, /*tp_as_sequence*/
4906 0, /*tp_as_mapping*/
4907 0, /*tp_hash*/
4908 0, /*tp_call*/
4909 0, /*tp_str*/
4910 0, /*tp_getattro*/
4911 0, /*tp_setattro*/
4912 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004913 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004914 0, /*tp_doc*/
4915 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4916 (inquiry)PySSLSession_clear, /*tp_clear*/
4917 PySSLSession_richcompare, /*tp_richcompare*/
4918 0, /*tp_weaklistoffset*/
4919 0, /*tp_iter*/
4920 0, /*tp_iternext*/
4921 0, /*tp_methods*/
4922 0, /*tp_members*/
4923 PySSLSession_getsetlist, /*tp_getset*/
4924};
4925
4926
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004927/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004928/*[clinic input]
4929_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004930 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004931 entropy: double
4932 /
4933
4934Mix string into the OpenSSL PRNG state.
4935
4936entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304937string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004938[clinic start generated code]*/
4939
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004940static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004941_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004942/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004943{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004944 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004945 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004946
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004947 buf = (const char *)view->buf;
4948 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004949 do {
4950 written = Py_MIN(len, INT_MAX);
4951 RAND_add(buf, (int)written, entropy);
4952 buf += written;
4953 len -= written;
4954 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004955 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004956}
4957
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004958static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004959PySSL_RAND(int len, int pseudo)
4960{
4961 int ok;
4962 PyObject *bytes;
4963 unsigned long err;
4964 const char *errstr;
4965 PyObject *v;
4966
Victor Stinner1e81a392013-12-19 16:47:04 +01004967 if (len < 0) {
4968 PyErr_SetString(PyExc_ValueError, "num must be positive");
4969 return NULL;
4970 }
4971
Victor Stinner99c8b162011-05-24 12:05:19 +02004972 bytes = PyBytes_FromStringAndSize(NULL, len);
4973 if (bytes == NULL)
4974 return NULL;
4975 if (pseudo) {
4976 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4977 if (ok == 0 || ok == 1)
4978 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4979 }
4980 else {
4981 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4982 if (ok == 1)
4983 return bytes;
4984 }
4985 Py_DECREF(bytes);
4986
4987 err = ERR_get_error();
4988 errstr = ERR_reason_error_string(err);
4989 v = Py_BuildValue("(ks)", err, errstr);
4990 if (v != NULL) {
4991 PyErr_SetObject(PySSLErrorObject, v);
4992 Py_DECREF(v);
4993 }
4994 return NULL;
4995}
4996
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004997/*[clinic input]
4998_ssl.RAND_bytes
4999 n: int
5000 /
5001
5002Generate n cryptographically strong pseudo-random bytes.
5003[clinic start generated code]*/
5004
Victor Stinner99c8b162011-05-24 12:05:19 +02005005static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005006_ssl_RAND_bytes_impl(PyObject *module, int n)
5007/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005008{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005009 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005010}
5011
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005012/*[clinic input]
5013_ssl.RAND_pseudo_bytes
5014 n: int
5015 /
5016
5017Generate n pseudo-random bytes.
5018
5019Return a pair (bytes, is_cryptographic). is_cryptographic is True
5020if the bytes generated are cryptographically strong.
5021[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005022
5023static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005024_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5025/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005026{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005027 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005028}
5029
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005030/*[clinic input]
5031_ssl.RAND_status
5032
5033Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5034
5035It is necessary to seed the PRNG with RAND_add() on some platforms before
5036using the ssl() function.
5037[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005038
5039static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005040_ssl_RAND_status_impl(PyObject *module)
5041/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005042{
Christian Heimes217cfd12007-12-02 14:31:20 +00005043 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005044}
5045
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005046#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005047/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005048/*[clinic input]
5049_ssl.RAND_egd
5050 path: object(converter="PyUnicode_FSConverter")
5051 /
5052
5053Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5054
5055Returns number of bytes read. Raises SSLError if connection to EGD
5056fails or if it does not provide enough data to seed PRNG.
5057[clinic start generated code]*/
5058
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005059static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005060_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5061/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005062{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005063 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005064 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005065 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005066 PyErr_SetString(PySSLErrorObject,
5067 "EGD connection failed or EGD did not return "
5068 "enough data to seed the PRNG");
5069 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005070 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005071 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005072}
Christian Heimesa5d07652016-09-24 10:48:05 +02005073/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005074#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005075
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005076
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005077
5078/*[clinic input]
5079_ssl.get_default_verify_paths
5080
5081Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5082
5083The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5084[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005085
5086static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005087_ssl_get_default_verify_paths_impl(PyObject *module)
5088/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005089{
5090 PyObject *ofile_env = NULL;
5091 PyObject *ofile = NULL;
5092 PyObject *odir_env = NULL;
5093 PyObject *odir = NULL;
5094
Benjamin Petersond113c962015-07-18 10:59:13 -07005095#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005096 const char *tmp = (info); \
5097 target = NULL; \
5098 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5099 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5100 target = PyBytes_FromString(tmp); } \
5101 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005102 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005103
Benjamin Petersond113c962015-07-18 10:59:13 -07005104 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5105 CONVERT(X509_get_default_cert_file(), ofile);
5106 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5107 CONVERT(X509_get_default_cert_dir(), odir);
5108#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005109
Christian Heimes200bb1b2013-06-14 15:14:29 +02005110 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005111
5112 error:
5113 Py_XDECREF(ofile_env);
5114 Py_XDECREF(ofile);
5115 Py_XDECREF(odir_env);
5116 Py_XDECREF(odir);
5117 return NULL;
5118}
5119
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005120static PyObject*
5121asn1obj2py(ASN1_OBJECT *obj)
5122{
5123 int nid;
5124 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005125
5126 nid = OBJ_obj2nid(obj);
5127 if (nid == NID_undef) {
5128 PyErr_Format(PyExc_ValueError, "Unknown object");
5129 return NULL;
5130 }
5131 sn = OBJ_nid2sn(nid);
5132 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005133 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005134}
5135
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005136/*[clinic input]
5137_ssl.txt2obj
5138 txt: str
5139 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005140
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005141Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5142
5143By default objects are looked up by OID. With name=True short and
5144long name are also matched.
5145[clinic start generated code]*/
5146
5147static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005148_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5149/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005150{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005151 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005152 ASN1_OBJECT *obj;
5153
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005154 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5155 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005156 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005157 return NULL;
5158 }
5159 result = asn1obj2py(obj);
5160 ASN1_OBJECT_free(obj);
5161 return result;
5162}
5163
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005164/*[clinic input]
5165_ssl.nid2obj
5166 nid: int
5167 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005168
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005169Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5170[clinic start generated code]*/
5171
5172static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005173_ssl_nid2obj_impl(PyObject *module, int nid)
5174/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005175{
5176 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005177 ASN1_OBJECT *obj;
5178
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005179 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005180 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005181 return NULL;
5182 }
5183 obj = OBJ_nid2obj(nid);
5184 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005185 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005186 return NULL;
5187 }
5188 result = asn1obj2py(obj);
5189 ASN1_OBJECT_free(obj);
5190 return result;
5191}
5192
Christian Heimes46bebee2013-06-09 19:03:31 +02005193#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005194
5195static PyObject*
5196certEncodingType(DWORD encodingType)
5197{
5198 static PyObject *x509_asn = NULL;
5199 static PyObject *pkcs_7_asn = NULL;
5200
5201 if (x509_asn == NULL) {
5202 x509_asn = PyUnicode_InternFromString("x509_asn");
5203 if (x509_asn == NULL)
5204 return NULL;
5205 }
5206 if (pkcs_7_asn == NULL) {
5207 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5208 if (pkcs_7_asn == NULL)
5209 return NULL;
5210 }
5211 switch(encodingType) {
5212 case X509_ASN_ENCODING:
5213 Py_INCREF(x509_asn);
5214 return x509_asn;
5215 case PKCS_7_ASN_ENCODING:
5216 Py_INCREF(pkcs_7_asn);
5217 return pkcs_7_asn;
5218 default:
5219 return PyLong_FromLong(encodingType);
5220 }
5221}
5222
5223static PyObject*
5224parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5225{
5226 CERT_ENHKEY_USAGE *usage;
5227 DWORD size, error, i;
5228 PyObject *retval;
5229
5230 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5231 error = GetLastError();
5232 if (error == CRYPT_E_NOT_FOUND) {
5233 Py_RETURN_TRUE;
5234 }
5235 return PyErr_SetFromWindowsErr(error);
5236 }
5237
5238 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5239 if (usage == NULL) {
5240 return PyErr_NoMemory();
5241 }
5242
5243 /* Now get the actual enhanced usage property */
5244 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5245 PyMem_Free(usage);
5246 error = GetLastError();
5247 if (error == CRYPT_E_NOT_FOUND) {
5248 Py_RETURN_TRUE;
5249 }
5250 return PyErr_SetFromWindowsErr(error);
5251 }
5252 retval = PySet_New(NULL);
5253 if (retval == NULL) {
5254 goto error;
5255 }
5256 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5257 if (usage->rgpszUsageIdentifier[i]) {
5258 PyObject *oid;
5259 int err;
5260 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5261 if (oid == NULL) {
5262 Py_CLEAR(retval);
5263 goto error;
5264 }
5265 err = PySet_Add(retval, oid);
5266 Py_DECREF(oid);
5267 if (err == -1) {
5268 Py_CLEAR(retval);
5269 goto error;
5270 }
5271 }
5272 }
5273 error:
5274 PyMem_Free(usage);
5275 return retval;
5276}
5277
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005278/*[clinic input]
5279_ssl.enum_certificates
5280 store_name: str
5281
5282Retrieve certificates from Windows' cert store.
5283
5284store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5285more cert storages, too. The function returns a list of (bytes,
5286encoding_type, trust) tuples. The encoding_type flag can be interpreted
5287with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5288a set of OIDs or the boolean True.
5289[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005290
Christian Heimes46bebee2013-06-09 19:03:31 +02005291static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005292_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5293/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005294{
Christian Heimes46bebee2013-06-09 19:03:31 +02005295 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005296 PCCERT_CONTEXT pCertCtx = NULL;
5297 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005298 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005299
Christian Heimes44109d72013-11-22 01:51:30 +01005300 result = PyList_New(0);
5301 if (result == NULL) {
5302 return NULL;
5303 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005304 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5305 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5306 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005307 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005308 Py_DECREF(result);
5309 return PyErr_SetFromWindowsErr(GetLastError());
5310 }
5311
Christian Heimes44109d72013-11-22 01:51:30 +01005312 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5313 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5314 pCertCtx->cbCertEncoded);
5315 if (!cert) {
5316 Py_CLEAR(result);
5317 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005318 }
Christian Heimes44109d72013-11-22 01:51:30 +01005319 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5320 Py_CLEAR(result);
5321 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005322 }
Christian Heimes44109d72013-11-22 01:51:30 +01005323 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5324 if (keyusage == Py_True) {
5325 Py_DECREF(keyusage);
5326 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005327 }
Christian Heimes44109d72013-11-22 01:51:30 +01005328 if (keyusage == NULL) {
5329 Py_CLEAR(result);
5330 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005331 }
Christian Heimes44109d72013-11-22 01:51:30 +01005332 if ((tup = PyTuple_New(3)) == NULL) {
5333 Py_CLEAR(result);
5334 break;
5335 }
5336 PyTuple_SET_ITEM(tup, 0, cert);
5337 cert = NULL;
5338 PyTuple_SET_ITEM(tup, 1, enc);
5339 enc = NULL;
5340 PyTuple_SET_ITEM(tup, 2, keyusage);
5341 keyusage = NULL;
5342 if (PyList_Append(result, tup) < 0) {
5343 Py_CLEAR(result);
5344 break;
5345 }
5346 Py_CLEAR(tup);
5347 }
5348 if (pCertCtx) {
5349 /* loop ended with an error, need to clean up context manually */
5350 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005351 }
5352
5353 /* In error cases cert, enc and tup may not be NULL */
5354 Py_XDECREF(cert);
5355 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005356 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005357 Py_XDECREF(tup);
5358
5359 if (!CertCloseStore(hStore, 0)) {
5360 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005361 Py_XDECREF(result);
5362 return PyErr_SetFromWindowsErr(GetLastError());
5363 }
5364 return result;
5365}
5366
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005367/*[clinic input]
5368_ssl.enum_crls
5369 store_name: str
5370
5371Retrieve CRLs from Windows' cert store.
5372
5373store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5374more cert storages, too. The function returns a list of (bytes,
5375encoding_type) tuples. The encoding_type flag can be interpreted with
5376X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5377[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005378
5379static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005380_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5381/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005382{
Christian Heimes44109d72013-11-22 01:51:30 +01005383 HCERTSTORE hStore = NULL;
5384 PCCRL_CONTEXT pCrlCtx = NULL;
5385 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5386 PyObject *result = NULL;
5387
Christian Heimes44109d72013-11-22 01:51:30 +01005388 result = PyList_New(0);
5389 if (result == NULL) {
5390 return NULL;
5391 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005392 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5393 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5394 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005395 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005396 Py_DECREF(result);
5397 return PyErr_SetFromWindowsErr(GetLastError());
5398 }
Christian Heimes44109d72013-11-22 01:51:30 +01005399
5400 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5401 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5402 pCrlCtx->cbCrlEncoded);
5403 if (!crl) {
5404 Py_CLEAR(result);
5405 break;
5406 }
5407 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5408 Py_CLEAR(result);
5409 break;
5410 }
5411 if ((tup = PyTuple_New(2)) == NULL) {
5412 Py_CLEAR(result);
5413 break;
5414 }
5415 PyTuple_SET_ITEM(tup, 0, crl);
5416 crl = NULL;
5417 PyTuple_SET_ITEM(tup, 1, enc);
5418 enc = NULL;
5419
5420 if (PyList_Append(result, tup) < 0) {
5421 Py_CLEAR(result);
5422 break;
5423 }
5424 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005425 }
Christian Heimes44109d72013-11-22 01:51:30 +01005426 if (pCrlCtx) {
5427 /* loop ended with an error, need to clean up context manually */
5428 CertFreeCRLContext(pCrlCtx);
5429 }
5430
5431 /* In error cases cert, enc and tup may not be NULL */
5432 Py_XDECREF(crl);
5433 Py_XDECREF(enc);
5434 Py_XDECREF(tup);
5435
5436 if (!CertCloseStore(hStore, 0)) {
5437 /* This error case might shadow another exception.*/
5438 Py_XDECREF(result);
5439 return PyErr_SetFromWindowsErr(GetLastError());
5440 }
5441 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005442}
Christian Heimes44109d72013-11-22 01:51:30 +01005443
5444#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005445
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005446/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005447static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005448 _SSL__TEST_DECODE_CERT_METHODDEF
5449 _SSL_RAND_ADD_METHODDEF
5450 _SSL_RAND_BYTES_METHODDEF
5451 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5452 _SSL_RAND_EGD_METHODDEF
5453 _SSL_RAND_STATUS_METHODDEF
5454 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5455 _SSL_ENUM_CERTIFICATES_METHODDEF
5456 _SSL_ENUM_CRLS_METHODDEF
5457 _SSL_TXT2OBJ_METHODDEF
5458 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005459 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005460};
5461
5462
Christian Heimes598894f2016-09-05 23:19:05 +02005463#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005464
5465/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005466 * of the Python C thread library
5467 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5468 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005469
5470static PyThread_type_lock *_ssl_locks = NULL;
5471
Christian Heimes4d98ca92013-08-19 17:36:29 +02005472#if OPENSSL_VERSION_NUMBER >= 0x10000000
5473/* use new CRYPTO_THREADID API. */
5474static void
5475_ssl_threadid_callback(CRYPTO_THREADID *id)
5476{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005477 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005478}
5479#else
5480/* deprecated CRYPTO_set_id_callback() API. */
5481static unsigned long
5482_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005483 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005484}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005485#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005486
Bill Janssen6e027db2007-11-15 22:23:56 +00005487static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005488 (int mode, int n, const char *file, int line) {
5489 /* this function is needed to perform locking on shared data
5490 structures. (Note that OpenSSL uses a number of global data
5491 structures that will be implicitly shared whenever multiple
5492 threads use OpenSSL.) Multi-threaded applications will
5493 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005494
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005495 locking_function() must be able to handle up to
5496 CRYPTO_num_locks() different mutex locks. It sets the n-th
5497 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005498
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005499 file and line are the file number of the function setting the
5500 lock. They can be useful for debugging.
5501 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005503 if ((_ssl_locks == NULL) ||
5504 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5505 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005506
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005507 if (mode & CRYPTO_LOCK) {
5508 PyThread_acquire_lock(_ssl_locks[n], 1);
5509 } else {
5510 PyThread_release_lock(_ssl_locks[n]);
5511 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005512}
5513
5514static int _setup_ssl_threads(void) {
5515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005516 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005518 if (_ssl_locks == NULL) {
5519 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005520 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5521 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005522 if (_ssl_locks == NULL) {
5523 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005524 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005525 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005526 for (i = 0; i < _ssl_locks_count; i++) {
5527 _ssl_locks[i] = PyThread_allocate_lock();
5528 if (_ssl_locks[i] == NULL) {
5529 unsigned int j;
5530 for (j = 0; j < i; j++) {
5531 PyThread_free_lock(_ssl_locks[j]);
5532 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005533 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005534 return 0;
5535 }
5536 }
5537 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005538#if OPENSSL_VERSION_NUMBER >= 0x10000000
5539 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5540#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005541 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005542#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005543 }
5544 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005545}
5546
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005547#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005548
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005549PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005550"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005551for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005552
Martin v. Löwis1a214512008-06-11 05:26:20 +00005553
5554static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005555 PyModuleDef_HEAD_INIT,
5556 "_ssl",
5557 module_doc,
5558 -1,
5559 PySSL_methods,
5560 NULL,
5561 NULL,
5562 NULL,
5563 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005564};
5565
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005566
5567static void
5568parse_openssl_version(unsigned long libver,
5569 unsigned int *major, unsigned int *minor,
5570 unsigned int *fix, unsigned int *patch,
5571 unsigned int *status)
5572{
5573 *status = libver & 0xF;
5574 libver >>= 4;
5575 *patch = libver & 0xFF;
5576 libver >>= 8;
5577 *fix = libver & 0xFF;
5578 libver >>= 8;
5579 *minor = libver & 0xFF;
5580 libver >>= 8;
5581 *major = libver & 0xFF;
5582}
5583
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005584PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005585PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005586{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005587 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005588 unsigned long libver;
5589 unsigned int major, minor, fix, patch, status;
5590 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005591 struct py_ssl_error_code *errcode;
5592 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005593
Antoine Pitrou152efa22010-05-16 18:19:27 +00005594 if (PyType_Ready(&PySSLContext_Type) < 0)
5595 return NULL;
5596 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005597 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005598 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5599 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005600 if (PyType_Ready(&PySSLSession_Type) < 0)
5601 return NULL;
5602
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005603
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005604 m = PyModule_Create(&_sslmodule);
5605 if (m == NULL)
5606 return NULL;
5607 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005608
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005609 /* Load _socket module and its C API */
5610 socket_api = PySocketModule_ImportModuleAndAPI();
5611 if (!socket_api)
5612 return NULL;
5613 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005614
Christian Heimesc941e622017-09-05 15:47:11 +02005615#ifndef OPENSSL_VERSION_1_1
5616 /* Load all algorithms and initialize cpuid */
5617 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005618 /* Init OpenSSL */
5619 SSL_load_error_strings();
5620 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005621#endif
5622
Christian Heimes598894f2016-09-05 23:19:05 +02005623#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005624 /* note that this will start threading if not already started */
5625 if (!_setup_ssl_threads()) {
5626 return NULL;
5627 }
Christian Heimes598894f2016-09-05 23:19:05 +02005628#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5629 /* OpenSSL 1.1.0 builtin thread support is enabled */
5630 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005631#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005633 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005634 sslerror_type_slots[0].pfunc = PyExc_OSError;
5635 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005636 if (PySSLErrorObject == NULL)
5637 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005638
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005639 /* ssl.CertificateError used to be a subclass of ValueError */
5640 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5641 if (bases == NULL)
5642 return NULL;
5643 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5644 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5645 bases, NULL);
5646 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005647 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5648 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5649 PySSLErrorObject, NULL);
5650 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5651 "ssl.SSLWantReadError", SSLWantReadError_doc,
5652 PySSLErrorObject, NULL);
5653 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5654 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5655 PySSLErrorObject, NULL);
5656 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5657 "ssl.SSLSyscallError", SSLSyscallError_doc,
5658 PySSLErrorObject, NULL);
5659 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5660 "ssl.SSLEOFError", SSLEOFError_doc,
5661 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005662 if (PySSLCertVerificationErrorObject == NULL
5663 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005664 || PySSLWantReadErrorObject == NULL
5665 || PySSLWantWriteErrorObject == NULL
5666 || PySSLSyscallErrorObject == NULL
5667 || PySSLEOFErrorObject == NULL)
5668 return NULL;
5669 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005670 || PyDict_SetItemString(d, "SSLCertVerificationError",
5671 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005672 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5673 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5674 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5675 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5676 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005677 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005678 if (PyDict_SetItemString(d, "_SSLContext",
5679 (PyObject *)&PySSLContext_Type) != 0)
5680 return NULL;
5681 if (PyDict_SetItemString(d, "_SSLSocket",
5682 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005683 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005684 if (PyDict_SetItemString(d, "MemoryBIO",
5685 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5686 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005687 if (PyDict_SetItemString(d, "SSLSession",
5688 (PyObject *)&PySSLSession_Type) != 0)
5689 return NULL;
5690
Christian Heimes892d66e2018-01-29 14:10:18 +01005691 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5692 PY_SSL_DEFAULT_CIPHER_STRING);
5693
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005694 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5695 PY_SSL_ERROR_ZERO_RETURN);
5696 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5697 PY_SSL_ERROR_WANT_READ);
5698 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5699 PY_SSL_ERROR_WANT_WRITE);
5700 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5701 PY_SSL_ERROR_WANT_X509_LOOKUP);
5702 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5703 PY_SSL_ERROR_SYSCALL);
5704 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5705 PY_SSL_ERROR_SSL);
5706 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5707 PY_SSL_ERROR_WANT_CONNECT);
5708 /* non ssl.h errorcodes */
5709 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5710 PY_SSL_ERROR_EOF);
5711 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5712 PY_SSL_ERROR_INVALID_ERROR_CODE);
5713 /* cert requirements */
5714 PyModule_AddIntConstant(m, "CERT_NONE",
5715 PY_SSL_CERT_NONE);
5716 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5717 PY_SSL_CERT_OPTIONAL);
5718 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5719 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005720 /* CRL verification for verification_flags */
5721 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5722 0);
5723 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5724 X509_V_FLAG_CRL_CHECK);
5725 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5726 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5727 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5728 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005729#ifdef X509_V_FLAG_TRUSTED_FIRST
5730 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5731 X509_V_FLAG_TRUSTED_FIRST);
5732#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005733
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005734 /* Alert Descriptions from ssl.h */
5735 /* note RESERVED constants no longer intended for use have been removed */
5736 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5737
5738#define ADD_AD_CONSTANT(s) \
5739 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5740 SSL_AD_##s)
5741
5742 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5743 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5744 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5745 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5746 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5747 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5748 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5749 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5750 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5751 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5752 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5753 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5754 ADD_AD_CONSTANT(UNKNOWN_CA);
5755 ADD_AD_CONSTANT(ACCESS_DENIED);
5756 ADD_AD_CONSTANT(DECODE_ERROR);
5757 ADD_AD_CONSTANT(DECRYPT_ERROR);
5758 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5759 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5760 ADD_AD_CONSTANT(INTERNAL_ERROR);
5761 ADD_AD_CONSTANT(USER_CANCELLED);
5762 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005763 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005764#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5765 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5766#endif
5767#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5768 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5769#endif
5770#ifdef SSL_AD_UNRECOGNIZED_NAME
5771 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5772#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005773#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5774 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5775#endif
5776#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5777 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5778#endif
5779#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5780 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5781#endif
5782
5783#undef ADD_AD_CONSTANT
5784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005785 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005786#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005787 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5788 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005789#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005790#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005791 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5792 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005793#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005794 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005795 PY_SSL_VERSION_TLS);
5796 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5797 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005798 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5799 PY_SSL_VERSION_TLS_CLIENT);
5800 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5801 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005802 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5803 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005804#if HAVE_TLSv1_2
5805 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5806 PY_SSL_VERSION_TLS1_1);
5807 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5808 PY_SSL_VERSION_TLS1_2);
5809#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005810
Antoine Pitroub5218772010-05-21 09:56:06 +00005811 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005812 PyModule_AddIntConstant(m, "OP_ALL",
5813 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005814 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5815 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5816 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005817#if HAVE_TLSv1_2
5818 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5819 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5820#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005821#ifdef SSL_OP_NO_TLSv1_3
5822 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5823#else
5824 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5825#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005826 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5827 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005828 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005829 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005830#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005831 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005832#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005833#ifdef SSL_OP_NO_COMPRESSION
5834 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5835 SSL_OP_NO_COMPRESSION);
5836#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005837#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5838 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5839 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5840#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005841
Christian Heimes61d478c2018-01-27 15:51:38 +01005842#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5843 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5844 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5845#endif
5846#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5847 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5848 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5849#endif
5850#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5851 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5852 X509_CHECK_FLAG_NO_WILDCARDS);
5853#endif
5854#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5855 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5856 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5857#endif
5858#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5859 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5860 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5861#endif
5862#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5863 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5864 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5865#endif
5866
Christian Heimes698dde12018-02-27 11:54:43 +01005867 /* protocol versions */
5868 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5869 PY_PROTO_MINIMUM_SUPPORTED);
5870 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5871 PY_PROTO_MAXIMUM_SUPPORTED);
5872 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5873 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5874 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5875 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5876 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005877
Christian Heimes698dde12018-02-27 11:54:43 +01005878#define addbool(m, v, b) \
5879 Py_INCREF((b) ? Py_True : Py_False); \
5880 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5881
5882#if HAVE_SNI
5883 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005884#else
Christian Heimes698dde12018-02-27 11:54:43 +01005885 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005886#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005887
5888 addbool(m, "HAS_TLS_UNIQUE", 1);
5889
5890#ifndef OPENSSL_NO_ECDH
5891 addbool(m, "HAS_ECDH", 1);
5892#else
5893 addbool(m, "HAS_ECDH", 0);
5894#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005895
Christian Heimes29eab552018-02-25 12:31:33 +01005896#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005897 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005898#else
Christian Heimes698dde12018-02-27 11:54:43 +01005899 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005900#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005901
Christian Heimes29eab552018-02-25 12:31:33 +01005902#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005903 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005904#else
Christian Heimes698dde12018-02-27 11:54:43 +01005905 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005906#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005907
5908#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5909 addbool(m, "HAS_SSLv2", 1);
5910#else
5911 addbool(m, "HAS_SSLv2", 0);
5912#endif
5913
5914#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5915 addbool(m, "HAS_SSLv3", 1);
5916#else
5917 addbool(m, "HAS_SSLv3", 0);
5918#endif
5919
5920#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5921 addbool(m, "HAS_TLSv1", 1);
5922#else
5923 addbool(m, "HAS_TLSv1", 0);
5924#endif
5925
5926#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5927 addbool(m, "HAS_TLSv1_1", 1);
5928#else
5929 addbool(m, "HAS_TLSv1_1", 0);
5930#endif
5931
5932#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5933 addbool(m, "HAS_TLSv1_2", 1);
5934#else
5935 addbool(m, "HAS_TLSv1_2", 0);
5936#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005937
Christian Heimescb5b68a2017-09-07 18:07:00 -07005938#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005939 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005940#else
Christian Heimes698dde12018-02-27 11:54:43 +01005941 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005942#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005943
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005944 /* Mappings for error codes */
5945 err_codes_to_names = PyDict_New();
5946 err_names_to_codes = PyDict_New();
5947 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5948 return NULL;
5949 errcode = error_codes;
5950 while (errcode->mnemonic != NULL) {
5951 PyObject *mnemo, *key;
5952 mnemo = PyUnicode_FromString(errcode->mnemonic);
5953 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5954 if (mnemo == NULL || key == NULL)
5955 return NULL;
5956 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5957 return NULL;
5958 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5959 return NULL;
5960 Py_DECREF(key);
5961 Py_DECREF(mnemo);
5962 errcode++;
5963 }
5964 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5965 return NULL;
5966 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5967 return NULL;
5968
5969 lib_codes_to_names = PyDict_New();
5970 if (lib_codes_to_names == NULL)
5971 return NULL;
5972 libcode = library_codes;
5973 while (libcode->library != NULL) {
5974 PyObject *mnemo, *key;
5975 key = PyLong_FromLong(libcode->code);
5976 mnemo = PyUnicode_FromString(libcode->library);
5977 if (key == NULL || mnemo == NULL)
5978 return NULL;
5979 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5980 return NULL;
5981 Py_DECREF(key);
5982 Py_DECREF(mnemo);
5983 libcode++;
5984 }
5985 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5986 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005988 /* OpenSSL version */
5989 /* SSLeay() gives us the version of the library linked against,
5990 which could be different from the headers version.
5991 */
5992 libver = SSLeay();
5993 r = PyLong_FromUnsignedLong(libver);
5994 if (r == NULL)
5995 return NULL;
5996 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5997 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005998 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005999 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6000 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6001 return NULL;
6002 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6003 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6004 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006005
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006006 libver = OPENSSL_VERSION_NUMBER;
6007 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6008 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6009 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6010 return NULL;
6011
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006012 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006013}