blob: 650f030345f7a6b0ad65cb8b0ad4395ce87deffb [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066
Christian Heimesff5be6e2018-01-20 13:19:21 +010067#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010068# ifdef LIBRESSL_VERSION_NUMBER
69# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
70# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010071# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010072# else
73# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010074# endif
75#endif
76
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077/* SSL error object */
78static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070079static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080static PyObject *PySSLZeroReturnErrorObject;
81static PyObject *PySSLWantReadErrorObject;
82static PyObject *PySSLWantWriteErrorObject;
83static PyObject *PySSLSyscallErrorObject;
84static PyObject *PySSLEOFErrorObject;
85
86/* Error mappings */
87static PyObject *err_codes_to_names;
88static PyObject *err_names_to_codes;
89static PyObject *lib_codes_to_names;
90
91struct py_ssl_error_code {
92 const char *mnemonic;
93 int library, reason;
94};
95struct py_ssl_library_code {
96 const char *library;
97 int code;
98};
99
Steve Dower68d663c2017-07-17 11:15:48 +0200100#if defined(MS_WINDOWS) && defined(Py_DEBUG)
101/* Debug builds on Windows rely on getting errno directly from OpenSSL.
102 * However, because it uses a different CRT, we need to transfer the
103 * value of errno from OpenSSL into our debug CRT.
104 *
105 * Don't be fooled - this is horribly ugly code. The only reasonable
106 * alternative is to do both debug and release builds of OpenSSL, which
107 * requires much uglier code to transform their automatically generated
108 * makefile. This is the lesser of all the evils.
109 */
110
111static void _PySSLFixErrno(void) {
112 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
113 if (!ucrtbase) {
114 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
115 * have a catastrophic failure, but this function is not the
116 * place to raise it. */
117 return;
118 }
119
120 typedef int *(__stdcall *errno_func)(void);
121 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
122 if (ssl_errno) {
123 errno = *ssl_errno();
124 *ssl_errno() = 0;
125 } else {
126 errno = ENOTRECOVERABLE;
127 }
128}
129
130#undef _PySSL_FIX_ERRNO
131#define _PySSL_FIX_ERRNO _PySSLFixErrno()
132#endif
133
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100134/* Include generated data (error codes) */
135#include "_ssl_data.h"
136
Christian Heimes598894f2016-09-05 23:19:05 +0200137#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
138# define OPENSSL_VERSION_1_1 1
Christian Heimes4ca07392018-03-24 15:41:37 +0100139# define PY_OPENSSL_1_1_API 1
140#endif
141
142/* LibreSSL 2.7.0 provides necessary OpenSSL 1.1.0 APIs */
143#if defined(LIBRESSL_VERSION_NUMBER) && LIBRESSL_VERSION_NUMBER >= 0x2070000fL
144# define PY_OPENSSL_1_1_API 1
Christian Heimes598894f2016-09-05 23:19:05 +0200145#endif
146
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100147/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
148 http://www.openssl.org/news/changelog.html
149 */
150#if OPENSSL_VERSION_NUMBER >= 0x10001000L
151# define HAVE_TLSv1_2 1
152#else
153# define HAVE_TLSv1_2 0
154#endif
155
Christian Heimes470fba12013-11-28 15:12:15 +0100156/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100157 * This includes the SSL_set_SSL_CTX() function.
158 */
159#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
160# define HAVE_SNI 1
161#else
162# define HAVE_SNI 0
163#endif
164
Benjamin Petersond3308222015-09-27 00:09:02 -0700165#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Christian Heimes29eab552018-02-25 12:31:33 +0100166# define HAVE_ALPN 1
167#else
168# define HAVE_ALPN 0
Benjamin Petersoncca27322015-01-23 16:35:37 -0500169#endif
170
Christian Heimes6cdb7952018-02-24 22:12:40 +0100171/* We cannot rely on OPENSSL_NO_NEXTPROTONEG because LibreSSL 2.6.1 dropped
172 * NPN support but did not set OPENSSL_NO_NEXTPROTONEG for compatibility
173 * reasons. The check for TLSEXT_TYPE_next_proto_neg works with
174 * OpenSSL 1.0.1+ and LibreSSL.
Christian Heimes29eab552018-02-25 12:31:33 +0100175 * OpenSSL 1.1.1-pre1 dropped NPN but still has TLSEXT_TYPE_next_proto_neg.
Christian Heimes6cdb7952018-02-24 22:12:40 +0100176 */
177#ifdef OPENSSL_NO_NEXTPROTONEG
Christian Heimes29eab552018-02-25 12:31:33 +0100178# define HAVE_NPN 0
179#elif (OPENSSL_VERSION_NUMBER >= 0x10101000L) && !defined(LIBRESSL_VERSION_NUMBER)
180# define HAVE_NPN 0
Christian Heimes6cdb7952018-02-24 22:12:40 +0100181#elif defined(TLSEXT_TYPE_next_proto_neg)
Christian Heimes29eab552018-02-25 12:31:33 +0100182# define HAVE_NPN 1
Christian Heimes6cdb7952018-02-24 22:12:40 +0100183#else
Christian Heimes29eab552018-02-25 12:31:33 +0100184# define HAVE_NPN 0
185#endif
Christian Heimes6cdb7952018-02-24 22:12:40 +0100186
Victor Stinner524714e2016-07-22 17:43:59 +0200187#ifndef INVALID_SOCKET /* MS defines this */
188#define INVALID_SOCKET (-1)
189#endif
190
Christian Heimes4ca07392018-03-24 15:41:37 +0100191/* OpenSSL 1.0.2 and LibreSSL needs extra code for locking */
192#ifndef OPENSSL_VERSION_1_1
193#define HAVE_OPENSSL_CRYPTO_LOCK
194#endif
195
196#if defined(OPENSSL_VERSION_1_1) && !defined(OPENSSL_NO_SSL2)
Christian Heimes598894f2016-09-05 23:19:05 +0200197#define OPENSSL_NO_SSL2
198#endif
Christian Heimes4ca07392018-03-24 15:41:37 +0100199
200#ifndef PY_OPENSSL_1_1_API
201/* OpenSSL 1.1 API shims for OpenSSL < 1.1.0 and LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200202
203#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200204#define TLS_client_method SSLv23_client_method
205#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200206
207static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
208{
209 return ne->set;
210}
211
212#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200213/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200214static int COMP_get_type(const COMP_METHOD *meth)
215{
216 return meth->type;
217}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200218/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200219#endif
220
221static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
222{
223 return ctx->default_passwd_callback;
224}
225
226static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
227{
228 return ctx->default_passwd_callback_userdata;
229}
230
231static int X509_OBJECT_get_type(X509_OBJECT *x)
232{
233 return x->type;
234}
235
236static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
237{
238 return x->data.x509;
239}
240
241static int BIO_up_ref(BIO *b)
242{
243 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
244 return 1;
245}
246
247static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
248 return store->objs;
249}
250
Christian Heimes99a65702016-09-10 23:44:53 +0200251static int
252SSL_SESSION_has_ticket(const SSL_SESSION *s)
253{
254 return (s->tlsext_ticklen > 0) ? 1 : 0;
255}
256
257static unsigned long
258SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
259{
260 return s->tlsext_tick_lifetime_hint;
261}
262
Christian Heimes4ca07392018-03-24 15:41:37 +0100263#endif /* OpenSSL < 1.1.0 or LibreSSL < 2.7.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200264
Christian Heimes892d66e2018-01-29 14:10:18 +0100265/* Default cipher suites */
266#ifndef PY_SSL_DEFAULT_CIPHERS
267#define PY_SSL_DEFAULT_CIPHERS 1
268#endif
269
270#if PY_SSL_DEFAULT_CIPHERS == 0
271 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
272 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
273 #endif
274#elif PY_SSL_DEFAULT_CIPHERS == 1
275/* Python custom selection of sensible ciper suites
276 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
277 * !aNULL:!eNULL: really no NULL ciphers
278 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
279 * !aDSS: no authentication with discrete logarithm DSA algorithm
280 * !SRP:!PSK: no secure remote password or pre-shared key authentication
281 */
282 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
283#elif PY_SSL_DEFAULT_CIPHERS == 2
284/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
285 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
286#else
287 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
288#endif
289
Christian Heimes598894f2016-09-05 23:19:05 +0200290
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000291enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000292 /* these mirror ssl.h */
293 PY_SSL_ERROR_NONE,
294 PY_SSL_ERROR_SSL,
295 PY_SSL_ERROR_WANT_READ,
296 PY_SSL_ERROR_WANT_WRITE,
297 PY_SSL_ERROR_WANT_X509_LOOKUP,
298 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
299 PY_SSL_ERROR_ZERO_RETURN,
300 PY_SSL_ERROR_WANT_CONNECT,
301 /* start of non ssl.h errorcodes */
302 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
303 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
304 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000305};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000306
Thomas Woutersed03b412007-08-28 21:37:11 +0000307enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000308 PY_SSL_CLIENT,
309 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000310};
311
312enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000313 PY_SSL_CERT_NONE,
314 PY_SSL_CERT_OPTIONAL,
315 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000316};
317
318enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000319 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200320 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200321 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100322#if HAVE_TLSv1_2
323 PY_SSL_VERSION_TLS1,
324 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200325 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100326#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200327 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000328#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200329 PY_SSL_VERSION_TLS_CLIENT=0x10,
330 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100331};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200332
Christian Heimes698dde12018-02-27 11:54:43 +0100333enum py_proto_version {
334 PY_PROTO_MINIMUM_SUPPORTED = -2,
335 PY_PROTO_SSLv3 = SSL3_VERSION,
336 PY_PROTO_TLSv1 = TLS1_VERSION,
337 PY_PROTO_TLSv1_1 = TLS1_1_VERSION,
338 PY_PROTO_TLSv1_2 = TLS1_2_VERSION,
339#ifdef TLS1_3_VERSION
340 PY_PROTO_TLSv1_3 = TLS1_3_VERSION,
341#else
342 PY_PROTO_TLSv1_3 = 0x304,
343#endif
344 PY_PROTO_MAXIMUM_SUPPORTED = -1,
345
346/* OpenSSL has no dedicated API to set the minimum version to the maximum
347 * available version, and the other way around. We have to figure out the
348 * minimum and maximum available version on our own and hope for the best.
349 */
350#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
351 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_SSLv3,
352#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
353 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1,
354#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
355 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
356#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
357 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
358#elif defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
359 PY_PROTO_MINIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
360#else
361 #error "PY_PROTO_MINIMUM_AVAILABLE not found"
362#endif
363
364#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
365 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_3,
366#elif defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
367 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_2,
368#elif defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
369 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1_1,
370#elif defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
371 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_TLSv1,
372#elif defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
373 PY_PROTO_MAXIMUM_AVAILABLE = PY_PROTO_SSLv3,
374#else
375 #error "PY_PROTO_MAXIMUM_AVAILABLE not found"
376#endif
377};
378
379
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000380/* serves as a flag to see whether we've initialized the SSL thread support. */
381/* 0 means no, greater than 0 means yes */
382
383static unsigned int _ssl_locks_count = 0;
384
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000385/* SSL socket object */
386
387#define X509_NAME_MAXLEN 256
388
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000389/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
390 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
391 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
392#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000393# define HAVE_SSL_CTX_CLEAR_OPTIONS
394#else
395# undef HAVE_SSL_CTX_CLEAR_OPTIONS
396#endif
397
Antoine Pitroud6494802011-07-21 01:11:30 +0200398/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
399 * older SSL, but let's be safe */
400#define PySSL_CB_MAXLEN 128
401
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100402
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000403typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000404 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000405 SSL_CTX *ctx;
Christian Heimes29eab552018-02-25 12:31:33 +0100406#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500407 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100408 int npn_protocols_len;
409#endif
Christian Heimes29eab552018-02-25 12:31:33 +0100410#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -0500411 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300412 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500413#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100414#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +0100415 PyObject *set_sni_cb;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100416#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100417 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100418 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
419 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
420 */
421 unsigned int hostflags;
Christian Heimes11a14932018-02-24 02:35:08 +0100422 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000423} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000424
Antoine Pitrou152efa22010-05-16 18:19:27 +0000425typedef struct {
426 PyObject_HEAD
427 PyObject *Socket; /* weakref to socket on which we're layered */
428 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100429 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200430 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200431 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200432 PyObject *owner; /* Python level "owner" passed to servername callback */
433 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700434 int ssl_errno; /* last seen error from SSL */
435 int c_errno; /* last seen error from libc */
436#ifdef MS_WINDOWS
437 int ws_errno; /* last seen error from winsock */
438#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000439} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000440
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200441typedef struct {
442 PyObject_HEAD
443 BIO *bio;
444 int eof_written;
445} PySSLMemoryBIO;
446
Christian Heimes99a65702016-09-10 23:44:53 +0200447typedef struct {
448 PyObject_HEAD
449 SSL_SESSION *session;
450 PySSLContext *ctx;
451} PySSLSession;
452
Antoine Pitrou152efa22010-05-16 18:19:27 +0000453static PyTypeObject PySSLContext_Type;
454static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200455static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200456static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000457
Steve Dowere6eb48c2017-09-08 15:16:15 -0700458#ifdef MS_WINDOWS
459#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
460 (sock)->ws_errno = WSAGetLastError(); \
461 _PySSL_FIX_ERRNO; \
462 (sock)->c_errno = errno; \
463 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
464 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
465#else
466#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
467 (sock)->c_errno = errno; \
468 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
469 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
470#endif
471#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
472
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300473/*[clinic input]
474module _ssl
475class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
476class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
477class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200478class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300479[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200480/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300481
482#include "clinic/_ssl.c.h"
483
Victor Stinner14690702015-04-06 22:46:13 +0200484static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000485
Christian Heimes141c5e82018-02-24 21:10:57 +0100486static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
487static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000488#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200489#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200490#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000491
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000492typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000493 SOCKET_IS_NONBLOCKING,
494 SOCKET_IS_BLOCKING,
495 SOCKET_HAS_TIMED_OUT,
496 SOCKET_HAS_BEEN_CLOSED,
497 SOCKET_TOO_LARGE_FOR_SELECT,
498 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000499} timeout_state;
500
Thomas Woutersed03b412007-08-28 21:37:11 +0000501/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000502#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200503#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000504
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200505/* Get the socket from a PySSLSocket, if it has one */
506#define GET_SOCKET(obj) ((obj)->Socket ? \
507 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200508
Victor Stinner14690702015-04-06 22:46:13 +0200509/* If sock is NULL, use a timeout of 0 second */
510#define GET_SOCKET_TIMEOUT(sock) \
511 ((sock != NULL) ? (sock)->sock_timeout : 0)
512
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200513/*
514 * SSL errors.
515 */
516
517PyDoc_STRVAR(SSLError_doc,
518"An error occurred in the SSL implementation.");
519
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700520PyDoc_STRVAR(SSLCertVerificationError_doc,
521"A certificate could not be verified.");
522
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200523PyDoc_STRVAR(SSLZeroReturnError_doc,
524"SSL/TLS session closed cleanly.");
525
526PyDoc_STRVAR(SSLWantReadError_doc,
527"Non-blocking SSL socket needs to read more data\n"
528"before the requested operation can be completed.");
529
530PyDoc_STRVAR(SSLWantWriteError_doc,
531"Non-blocking SSL socket needs to write more data\n"
532"before the requested operation can be completed.");
533
534PyDoc_STRVAR(SSLSyscallError_doc,
535"System error when attempting SSL operation.");
536
537PyDoc_STRVAR(SSLEOFError_doc,
538"SSL/TLS connection terminated abruptly.");
539
540static PyObject *
541SSLError_str(PyOSErrorObject *self)
542{
543 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
544 Py_INCREF(self->strerror);
545 return self->strerror;
546 }
547 else
548 return PyObject_Str(self->args);
549}
550
551static PyType_Slot sslerror_type_slots[] = {
552 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
553 {Py_tp_doc, SSLError_doc},
554 {Py_tp_str, SSLError_str},
555 {0, 0},
556};
557
558static PyType_Spec sslerror_type_spec = {
559 "ssl.SSLError",
560 sizeof(PyOSErrorObject),
561 0,
562 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
563 sslerror_type_slots
564};
565
566static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700567fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
568 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569{
570 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200572 PyObject *init_value, *msg, *key;
573 _Py_IDENTIFIER(reason);
574 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700575 _Py_IDENTIFIER(verify_message);
576 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577
578 if (errcode != 0) {
579 int lib, reason;
580
581 lib = ERR_GET_LIB(errcode);
582 reason = ERR_GET_REASON(errcode);
583 key = Py_BuildValue("ii", lib, reason);
584 if (key == NULL)
585 goto fail;
586 reason_obj = PyDict_GetItem(err_codes_to_names, key);
587 Py_DECREF(key);
588 if (reason_obj == NULL) {
589 /* XXX if reason < 100, it might reflect a library number (!!) */
590 PyErr_Clear();
591 }
592 key = PyLong_FromLong(lib);
593 if (key == NULL)
594 goto fail;
595 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
596 Py_DECREF(key);
597 if (lib_obj == NULL) {
598 PyErr_Clear();
599 }
600 if (errstr == NULL)
601 errstr = ERR_reason_error_string(errcode);
602 }
603 if (errstr == NULL)
604 errstr = "unknown error";
605
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700606 /* verify code for cert validation error */
607 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
608 const char *verify_str = NULL;
609 long verify_code;
610
611 verify_code = SSL_get_verify_result(sslsock->ssl);
612 verify_code_obj = PyLong_FromLong(verify_code);
613 if (verify_code_obj == NULL) {
614 goto fail;
615 }
616
617 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700618#ifdef X509_V_ERR_HOSTNAME_MISMATCH
619 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700620 case X509_V_ERR_HOSTNAME_MISMATCH:
621 verify_obj = PyUnicode_FromFormat(
622 "Hostname mismatch, certificate is not valid for '%S'.",
623 sslsock->server_hostname
624 );
625 break;
Christian Heimes09153602017-09-08 14:47:58 -0700626#endif
627#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700628 case X509_V_ERR_IP_ADDRESS_MISMATCH:
629 verify_obj = PyUnicode_FromFormat(
630 "IP address mismatch, certificate is not valid for '%S'.",
631 sslsock->server_hostname
632 );
633 break;
Christian Heimes09153602017-09-08 14:47:58 -0700634#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 default:
636 verify_str = X509_verify_cert_error_string(verify_code);
637 if (verify_str != NULL) {
638 verify_obj = PyUnicode_FromString(verify_str);
639 } else {
640 verify_obj = Py_None;
641 Py_INCREF(verify_obj);
642 }
643 break;
644 }
645 if (verify_obj == NULL) {
646 goto fail;
647 }
648 }
649
650 if (verify_obj && reason_obj && lib_obj)
651 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
652 lib_obj, reason_obj, errstr, verify_obj,
653 lineno);
654 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200655 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
656 lib_obj, reason_obj, errstr, lineno);
657 else if (lib_obj)
658 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
659 lib_obj, errstr, lineno);
660 else
661 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200662 if (msg == NULL)
663 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100664
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200665 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100666 if (init_value == NULL)
667 goto fail;
668
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200669 err_value = PyObject_CallObject(type, init_value);
670 Py_DECREF(init_value);
671 if (err_value == NULL)
672 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100673
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200674 if (reason_obj == NULL)
675 reason_obj = Py_None;
676 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
677 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700678
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200679 if (lib_obj == NULL)
680 lib_obj = Py_None;
681 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
682 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700683
684 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
685 /* Only set verify code / message for SSLCertVerificationError */
686 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
687 verify_code_obj))
688 goto fail;
689 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
690 goto fail;
691 }
692
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200693 PyErr_SetObject(type, err_value);
694fail:
695 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700696 Py_XDECREF(verify_code_obj);
697 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200698}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000699
700static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700701PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000702{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200703 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200704 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000705 int err;
706 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200707 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000708
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000709 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200710 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000711
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700712 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700713 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000714
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 switch (err) {
716 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200717 errstr = "TLS/SSL connection has been closed (EOF)";
718 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 p = PY_SSL_ERROR_ZERO_RETURN;
720 break;
721 case SSL_ERROR_WANT_READ:
722 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200723 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 p = PY_SSL_ERROR_WANT_READ;
725 break;
726 case SSL_ERROR_WANT_WRITE:
727 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200728 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 errstr = "The operation did not complete (write)";
730 break;
731 case SSL_ERROR_WANT_X509_LOOKUP:
732 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000733 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000734 break;
735 case SSL_ERROR_WANT_CONNECT:
736 p = PY_SSL_ERROR_WANT_CONNECT;
737 errstr = "The operation did not complete (connect)";
738 break;
739 case SSL_ERROR_SYSCALL:
740 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000741 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700742 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000743 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000744 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200745 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000746 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200747 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000748 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000749 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700750#ifdef MS_WINDOWS
751 if (sslsock->ws_errno)
752 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
753#endif
754 if (sslsock->c_errno) {
755 errno = sslsock->c_errno;
756 return PyErr_SetFromErrno(PyExc_OSError);
757 }
758 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200759 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000760 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200761 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000762 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000763 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200764 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000765 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 }
767 } else {
768 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 }
770 break;
771 }
772 case SSL_ERROR_SSL:
773 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700775 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200776 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000777 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700778 }
779 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
780 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
781 type = PySSLCertVerificationErrorObject;
782 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 break;
784 }
785 default:
786 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
787 errstr = "Invalid error code";
788 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700790 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000791 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000793}
794
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000795static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200796_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000797
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200798 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200800 else
801 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700802 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000803 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000805}
806
Christian Heimes61d478c2018-01-27 15:51:38 +0100807/*
808 * SSL objects
809 */
810
811static int
812_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
813{
814 int retval = -1;
815 ASN1_OCTET_STRING *ip;
816 PyObject *hostname;
817 size_t len;
818
819 assert(server_hostname);
820
821 /* Disable OpenSSL's special mode with leading dot in hostname:
822 * When name starts with a dot (e.g ".example.com"), it will be
823 * matched by a certificate valid for any sub-domain of name.
824 */
825 len = strlen(server_hostname);
826 if (len == 0 || *server_hostname == '.') {
827 PyErr_SetString(
828 PyExc_ValueError,
829 "server_hostname cannot be an empty string or start with a "
830 "leading dot.");
831 return retval;
832 }
833
834 /* inet_pton is not available on all platforms. */
835 ip = a2i_IPADDRESS(server_hostname);
836 if (ip == NULL) {
837 ERR_clear_error();
838 }
839
Christian Heimes11a14932018-02-24 02:35:08 +0100840 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100841 if (hostname == NULL) {
842 goto error;
843 }
844 self->server_hostname = hostname;
845
846 /* Only send SNI extension for non-IP hostnames */
847 if (ip == NULL) {
848 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
849 _setSSLError(NULL, 0, __FILE__, __LINE__);
850 }
851 }
852 if (self->ctx->check_hostname) {
853 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
854 if (ip == NULL) {
Christian Heimesd02ac252018-03-25 12:36:13 +0200855 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname,
856 strlen(server_hostname))) {
Christian Heimes61d478c2018-01-27 15:51:38 +0100857 _setSSLError(NULL, 0, __FILE__, __LINE__);
858 goto error;
859 }
860 } else {
861 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
862 ASN1_STRING_length(ip))) {
863 _setSSLError(NULL, 0, __FILE__, __LINE__);
864 goto error;
865 }
866 }
867 }
868 retval = 0;
869 error:
870 if (ip != NULL) {
871 ASN1_OCTET_STRING_free(ip);
872 }
873 return retval;
874}
875
Antoine Pitrou152efa22010-05-16 18:19:27 +0000876static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100877newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000878 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200879 char *server_hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +0100880 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200881 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000882{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000883 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100884 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200885 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000886
Antoine Pitrou152efa22010-05-16 18:19:27 +0000887 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000888 if (self == NULL)
889 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000890
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100893 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700894 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200895 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200896 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700897 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700898 self->ssl_errno = 0;
899 self->c_errno = 0;
900#ifdef MS_WINDOWS
901 self->ws_errno = 0;
902#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000904 /* Make sure the SSL error state is initialized */
905 (void) ERR_get_state();
906 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000908 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000909 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200911 SSL_set_app_data(self->ssl, self);
912 if (sock) {
913 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
914 } else {
915 /* BIOs are reference counted and SSL_set_bio borrows our reference.
916 * To prevent a double free in memory_bio_dealloc() we need to take an
917 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200918 BIO_up_ref(inbio->bio);
919 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200920 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
921 }
Alex Gaynorf0422422018-05-14 11:51:45 -0400922 SSL_set_mode(self->ssl,
923 SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER | SSL_MODE_AUTO_RETRY);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000924
Christian Heimes61d478c2018-01-27 15:51:38 +0100925 if (server_hostname != NULL) {
926 if (_ssl_configure_hostname(self, server_hostname) < 0) {
927 Py_DECREF(self);
928 return NULL;
929 }
930 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 /* If the socket is in non-blocking mode or timeout mode, set the BIO
932 * to non-blocking mode (blocking is the default)
933 */
Victor Stinnere2452312015-03-28 03:00:46 +0100934 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
936 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
937 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000938
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000939 PySSL_BEGIN_ALLOW_THREADS
940 if (socket_type == PY_SSL_CLIENT)
941 SSL_set_connect_state(self->ssl);
942 else
943 SSL_set_accept_state(self->ssl);
944 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000945
Antoine Pitroud6494802011-07-21 01:11:30 +0200946 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200947 if (sock != NULL) {
948 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
949 if (self->Socket == NULL) {
950 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200951 return NULL;
952 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100953 }
Christian Heimes141c5e82018-02-24 21:10:57 +0100954 if (owner && owner != Py_None) {
955 if (PySSL_set_owner(self, owner, NULL) == -1) {
956 Py_DECREF(self);
957 return NULL;
958 }
959 }
960 if (session && session != Py_None) {
961 if (PySSL_set_session(self, session, NULL) == -1) {
962 Py_DECREF(self);
963 return NULL;
964 }
965 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000967}
968
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000969/* SSL object methods */
970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300971/*[clinic input]
972_ssl._SSLSocket.do_handshake
973[clinic start generated code]*/
974
975static PyObject *
976_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
977/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000978{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 int ret;
980 int err;
981 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200982 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200983 _PyTime_t timeout, deadline = 0;
984 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000985
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200986 if (sock) {
987 if (((PyObject*)sock) == Py_None) {
988 _setSSLError("Underlying socket connection gone",
989 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
990 return NULL;
991 }
992 Py_INCREF(sock);
993
994 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100995 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200996 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
997 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000998 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000999
Victor Stinner14690702015-04-06 22:46:13 +02001000 timeout = GET_SOCKET_TIMEOUT(sock);
1001 has_timeout = (timeout > 0);
1002 if (has_timeout)
1003 deadline = _PyTime_GetMonotonicClock() + timeout;
1004
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001005 /* Actually negotiate SSL connection */
1006 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 do {
Bill Janssen6e027db2007-11-15 22:23:56 +00001008 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07001010 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07001012 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001013
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001014 if (PyErr_CheckSignals())
1015 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001016
Victor Stinner14690702015-04-06 22:46:13 +02001017 if (has_timeout)
1018 timeout = deadline - _PyTime_GetMonotonicClock();
1019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001020 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02001021 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02001023 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 } else {
1025 sockstate = SOCKET_OPERATION_OK;
1026 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001029 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001030 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001031 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1033 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001034 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001035 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1037 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +00001038 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001039 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
1041 break;
1042 }
1043 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001044 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 if (ret < 1)
1046 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +00001047
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02001048 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001049
1050error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001051 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00001052 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001053}
1054
Thomas Woutersed03b412007-08-28 21:37:11 +00001055static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001056_asn1obj2py(const ASN1_OBJECT *name, int no_name)
1057{
1058 char buf[X509_NAME_MAXLEN];
1059 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001061 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001062
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001063 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001064 if (buflen < 0) {
1065 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001066 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001068 /* initial buffer is too small for oid + terminating null byte */
1069 if (buflen > X509_NAME_MAXLEN - 1) {
1070 /* make OBJ_obj2txt() calculate the required buflen */
1071 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
1072 /* allocate len + 1 for terminating NULL byte */
1073 namebuf = PyMem_Malloc(buflen + 1);
1074 if (namebuf == NULL) {
1075 PyErr_NoMemory();
1076 return NULL;
1077 }
1078 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1079 if (buflen < 0) {
1080 _setSSLError(NULL, 0, __FILE__, __LINE__);
1081 goto done;
1082 }
1083 }
1084 if (!buflen && no_name) {
1085 Py_INCREF(Py_None);
1086 name_obj = Py_None;
1087 }
1088 else {
1089 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1090 }
1091
1092 done:
1093 if (buf != namebuf) {
1094 PyMem_Free(namebuf);
1095 }
1096 return name_obj;
1097}
1098
1099static PyObject *
1100_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1101{
1102 Py_ssize_t buflen;
1103 unsigned char *valuebuf = NULL;
1104 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001105
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001106 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1107 if (buflen < 0) {
1108 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001109 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001111 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001114}
1115
1116static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001118{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001119 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1120 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1121 PyObject *rdnt;
1122 PyObject *attr = NULL; /* tuple to hold an attribute */
1123 int entry_count = X509_NAME_entry_count(xname);
1124 X509_NAME_ENTRY *entry;
1125 ASN1_OBJECT *name;
1126 ASN1_STRING *value;
1127 int index_counter;
1128 int rdn_level = -1;
1129 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 dn = PyList_New(0);
1132 if (dn == NULL)
1133 return NULL;
1134 /* now create another tuple to hold the top-level RDN */
1135 rdn = PyList_New(0);
1136 if (rdn == NULL)
1137 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 for (index_counter = 0;
1140 index_counter < entry_count;
1141 index_counter++)
1142 {
1143 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 /* check to see if we've gotten to a new RDN */
1146 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001147 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 /* yes, new RDN */
1149 /* add old RDN to DN */
1150 rdnt = PyList_AsTuple(rdn);
1151 Py_DECREF(rdn);
1152 if (rdnt == NULL)
1153 goto fail0;
1154 retcode = PyList_Append(dn, rdnt);
1155 Py_DECREF(rdnt);
1156 if (retcode < 0)
1157 goto fail0;
1158 /* create new RDN */
1159 rdn = PyList_New(0);
1160 if (rdn == NULL)
1161 goto fail0;
1162 }
1163 }
Christian Heimes598894f2016-09-05 23:19:05 +02001164 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 /* now add this attribute to the current RDN */
1167 name = X509_NAME_ENTRY_get_object(entry);
1168 value = X509_NAME_ENTRY_get_data(entry);
1169 attr = _create_tuple_for_attribute(name, value);
1170 /*
1171 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1172 entry->set,
1173 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1174 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1175 */
1176 if (attr == NULL)
1177 goto fail1;
1178 retcode = PyList_Append(rdn, attr);
1179 Py_DECREF(attr);
1180 if (retcode < 0)
1181 goto fail1;
1182 }
1183 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001184 if (rdn != NULL) {
1185 if (PyList_GET_SIZE(rdn) > 0) {
1186 rdnt = PyList_AsTuple(rdn);
1187 Py_DECREF(rdn);
1188 if (rdnt == NULL)
1189 goto fail0;
1190 retcode = PyList_Append(dn, rdnt);
1191 Py_DECREF(rdnt);
1192 if (retcode < 0)
1193 goto fail0;
1194 }
1195 else {
1196 Py_DECREF(rdn);
1197 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001198 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 /* convert list to tuple */
1201 rdnt = PyList_AsTuple(dn);
1202 Py_DECREF(dn);
1203 if (rdnt == NULL)
1204 return NULL;
1205 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001206
1207 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001208 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001209
1210 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001211 Py_XDECREF(dn);
1212 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001213}
1214
1215static PyObject *
1216_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001218 /* this code follows the procedure outlined in
1219 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1220 function to extract the STACK_OF(GENERAL_NAME),
1221 then iterates through the stack to add the
1222 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001223
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001224 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001225 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001226 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001227 GENERAL_NAMES *names = NULL;
1228 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001229 BIO *biobuf = NULL;
1230 char buf[2048];
1231 char *vptr;
1232 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001233
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001234 if (certificate == NULL)
1235 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001236
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001237 /* get a memory buffer */
1238 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001239
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001240 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1241 certificate, NID_subject_alt_name, NULL, NULL);
1242 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 if (peer_alt_names == Py_None) {
1244 peer_alt_names = PyList_New(0);
1245 if (peer_alt_names == NULL)
1246 goto fail;
1247 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001249 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001251 int gntype;
1252 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001253
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001254 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001255 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001256 switch (gntype) {
1257 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 /* we special-case DirName as a tuple of
1259 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 t = PyTuple_New(2);
1262 if (t == NULL) {
1263 goto fail;
1264 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001265
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 v = PyUnicode_FromString("DirName");
1267 if (v == NULL) {
1268 Py_DECREF(t);
1269 goto fail;
1270 }
1271 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001273 v = _create_tuple_for_X509_NAME (name->d.dirn);
1274 if (v == NULL) {
1275 Py_DECREF(t);
1276 goto fail;
1277 }
1278 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001279 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001280
Christian Heimes824f7f32013-08-17 00:54:47 +02001281 case GEN_EMAIL:
1282 case GEN_DNS:
1283 case GEN_URI:
1284 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1285 correctly, CVE-2013-4238 */
1286 t = PyTuple_New(2);
1287 if (t == NULL)
1288 goto fail;
1289 switch (gntype) {
1290 case GEN_EMAIL:
1291 v = PyUnicode_FromString("email");
1292 as = name->d.rfc822Name;
1293 break;
1294 case GEN_DNS:
1295 v = PyUnicode_FromString("DNS");
1296 as = name->d.dNSName;
1297 break;
1298 case GEN_URI:
1299 v = PyUnicode_FromString("URI");
1300 as = name->d.uniformResourceIdentifier;
1301 break;
1302 }
1303 if (v == NULL) {
1304 Py_DECREF(t);
1305 goto fail;
1306 }
1307 PyTuple_SET_ITEM(t, 0, v);
1308 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1309 ASN1_STRING_length(as));
1310 if (v == NULL) {
1311 Py_DECREF(t);
1312 goto fail;
1313 }
1314 PyTuple_SET_ITEM(t, 1, v);
1315 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001316
Christian Heimes1c03abd2016-09-06 23:25:35 +02001317 case GEN_RID:
1318 t = PyTuple_New(2);
1319 if (t == NULL)
1320 goto fail;
1321
1322 v = PyUnicode_FromString("Registered ID");
1323 if (v == NULL) {
1324 Py_DECREF(t);
1325 goto fail;
1326 }
1327 PyTuple_SET_ITEM(t, 0, v);
1328
1329 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1330 if (len < 0) {
1331 Py_DECREF(t);
1332 _setSSLError(NULL, 0, __FILE__, __LINE__);
1333 goto fail;
1334 } else if (len >= (int)sizeof(buf)) {
1335 v = PyUnicode_FromString("<INVALID>");
1336 } else {
1337 v = PyUnicode_FromStringAndSize(buf, len);
1338 }
1339 if (v == NULL) {
1340 Py_DECREF(t);
1341 goto fail;
1342 }
1343 PyTuple_SET_ITEM(t, 1, v);
1344 break;
1345
Christian Heimes824f7f32013-08-17 00:54:47 +02001346 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001347 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001348 switch (gntype) {
1349 /* check for new general name type */
1350 case GEN_OTHERNAME:
1351 case GEN_X400:
1352 case GEN_EDIPARTY:
1353 case GEN_IPADD:
1354 case GEN_RID:
1355 break;
1356 default:
1357 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1358 "Unknown general name type %d",
1359 gntype) == -1) {
1360 goto fail;
1361 }
1362 break;
1363 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001364 (void) BIO_reset(biobuf);
1365 GENERAL_NAME_print(biobuf, name);
1366 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1367 if (len < 0) {
1368 _setSSLError(NULL, 0, __FILE__, __LINE__);
1369 goto fail;
1370 }
1371 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001372 if (vptr == NULL) {
1373 PyErr_Format(PyExc_ValueError,
1374 "Invalid value %.200s",
1375 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001376 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001377 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 t = PyTuple_New(2);
1379 if (t == NULL)
1380 goto fail;
1381 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1382 if (v == NULL) {
1383 Py_DECREF(t);
1384 goto fail;
1385 }
1386 PyTuple_SET_ITEM(t, 0, v);
1387 v = PyUnicode_FromStringAndSize((vptr + 1),
1388 (len - (vptr - buf + 1)));
1389 if (v == NULL) {
1390 Py_DECREF(t);
1391 goto fail;
1392 }
1393 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001394 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001396
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001397 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001399 if (PyList_Append(peer_alt_names, t) < 0) {
1400 Py_DECREF(t);
1401 goto fail;
1402 }
1403 Py_DECREF(t);
1404 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001405 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 }
1407 BIO_free(biobuf);
1408 if (peer_alt_names != Py_None) {
1409 v = PyList_AsTuple(peer_alt_names);
1410 Py_DECREF(peer_alt_names);
1411 return v;
1412 } else {
1413 return peer_alt_names;
1414 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001415
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001416
1417 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 if (biobuf != NULL)
1419 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001420
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001421 if (peer_alt_names != Py_None) {
1422 Py_XDECREF(peer_alt_names);
1423 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001426}
1427
1428static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001429_get_aia_uri(X509 *certificate, int nid) {
1430 PyObject *lst = NULL, *ostr = NULL;
1431 int i, result;
1432 AUTHORITY_INFO_ACCESS *info;
1433
1434 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001435 if (info == NULL)
1436 return Py_None;
1437 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1438 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001439 return Py_None;
1440 }
1441
1442 if ((lst = PyList_New(0)) == NULL) {
1443 goto fail;
1444 }
1445
1446 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1447 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1448 ASN1_IA5STRING *uri;
1449
1450 if ((OBJ_obj2nid(ad->method) != nid) ||
1451 (ad->location->type != GEN_URI)) {
1452 continue;
1453 }
1454 uri = ad->location->d.uniformResourceIdentifier;
1455 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1456 uri->length);
1457 if (ostr == NULL) {
1458 goto fail;
1459 }
1460 result = PyList_Append(lst, ostr);
1461 Py_DECREF(ostr);
1462 if (result < 0) {
1463 goto fail;
1464 }
1465 }
1466 AUTHORITY_INFO_ACCESS_free(info);
1467
1468 /* convert to tuple or None */
1469 if (PyList_Size(lst) == 0) {
1470 Py_DECREF(lst);
1471 return Py_None;
1472 } else {
1473 PyObject *tup;
1474 tup = PyList_AsTuple(lst);
1475 Py_DECREF(lst);
1476 return tup;
1477 }
1478
1479 fail:
1480 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001481 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001482 return NULL;
1483}
1484
1485static PyObject *
1486_get_crl_dp(X509 *certificate) {
1487 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001488 int i, j;
1489 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001490
Christian Heimes598894f2016-09-05 23:19:05 +02001491 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001492
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001493 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001494 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001495
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001496 lst = PyList_New(0);
1497 if (lst == NULL)
1498 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001499
1500 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1501 DIST_POINT *dp;
1502 STACK_OF(GENERAL_NAME) *gns;
1503
1504 dp = sk_DIST_POINT_value(dps, i);
1505 gns = dp->distpoint->name.fullname;
1506
1507 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1508 GENERAL_NAME *gn;
1509 ASN1_IA5STRING *uri;
1510 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001511 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001512
1513 gn = sk_GENERAL_NAME_value(gns, j);
1514 if (gn->type != GEN_URI) {
1515 continue;
1516 }
1517 uri = gn->d.uniformResourceIdentifier;
1518 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1519 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001520 if (ouri == NULL)
1521 goto done;
1522
1523 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001524 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001525 if (err < 0)
1526 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001527 }
1528 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001529
1530 /* Convert to tuple. */
1531 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1532
1533 done:
1534 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001535 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001536 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001537}
1538
1539static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001540_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001541
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 PyObject *retval = NULL;
1543 BIO *biobuf = NULL;
1544 PyObject *peer;
1545 PyObject *peer_alt_names = NULL;
1546 PyObject *issuer;
1547 PyObject *version;
1548 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001549 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 ASN1_INTEGER *serialNumber;
1551 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001552 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 ASN1_TIME *notBefore, *notAfter;
1554 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 retval = PyDict_New();
1557 if (retval == NULL)
1558 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560 peer = _create_tuple_for_X509_NAME(
1561 X509_get_subject_name(certificate));
1562 if (peer == NULL)
1563 goto fail0;
1564 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1565 Py_DECREF(peer);
1566 goto fail0;
1567 }
1568 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001569
Antoine Pitroufb046912010-11-09 20:21:19 +00001570 issuer = _create_tuple_for_X509_NAME(
1571 X509_get_issuer_name(certificate));
1572 if (issuer == NULL)
1573 goto fail0;
1574 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001576 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001578 Py_DECREF(issuer);
1579
1580 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001581 if (version == NULL)
1582 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001583 if (PyDict_SetItemString(retval, "version", version) < 0) {
1584 Py_DECREF(version);
1585 goto fail0;
1586 }
1587 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001588
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589 /* get a memory buffer */
1590 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001591
Antoine Pitroufb046912010-11-09 20:21:19 +00001592 (void) BIO_reset(biobuf);
1593 serialNumber = X509_get_serialNumber(certificate);
1594 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1595 i2a_ASN1_INTEGER(biobuf, serialNumber);
1596 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1597 if (len < 0) {
1598 _setSSLError(NULL, 0, __FILE__, __LINE__);
1599 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001600 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001601 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1602 if (sn_obj == NULL)
1603 goto fail1;
1604 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1605 Py_DECREF(sn_obj);
1606 goto fail1;
1607 }
1608 Py_DECREF(sn_obj);
1609
1610 (void) BIO_reset(biobuf);
1611 notBefore = X509_get_notBefore(certificate);
1612 ASN1_TIME_print(biobuf, notBefore);
1613 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1614 if (len < 0) {
1615 _setSSLError(NULL, 0, __FILE__, __LINE__);
1616 goto fail1;
1617 }
1618 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1619 if (pnotBefore == NULL)
1620 goto fail1;
1621 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1622 Py_DECREF(pnotBefore);
1623 goto fail1;
1624 }
1625 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001626
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 (void) BIO_reset(biobuf);
1628 notAfter = X509_get_notAfter(certificate);
1629 ASN1_TIME_print(biobuf, notAfter);
1630 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1631 if (len < 0) {
1632 _setSSLError(NULL, 0, __FILE__, __LINE__);
1633 goto fail1;
1634 }
1635 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1636 if (pnotAfter == NULL)
1637 goto fail1;
1638 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1639 Py_DECREF(pnotAfter);
1640 goto fail1;
1641 }
1642 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001643
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001645
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646 peer_alt_names = _get_peer_alt_names(certificate);
1647 if (peer_alt_names == NULL)
1648 goto fail1;
1649 else if (peer_alt_names != Py_None) {
1650 if (PyDict_SetItemString(retval, "subjectAltName",
1651 peer_alt_names) < 0) {
1652 Py_DECREF(peer_alt_names);
1653 goto fail1;
1654 }
1655 Py_DECREF(peer_alt_names);
1656 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001657
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001658 /* Authority Information Access: OCSP URIs */
1659 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1660 if (obj == NULL) {
1661 goto fail1;
1662 } else if (obj != Py_None) {
1663 result = PyDict_SetItemString(retval, "OCSP", obj);
1664 Py_DECREF(obj);
1665 if (result < 0) {
1666 goto fail1;
1667 }
1668 }
1669
1670 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1671 if (obj == NULL) {
1672 goto fail1;
1673 } else if (obj != Py_None) {
1674 result = PyDict_SetItemString(retval, "caIssuers", obj);
1675 Py_DECREF(obj);
1676 if (result < 0) {
1677 goto fail1;
1678 }
1679 }
1680
1681 /* CDP (CRL distribution points) */
1682 obj = _get_crl_dp(certificate);
1683 if (obj == NULL) {
1684 goto fail1;
1685 } else if (obj != Py_None) {
1686 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1687 Py_DECREF(obj);
1688 if (result < 0) {
1689 goto fail1;
1690 }
1691 }
1692
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001693 BIO_free(biobuf);
1694 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001695
1696 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001697 if (biobuf != NULL)
1698 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001699 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700 Py_XDECREF(retval);
1701 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001702}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001703
Christian Heimes9a5395a2013-06-17 15:44:12 +02001704static PyObject *
1705_certificate_to_der(X509 *certificate)
1706{
1707 unsigned char *bytes_buf = NULL;
1708 int len;
1709 PyObject *retval;
1710
1711 bytes_buf = NULL;
1712 len = i2d_X509(certificate, &bytes_buf);
1713 if (len < 0) {
1714 _setSSLError(NULL, 0, __FILE__, __LINE__);
1715 return NULL;
1716 }
1717 /* this is actually an immutable bytes sequence */
1718 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1719 OPENSSL_free(bytes_buf);
1720 return retval;
1721}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001722
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001723/*[clinic input]
1724_ssl._test_decode_cert
1725 path: object(converter="PyUnicode_FSConverter")
1726 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001727
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001728[clinic start generated code]*/
1729
1730static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001731_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1732/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001733{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001734 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 X509 *x=NULL;
1736 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001737
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1739 PyErr_SetString(PySSLErrorObject,
1740 "Can't malloc memory to read file");
1741 goto fail0;
1742 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001743
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001744 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001745 PyErr_SetString(PySSLErrorObject,
1746 "Can't open file");
1747 goto fail0;
1748 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001749
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1751 if (x == NULL) {
1752 PyErr_SetString(PySSLErrorObject,
1753 "Error decoding PEM-encoded file");
1754 goto fail0;
1755 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001756
Antoine Pitroufb046912010-11-09 20:21:19 +00001757 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001758 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001759
1760 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001761 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001762 if (cert != NULL) BIO_free(cert);
1763 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001764}
1765
1766
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001767/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01001768_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001769 der as binary_mode: bool = False
1770 /
1771
1772Returns the certificate for the peer.
1773
1774If no certificate was provided, returns None. If a certificate was
1775provided, but not validated, returns an empty dictionary. Otherwise
1776returns a dict containing information about the peer certificate.
1777
1778If the optional argument is True, returns a DER-encoded copy of the
1779peer certificate, or None if no certificate was provided. This will
1780return the certificate even if it wasn't validated.
1781[clinic start generated code]*/
1782
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001783static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01001784_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1785/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001786{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001787 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001788 X509 *peer_cert;
1789 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001790
Christian Heimes66dc33b2017-05-23 16:02:02 -07001791 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001792 PyErr_SetString(PyExc_ValueError,
1793 "handshake not done yet");
1794 return NULL;
1795 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001796 peer_cert = SSL_get_peer_certificate(self->ssl);
1797 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001798 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001799
Antoine Pitrou721738f2012-08-15 23:20:39 +02001800 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001801 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001802 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001803 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001804 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001805 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001806 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001807 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001808 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001809 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001810 X509_free(peer_cert);
1811 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001812}
1813
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001814static PyObject *
1815cipher_to_tuple(const SSL_CIPHER *cipher)
1816{
1817 const char *cipher_name, *cipher_protocol;
1818 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001819 if (retval == NULL)
1820 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001821
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001822 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001823 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001824 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001825 PyTuple_SET_ITEM(retval, 0, Py_None);
1826 } else {
1827 v = PyUnicode_FromString(cipher_name);
1828 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001829 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001830 PyTuple_SET_ITEM(retval, 0, v);
1831 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001832
1833 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001834 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001835 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001836 PyTuple_SET_ITEM(retval, 1, Py_None);
1837 } else {
1838 v = PyUnicode_FromString(cipher_protocol);
1839 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001840 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001841 PyTuple_SET_ITEM(retval, 1, v);
1842 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001843
1844 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001845 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001846 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001847 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001848
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001849 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001850
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001851 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 Py_DECREF(retval);
1853 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001854}
1855
Christian Heimes25bfcd52016-09-06 00:04:45 +02001856#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1857static PyObject *
1858cipher_to_dict(const SSL_CIPHER *cipher)
1859{
1860 const char *cipher_name, *cipher_protocol;
1861
1862 unsigned long cipher_id;
1863 int alg_bits, strength_bits, len;
1864 char buf[512] = {0};
1865#if OPENSSL_VERSION_1_1
1866 int aead, nid;
1867 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1868#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001869
1870 /* can be NULL */
1871 cipher_name = SSL_CIPHER_get_name(cipher);
1872 cipher_protocol = SSL_CIPHER_get_version(cipher);
1873 cipher_id = SSL_CIPHER_get_id(cipher);
1874 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001875 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1876 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001877 if (len > 1 && buf[len-1] == '\n')
1878 buf[len-1] = '\0';
1879 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1880
1881#if OPENSSL_VERSION_1_1
1882 aead = SSL_CIPHER_is_aead(cipher);
1883 nid = SSL_CIPHER_get_cipher_nid(cipher);
1884 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1885 nid = SSL_CIPHER_get_digest_nid(cipher);
1886 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1887 nid = SSL_CIPHER_get_kx_nid(cipher);
1888 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1889 nid = SSL_CIPHER_get_auth_nid(cipher);
1890 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1891#endif
1892
Victor Stinner410b9882016-09-12 12:00:23 +02001893 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001894 "{sksssssssisi"
1895#if OPENSSL_VERSION_1_1
1896 "sOssssssss"
1897#endif
1898 "}",
1899 "id", cipher_id,
1900 "name", cipher_name,
1901 "protocol", cipher_protocol,
1902 "description", buf,
1903 "strength_bits", strength_bits,
1904 "alg_bits", alg_bits
1905#if OPENSSL_VERSION_1_1
1906 ,"aead", aead ? Py_True : Py_False,
1907 "symmetric", skcipher,
1908 "digest", digest,
1909 "kea", kx,
1910 "auth", auth
1911#endif
1912 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001913}
1914#endif
1915
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001916/*[clinic input]
1917_ssl._SSLSocket.shared_ciphers
1918[clinic start generated code]*/
1919
1920static PyObject *
1921_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1922/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001923{
1924 STACK_OF(SSL_CIPHER) *ciphers;
1925 int i;
1926 PyObject *res;
1927
Christian Heimes598894f2016-09-05 23:19:05 +02001928 ciphers = SSL_get_ciphers(self->ssl);
1929 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001930 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001931 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1932 if (!res)
1933 return NULL;
1934 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1935 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1936 if (!tup) {
1937 Py_DECREF(res);
1938 return NULL;
1939 }
1940 PyList_SET_ITEM(res, i, tup);
1941 }
1942 return res;
1943}
1944
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001945/*[clinic input]
1946_ssl._SSLSocket.cipher
1947[clinic start generated code]*/
1948
1949static PyObject *
1950_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1951/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001952{
1953 const SSL_CIPHER *current;
1954
1955 if (self->ssl == NULL)
1956 Py_RETURN_NONE;
1957 current = SSL_get_current_cipher(self->ssl);
1958 if (current == NULL)
1959 Py_RETURN_NONE;
1960 return cipher_to_tuple(current);
1961}
1962
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001963/*[clinic input]
1964_ssl._SSLSocket.version
1965[clinic start generated code]*/
1966
1967static PyObject *
1968_ssl__SSLSocket_version_impl(PySSLSocket *self)
1969/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001970{
1971 const char *version;
1972
1973 if (self->ssl == NULL)
1974 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001975 if (!SSL_is_init_finished(self->ssl)) {
1976 /* handshake not finished */
1977 Py_RETURN_NONE;
1978 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001979 version = SSL_get_version(self->ssl);
1980 if (!strcmp(version, "unknown"))
1981 Py_RETURN_NONE;
1982 return PyUnicode_FromString(version);
1983}
1984
Christian Heimes29eab552018-02-25 12:31:33 +01001985#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001986/*[clinic input]
1987_ssl._SSLSocket.selected_npn_protocol
1988[clinic start generated code]*/
1989
1990static PyObject *
1991_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1992/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1993{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001994 const unsigned char *out;
1995 unsigned int outlen;
1996
Victor Stinner4569cd52013-06-23 14:58:43 +02001997 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001998 &out, &outlen);
1999
2000 if (out == NULL)
2001 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002002 return PyUnicode_FromStringAndSize((char *)out, outlen);
2003}
2004#endif
2005
Christian Heimes29eab552018-02-25 12:31:33 +01002006#if HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002007/*[clinic input]
2008_ssl._SSLSocket.selected_alpn_protocol
2009[clinic start generated code]*/
2010
2011static PyObject *
2012_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
2013/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
2014{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002015 const unsigned char *out;
2016 unsigned int outlen;
2017
2018 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
2019
2020 if (out == NULL)
2021 Py_RETURN_NONE;
2022 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002023}
2024#endif
2025
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002026/*[clinic input]
2027_ssl._SSLSocket.compression
2028[clinic start generated code]*/
2029
2030static PyObject *
2031_ssl__SSLSocket_compression_impl(PySSLSocket *self)
2032/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
2033{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002034#ifdef OPENSSL_NO_COMP
2035 Py_RETURN_NONE;
2036#else
2037 const COMP_METHOD *comp_method;
2038 const char *short_name;
2039
2040 if (self->ssl == NULL)
2041 Py_RETURN_NONE;
2042 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02002043 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002044 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02002045 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01002046 if (short_name == NULL)
2047 Py_RETURN_NONE;
2048 return PyUnicode_DecodeFSDefault(short_name);
2049#endif
2050}
2051
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002052static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
2053 Py_INCREF(self->ctx);
2054 return self->ctx;
2055}
2056
2057static int PySSL_set_context(PySSLSocket *self, PyObject *value,
2058 void *closure) {
2059
2060 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002061#if !HAVE_SNI
2062 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
2063 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01002064 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002065#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002066 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03002067 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002068 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01002069#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002070 } else {
2071 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
2072 return -1;
2073 }
2074
2075 return 0;
2076}
2077
2078PyDoc_STRVAR(PySSL_set_context_doc,
2079"_setter_context(ctx)\n\
2080\
2081This changes the context associated with the SSLSocket. This is typically\n\
Christian Heimes11a14932018-02-24 02:35:08 +01002082used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002083on the SSLContext to change the certificate information associated with the\n\
2084SSLSocket before the cryptographic exchange handshake messages\n");
2085
2086
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002087static PyObject *
2088PySSL_get_server_side(PySSLSocket *self, void *c)
2089{
2090 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2091}
2092
2093PyDoc_STRVAR(PySSL_get_server_side_doc,
2094"Whether this is a server-side socket.");
2095
2096static PyObject *
2097PySSL_get_server_hostname(PySSLSocket *self, void *c)
2098{
2099 if (self->server_hostname == NULL)
2100 Py_RETURN_NONE;
2101 Py_INCREF(self->server_hostname);
2102 return self->server_hostname;
2103}
2104
2105PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2106"The currently set server hostname (for SNI).");
2107
2108static PyObject *
2109PySSL_get_owner(PySSLSocket *self, void *c)
2110{
2111 PyObject *owner;
2112
2113 if (self->owner == NULL)
2114 Py_RETURN_NONE;
2115
2116 owner = PyWeakref_GetObject(self->owner);
2117 Py_INCREF(owner);
2118 return owner;
2119}
2120
2121static int
2122PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2123{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002124 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002125 if (self->owner == NULL)
2126 return -1;
2127 return 0;
2128}
2129
2130PyDoc_STRVAR(PySSL_get_owner_doc,
2131"The Python-level owner of this object.\
2132Passed as \"self\" in servername callback.");
2133
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002134
Antoine Pitrou152efa22010-05-16 18:19:27 +00002135static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002136{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002137 if (self->ssl)
2138 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002140 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002141 Py_XDECREF(self->server_hostname);
2142 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002144}
2145
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002146/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002147 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002148 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002149 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002150
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002151static int
Victor Stinner14690702015-04-06 22:46:13 +02002152PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002153{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002154 int rc;
2155#ifdef HAVE_POLL
2156 struct pollfd pollfd;
2157 _PyTime_t ms;
2158#else
2159 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 fd_set fds;
2161 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002162#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002165 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002167 else if (timeout < 0) {
2168 if (s->sock_timeout > 0)
2169 return SOCKET_HAS_TIMED_OUT;
2170 else
2171 return SOCKET_IS_BLOCKING;
2172 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002174 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002175 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002176 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 /* Prefer poll, if available, since you can poll() any fd
2179 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002180#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002181 pollfd.fd = s->sock_fd;
2182 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002183
Victor Stinner14690702015-04-06 22:46:13 +02002184 /* timeout is in seconds, poll() uses milliseconds */
2185 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002186 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002187
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002188 PySSL_BEGIN_ALLOW_THREADS
2189 rc = poll(&pollfd, 1, (int)ms);
2190 PySSL_END_ALLOW_THREADS
2191#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002193 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002195
Victor Stinner14690702015-04-06 22:46:13 +02002196 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002197
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002198 FD_ZERO(&fds);
2199 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002200
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002201 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002202 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002203 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002204 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002205 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002207 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002209#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002210
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2212 (when we are able to write or when there's something to read) */
2213 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002214}
2215
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002216/*[clinic input]
2217_ssl._SSLSocket.write
2218 b: Py_buffer
2219 /
2220
2221Writes the bytes-like object b into the SSL object.
2222
2223Returns the number of bytes written.
2224[clinic start generated code]*/
2225
2226static PyObject *
2227_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2228/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002229{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 int len;
2231 int sockstate;
2232 int err;
2233 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002234 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002235 _PyTime_t timeout, deadline = 0;
2236 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002237
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002238 if (sock != NULL) {
2239 if (((PyObject*)sock) == Py_None) {
2240 _setSSLError("Underlying socket connection gone",
2241 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2242 return NULL;
2243 }
2244 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002245 }
2246
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002247 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002248 PyErr_Format(PyExc_OverflowError,
2249 "string longer than %d bytes", INT_MAX);
2250 goto error;
2251 }
2252
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002253 if (sock != NULL) {
2254 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002255 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002256 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2257 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2258 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002259
Victor Stinner14690702015-04-06 22:46:13 +02002260 timeout = GET_SOCKET_TIMEOUT(sock);
2261 has_timeout = (timeout > 0);
2262 if (has_timeout)
2263 deadline = _PyTime_GetMonotonicClock() + timeout;
2264
2265 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002266 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002267 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 "The write operation timed out");
2269 goto error;
2270 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2271 PyErr_SetString(PySSLErrorObject,
2272 "Underlying socket has been closed.");
2273 goto error;
2274 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2275 PyErr_SetString(PySSLErrorObject,
2276 "Underlying socket too large for select().");
2277 goto error;
2278 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002279
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002282 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002283 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002284 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002285 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002286
2287 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002289
Victor Stinner14690702015-04-06 22:46:13 +02002290 if (has_timeout)
2291 timeout = deadline - _PyTime_GetMonotonicClock();
2292
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002294 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002296 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 } else {
2298 sockstate = SOCKET_OPERATION_OK;
2299 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002302 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 "The write operation timed out");
2304 goto error;
2305 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2306 PyErr_SetString(PySSLErrorObject,
2307 "Underlying socket has been closed.");
2308 goto error;
2309 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2310 break;
2311 }
2312 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002313
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002314 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002315 if (len > 0)
2316 return PyLong_FromLong(len);
2317 else
2318 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002319
2320error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002321 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002322 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002323}
2324
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002325/*[clinic input]
2326_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002327
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002328Returns the number of already decrypted bytes available for read, pending on the connection.
2329[clinic start generated code]*/
2330
2331static PyObject *
2332_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2333/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002334{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002335 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 PySSL_BEGIN_ALLOW_THREADS
2338 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002339 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 PySSL_END_ALLOW_THREADS
2341 if (count < 0)
2342 return PySSL_SetError(self, count, __FILE__, __LINE__);
2343 else
2344 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002345}
2346
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002347/*[clinic input]
2348_ssl._SSLSocket.read
2349 size as len: int
2350 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002351 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002352 ]
2353 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002354
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002355Read up to size bytes from the SSL socket.
2356[clinic start generated code]*/
2357
2358static PyObject *
2359_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2360 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002361/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002362{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002365 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 int sockstate;
2367 int err;
2368 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002369 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002370 _PyTime_t timeout, deadline = 0;
2371 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002372
Martin Panter5503d472016-03-27 05:35:19 +00002373 if (!group_right_1 && len < 0) {
2374 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2375 return NULL;
2376 }
2377
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002378 if (sock != NULL) {
2379 if (((PyObject*)sock) == Py_None) {
2380 _setSSLError("Underlying socket connection gone",
2381 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2382 return NULL;
2383 }
2384 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 }
2386
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002387 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002388 dest = PyBytes_FromStringAndSize(NULL, len);
2389 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002390 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002391 if (len == 0) {
2392 Py_XDECREF(sock);
2393 return dest;
2394 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002395 mem = PyBytes_AS_STRING(dest);
2396 }
2397 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002398 mem = buffer->buf;
2399 if (len <= 0 || len > buffer->len) {
2400 len = (int) buffer->len;
2401 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002402 PyErr_SetString(PyExc_OverflowError,
2403 "maximum length can't fit in a C 'int'");
2404 goto error;
2405 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002406 if (len == 0) {
2407 count = 0;
2408 goto done;
2409 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002410 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002411 }
2412
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002413 if (sock != NULL) {
2414 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002415 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002416 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2417 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2418 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002419
Victor Stinner14690702015-04-06 22:46:13 +02002420 timeout = GET_SOCKET_TIMEOUT(sock);
2421 has_timeout = (timeout > 0);
2422 if (has_timeout)
2423 deadline = _PyTime_GetMonotonicClock() + timeout;
2424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 PySSL_BEGIN_ALLOW_THREADS
2427 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002428 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002429 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002430
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002431 if (PyErr_CheckSignals())
2432 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002433
Victor Stinner14690702015-04-06 22:46:13 +02002434 if (has_timeout)
2435 timeout = deadline - _PyTime_GetMonotonicClock();
2436
Steve Dowere6eb48c2017-09-08 15:16:15 -07002437 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002439 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002441 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002442 } else if (err == SSL_ERROR_ZERO_RETURN &&
2443 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002444 {
2445 count = 0;
2446 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002448 else
2449 sockstate = SOCKET_OPERATION_OK;
2450
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002451 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002452 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002453 "The read operation timed out");
2454 goto error;
2455 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2456 break;
2457 }
2458 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002460 if (count <= 0) {
2461 PySSL_SetError(self, count, __FILE__, __LINE__);
2462 goto error;
2463 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002464
2465done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002466 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002467 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002468 _PyBytes_Resize(&dest, count);
2469 return dest;
2470 }
2471 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 return PyLong_FromLong(count);
2473 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002474
2475error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002476 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002477 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002478 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002479 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002480}
2481
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002482/*[clinic input]
2483_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002484
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002485Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002486[clinic start generated code]*/
2487
2488static PyObject *
2489_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Christian Heimes141c5e82018-02-24 21:10:57 +01002490/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002491{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002492 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002494 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002495 _PyTime_t timeout, deadline = 0;
2496 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002497
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002498 if (sock != NULL) {
2499 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002500 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002501 _setSSLError("Underlying socket connection gone",
2502 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2503 return NULL;
2504 }
2505 Py_INCREF(sock);
2506
2507 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002508 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002509 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2510 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002511 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002512
Victor Stinner14690702015-04-06 22:46:13 +02002513 timeout = GET_SOCKET_TIMEOUT(sock);
2514 has_timeout = (timeout > 0);
2515 if (has_timeout)
2516 deadline = _PyTime_GetMonotonicClock() + timeout;
2517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 while (1) {
2519 PySSL_BEGIN_ALLOW_THREADS
2520 /* Disable read-ahead so that unwrap can work correctly.
2521 * Otherwise OpenSSL might read in too much data,
2522 * eating clear text data that happens to be
2523 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002524 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 * function is used and the shutdown_seen_zero != 0
2526 * condition is met.
2527 */
2528 if (self->shutdown_seen_zero)
2529 SSL_set_read_ahead(self->ssl, 0);
2530 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002531 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002534 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2535 if (err > 0)
2536 break;
2537 if (err == 0) {
2538 /* Don't loop endlessly; instead preserve legacy
2539 behaviour of trying SSL_shutdown() only twice.
2540 This looks necessary for OpenSSL < 0.9.8m */
2541 if (++zeros > 1)
2542 break;
2543 /* Shutdown was sent, now try receiving */
2544 self->shutdown_seen_zero = 1;
2545 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002546 }
2547
Victor Stinner14690702015-04-06 22:46:13 +02002548 if (has_timeout)
2549 timeout = deadline - _PyTime_GetMonotonicClock();
2550
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002551 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002552 _PySSL_UPDATE_ERRNO(self, err);
2553 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002554 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002555 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002556 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002557 else
2558 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002559
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002560 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002561 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002562 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002563 "The read operation timed out");
2564 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002565 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002566 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002567 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002568 }
2569 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2570 PyErr_SetString(PySSLErrorObject,
2571 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002572 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002573 }
2574 else if (sockstate != SOCKET_OPERATION_OK)
2575 /* Retain the SSL error code */
2576 break;
2577 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002578
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002579 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002580 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002582 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002583 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002584 /* It's already INCREF'ed */
2585 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002586 else
2587 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002588
2589error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002590 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002591 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002592}
2593
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002594/*[clinic input]
Christian Heimes141c5e82018-02-24 21:10:57 +01002595_ssl._SSLSocket.get_channel_binding
2596 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002597
Christian Heimes141c5e82018-02-24 21:10:57 +01002598Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002599
Christian Heimes141c5e82018-02-24 21:10:57 +01002600Raise ValueError if the requested `cb_type` is not supported. Return bytes
2601of the data or None if the data is not available (e.g. before the handshake).
2602Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002603[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002604
Antoine Pitroud6494802011-07-21 01:11:30 +02002605static PyObject *
Christian Heimes141c5e82018-02-24 21:10:57 +01002606_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2607 const char *cb_type)
2608/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002609{
Antoine Pitroud6494802011-07-21 01:11:30 +02002610 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002611 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002612
Christian Heimes141c5e82018-02-24 21:10:57 +01002613 if (strcmp(cb_type, "tls-unique") == 0) {
2614 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2615 /* if session is resumed XOR we are the client */
2616 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2617 }
2618 else {
2619 /* if a new session XOR we are the server */
2620 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2621 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002622 }
2623 else {
Christian Heimes141c5e82018-02-24 21:10:57 +01002624 PyErr_Format(
2625 PyExc_ValueError,
2626 "'%s' channel binding type not implemented",
2627 cb_type
2628 );
2629 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002630 }
2631
2632 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002633 if (len == 0)
2634 Py_RETURN_NONE;
2635
Christian Heimes141c5e82018-02-24 21:10:57 +01002636 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002637}
2638
Christian Heimes99a65702016-09-10 23:44:53 +02002639#ifdef OPENSSL_VERSION_1_1
2640
2641static SSL_SESSION*
2642_ssl_session_dup(SSL_SESSION *session) {
2643 SSL_SESSION *newsession = NULL;
2644 int slen;
2645 unsigned char *senc = NULL, *p;
2646 const unsigned char *const_p;
2647
2648 if (session == NULL) {
2649 PyErr_SetString(PyExc_ValueError, "Invalid session");
2650 goto error;
2651 }
2652
2653 /* get length */
2654 slen = i2d_SSL_SESSION(session, NULL);
2655 if (slen == 0 || slen > 0xFF00) {
2656 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2657 goto error;
2658 }
2659 if ((senc = PyMem_Malloc(slen)) == NULL) {
2660 PyErr_NoMemory();
2661 goto error;
2662 }
2663 p = senc;
2664 if (!i2d_SSL_SESSION(session, &p)) {
2665 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2666 goto error;
2667 }
2668 const_p = senc;
2669 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2670 if (session == NULL) {
2671 goto error;
2672 }
2673 PyMem_Free(senc);
2674 return newsession;
2675 error:
2676 if (senc != NULL) {
2677 PyMem_Free(senc);
2678 }
2679 return NULL;
2680}
2681#endif
2682
2683static PyObject *
2684PySSL_get_session(PySSLSocket *self, void *closure) {
2685 /* get_session can return sessions from a server-side connection,
2686 * it does not check for handshake done or client socket. */
2687 PySSLSession *pysess;
2688 SSL_SESSION *session;
2689
2690#ifdef OPENSSL_VERSION_1_1
2691 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2692 * https://github.com/openssl/openssl/issues/1550 */
2693 session = SSL_get0_session(self->ssl); /* borrowed reference */
2694 if (session == NULL) {
2695 Py_RETURN_NONE;
2696 }
2697 if ((session = _ssl_session_dup(session)) == NULL) {
2698 return NULL;
2699 }
2700#else
2701 session = SSL_get1_session(self->ssl);
2702 if (session == NULL) {
2703 Py_RETURN_NONE;
2704 }
2705#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002706 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002707 if (pysess == NULL) {
2708 SSL_SESSION_free(session);
2709 return NULL;
2710 }
2711
2712 assert(self->ctx);
2713 pysess->ctx = self->ctx;
2714 Py_INCREF(pysess->ctx);
2715 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002716 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002717 return (PyObject *)pysess;
2718}
2719
2720static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2721 void *closure)
2722 {
2723 PySSLSession *pysess;
2724#ifdef OPENSSL_VERSION_1_1
2725 SSL_SESSION *session;
2726#endif
2727 int result;
2728
2729 if (!PySSLSession_Check(value)) {
2730 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2731 return -1;
2732 }
2733 pysess = (PySSLSession *)value;
2734
2735 if (self->ctx->ctx != pysess->ctx->ctx) {
2736 PyErr_SetString(PyExc_ValueError,
2737 "Session refers to a different SSLContext.");
2738 return -1;
2739 }
2740 if (self->socket_type != PY_SSL_CLIENT) {
2741 PyErr_SetString(PyExc_ValueError,
2742 "Cannot set session for server-side SSLSocket.");
2743 return -1;
2744 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002745 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002746 PyErr_SetString(PyExc_ValueError,
2747 "Cannot set session after handshake.");
2748 return -1;
2749 }
2750#ifdef OPENSSL_VERSION_1_1
2751 /* duplicate session */
2752 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2753 return -1;
2754 }
2755 result = SSL_set_session(self->ssl, session);
2756 /* free duplicate, SSL_set_session() bumps ref count */
2757 SSL_SESSION_free(session);
2758#else
2759 result = SSL_set_session(self->ssl, pysess->session);
2760#endif
2761 if (result == 0) {
2762 _setSSLError(NULL, 0, __FILE__, __LINE__);
2763 return -1;
2764 }
2765 return 0;
2766}
2767
2768PyDoc_STRVAR(PySSL_set_session_doc,
2769"_setter_session(session)\n\
2770\
2771Get / set SSLSession.");
2772
2773static PyObject *
2774PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2775 if (SSL_session_reused(self->ssl)) {
2776 Py_RETURN_TRUE;
2777 } else {
2778 Py_RETURN_FALSE;
2779 }
2780}
2781
2782PyDoc_STRVAR(PySSL_get_session_reused_doc,
2783"Was the client session reused during handshake?");
2784
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002785static PyGetSetDef ssl_getsetlist[] = {
2786 {"context", (getter) PySSL_get_context,
2787 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002788 {"server_side", (getter) PySSL_get_server_side, NULL,
2789 PySSL_get_server_side_doc},
2790 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2791 PySSL_get_server_hostname_doc},
2792 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2793 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002794 {"session", (getter) PySSL_get_session,
2795 (setter) PySSL_set_session, PySSL_set_session_doc},
2796 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2797 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002798 {NULL}, /* sentinel */
2799};
2800
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002801static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002802 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2803 _SSL__SSLSOCKET_WRITE_METHODDEF
2804 _SSL__SSLSOCKET_READ_METHODDEF
2805 _SSL__SSLSOCKET_PENDING_METHODDEF
Christian Heimes141c5e82018-02-24 21:10:57 +01002806 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2807 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002808 _SSL__SSLSOCKET_CIPHER_METHODDEF
2809 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2810 _SSL__SSLSOCKET_VERSION_METHODDEF
2811 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2812 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2813 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2814 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002815 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002816};
2817
Antoine Pitrou152efa22010-05-16 18:19:27 +00002818static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002819 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002820 "_ssl._SSLSocket", /*tp_name*/
2821 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002822 0, /*tp_itemsize*/
2823 /* methods */
2824 (destructor)PySSL_dealloc, /*tp_dealloc*/
2825 0, /*tp_print*/
2826 0, /*tp_getattr*/
2827 0, /*tp_setattr*/
2828 0, /*tp_reserved*/
2829 0, /*tp_repr*/
2830 0, /*tp_as_number*/
2831 0, /*tp_as_sequence*/
2832 0, /*tp_as_mapping*/
2833 0, /*tp_hash*/
2834 0, /*tp_call*/
2835 0, /*tp_str*/
2836 0, /*tp_getattro*/
2837 0, /*tp_setattro*/
2838 0, /*tp_as_buffer*/
2839 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2840 0, /*tp_doc*/
2841 0, /*tp_traverse*/
2842 0, /*tp_clear*/
2843 0, /*tp_richcompare*/
2844 0, /*tp_weaklistoffset*/
2845 0, /*tp_iter*/
2846 0, /*tp_iternext*/
2847 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002848 0, /*tp_members*/
2849 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002850};
2851
Antoine Pitrou152efa22010-05-16 18:19:27 +00002852
2853/*
2854 * _SSLContext objects
2855 */
2856
Christian Heimes5fe668c2016-09-12 00:01:11 +02002857static int
2858_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2859{
2860 int mode;
2861 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2862
2863 switch(n) {
2864 case PY_SSL_CERT_NONE:
2865 mode = SSL_VERIFY_NONE;
2866 break;
2867 case PY_SSL_CERT_OPTIONAL:
2868 mode = SSL_VERIFY_PEER;
2869 break;
2870 case PY_SSL_CERT_REQUIRED:
2871 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2872 break;
2873 default:
2874 PyErr_SetString(PyExc_ValueError,
2875 "invalid value for verify_mode");
2876 return -1;
2877 }
2878 /* keep current verify cb */
2879 verify_cb = SSL_CTX_get_verify_callback(ctx);
2880 SSL_CTX_set_verify(ctx, mode, verify_cb);
2881 return 0;
2882}
2883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002884/*[clinic input]
2885@classmethod
2886_ssl._SSLContext.__new__
2887 protocol as proto_version: int
2888 /
2889[clinic start generated code]*/
2890
Antoine Pitrou152efa22010-05-16 18:19:27 +00002891static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002892_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2893/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002894{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002895 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002896 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002898 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002899 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002900#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002901 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002902#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002903
Antoine Pitrou152efa22010-05-16 18:19:27 +00002904 PySSL_BEGIN_ALLOW_THREADS
2905 if (proto_version == PY_SSL_VERSION_TLS1)
2906 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002907#if HAVE_TLSv1_2
2908 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2909 ctx = SSL_CTX_new(TLSv1_1_method());
2910 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2911 ctx = SSL_CTX_new(TLSv1_2_method());
2912#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002913#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002914 else if (proto_version == PY_SSL_VERSION_SSL3)
2915 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002916#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002917#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918 else if (proto_version == PY_SSL_VERSION_SSL2)
2919 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002920#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002921 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002922 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002923 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2924 ctx = SSL_CTX_new(TLS_client_method());
2925 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2926 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002927 else
2928 proto_version = -1;
2929 PySSL_END_ALLOW_THREADS
2930
2931 if (proto_version == -1) {
2932 PyErr_SetString(PyExc_ValueError,
2933 "invalid protocol version");
2934 return NULL;
2935 }
2936 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002937 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002938 return NULL;
2939 }
2940
2941 assert(type != NULL && type->tp_alloc != NULL);
2942 self = (PySSLContext *) type->tp_alloc(type, 0);
2943 if (self == NULL) {
2944 SSL_CTX_free(ctx);
2945 return NULL;
2946 }
2947 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002948 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Christian Heimes11a14932018-02-24 02:35:08 +01002949 self->protocol = proto_version;
Christian Heimes29eab552018-02-25 12:31:33 +01002950#if HAVE_NPN
Christian Heimes5cb31c92012-09-20 12:42:54 +02002951 self->npn_protocols = NULL;
2952#endif
Christian Heimes29eab552018-02-25 12:31:33 +01002953#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05002954 self->alpn_protocols = NULL;
2955#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002956#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01002957 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002958#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002959 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002960 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2961 self->check_hostname = 1;
2962 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2963 Py_DECREF(self);
2964 return NULL;
2965 }
2966 } else {
2967 self->check_hostname = 0;
2968 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2969 Py_DECREF(self);
2970 return NULL;
2971 }
2972 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002973 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002974 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2975 if (proto_version != PY_SSL_VERSION_SSL2)
2976 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002977 if (proto_version != PY_SSL_VERSION_SSL3)
2978 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002979 /* Minimal security flags for server and client side context.
2980 * Client sockets ignore server-side parameters. */
2981#ifdef SSL_OP_NO_COMPRESSION
2982 options |= SSL_OP_NO_COMPRESSION;
2983#endif
2984#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2985 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2986#endif
2987#ifdef SSL_OP_SINGLE_DH_USE
2988 options |= SSL_OP_SINGLE_DH_USE;
2989#endif
2990#ifdef SSL_OP_SINGLE_ECDH_USE
2991 options |= SSL_OP_SINGLE_ECDH_USE;
2992#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002993 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002994
Semen Zhydenko1295e112017-10-15 21:28:31 +02002995 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002996 * It's far from perfect but gives users a better head start. */
2997 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002998#if PY_SSL_DEFAULT_CIPHERS == 2
2999 /* stick to OpenSSL's default settings */
3000 result = 1;
3001#else
3002 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
3003#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02003004 } else {
3005 /* SSLv2 needs MD5 */
3006 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
3007 }
3008 if (result == 0) {
3009 Py_DECREF(self);
3010 ERR_clear_error();
3011 PyErr_SetString(PySSLErrorObject,
3012 "No cipher can be selected.");
3013 return NULL;
3014 }
3015
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08003016#if defined(SSL_MODE_RELEASE_BUFFERS)
3017 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
3018 usage for no cost at all. However, don't do this for OpenSSL versions
3019 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
3020 2014-0198. I can't find exactly which beta fixed this CVE, so be
3021 conservative and assume it wasn't fixed until release. We do this check
3022 at runtime to avoid problems from the dynamic linker.
3023 See #25672 for more on this. */
3024 libver = SSLeay();
3025 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
3026 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
3027 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
3028 }
3029#endif
3030
3031
Donald Stufft8ae264c2017-03-02 11:45:29 -05003032#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003033 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
3034 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02003035 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
3036 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05003037#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01003038 SSL_CTX_set_ecdh_auto(self->ctx, 1);
3039#else
3040 {
3041 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
3042 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3043 EC_KEY_free(key);
3044 }
3045#endif
3046#endif
3047
Antoine Pitroufc113ee2010-10-13 12:46:13 +00003048#define SID_CTX "Python"
3049 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
3050 sizeof(SID_CTX));
3051#undef SID_CTX
3052
Christian Heimes61d478c2018-01-27 15:51:38 +01003053 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003054#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01003055 /* Improve trust chain building when cross-signed intermediate
3056 certificates are present. See https://bugs.python.org/issue23476. */
3057 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003058#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01003059 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05003060
Antoine Pitrou152efa22010-05-16 18:19:27 +00003061 return (PyObject *)self;
3062}
3063
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003064static int
3065context_traverse(PySSLContext *self, visitproc visit, void *arg)
3066{
3067#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003068 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003069#endif
3070 return 0;
3071}
3072
3073static int
3074context_clear(PySSLContext *self)
3075{
3076#ifndef OPENSSL_NO_TLSEXT
Christian Heimes11a14932018-02-24 02:35:08 +01003077 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003078#endif
3079 return 0;
3080}
3081
Antoine Pitrou152efa22010-05-16 18:19:27 +00003082static void
3083context_dealloc(PySSLContext *self)
3084{
INADA Naokia6296d32017-08-24 14:55:17 +09003085 /* bpo-31095: UnTrack is needed before calling any callbacks */
3086 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003087 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003088 SSL_CTX_free(self->ctx);
Christian Heimes29eab552018-02-25 12:31:33 +01003089#if HAVE_NPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003090 PyMem_FREE(self->npn_protocols);
3091#endif
Christian Heimes29eab552018-02-25 12:31:33 +01003092#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003093 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003094#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003095 Py_TYPE(self)->tp_free(self);
3096}
3097
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003098/*[clinic input]
3099_ssl._SSLContext.set_ciphers
3100 cipherlist: str
3101 /
3102[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003103
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003104static PyObject *
3105_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3106/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3107{
3108 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003109 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003110 /* Clearing the error queue is necessary on some OpenSSL versions,
3111 otherwise the error will be reported again when another SSL call
3112 is done. */
3113 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003114 PyErr_SetString(PySSLErrorObject,
3115 "No cipher can be selected.");
3116 return NULL;
3117 }
3118 Py_RETURN_NONE;
3119}
3120
Christian Heimes25bfcd52016-09-06 00:04:45 +02003121#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3122/*[clinic input]
3123_ssl._SSLContext.get_ciphers
3124[clinic start generated code]*/
3125
3126static PyObject *
3127_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3128/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3129{
3130 SSL *ssl = NULL;
3131 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003132 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003133 int i=0;
3134 PyObject *result = NULL, *dct;
3135
3136 ssl = SSL_new(self->ctx);
3137 if (ssl == NULL) {
3138 _setSSLError(NULL, 0, __FILE__, __LINE__);
3139 goto exit;
3140 }
3141 sk = SSL_get_ciphers(ssl);
3142
3143 result = PyList_New(sk_SSL_CIPHER_num(sk));
3144 if (result == NULL) {
3145 goto exit;
3146 }
3147
3148 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3149 cipher = sk_SSL_CIPHER_value(sk, i);
3150 dct = cipher_to_dict(cipher);
3151 if (dct == NULL) {
3152 Py_CLEAR(result);
3153 goto exit;
3154 }
3155 PyList_SET_ITEM(result, i, dct);
3156 }
3157
3158 exit:
3159 if (ssl != NULL)
3160 SSL_free(ssl);
3161 return result;
3162
3163}
3164#endif
3165
3166
Christian Heimes29eab552018-02-25 12:31:33 +01003167#if HAVE_NPN || HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003168static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003169do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3170 const unsigned char *server_protocols, unsigned int server_protocols_len,
3171 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003172{
Benjamin Peterson88615022015-01-23 17:30:26 -05003173 int ret;
3174 if (client_protocols == NULL) {
3175 client_protocols = (unsigned char *)"";
3176 client_protocols_len = 0;
3177 }
3178 if (server_protocols == NULL) {
3179 server_protocols = (unsigned char *)"";
3180 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003181 }
3182
Benjamin Peterson88615022015-01-23 17:30:26 -05003183 ret = SSL_select_next_proto(out, outlen,
3184 server_protocols, server_protocols_len,
3185 client_protocols, client_protocols_len);
3186 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3187 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003188
3189 return SSL_TLSEXT_ERR_OK;
3190}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003191#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003192
Christian Heimes29eab552018-02-25 12:31:33 +01003193#if HAVE_NPN
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003194/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3195static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003196_advertiseNPN_cb(SSL *s,
3197 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003198 void *args)
3199{
3200 PySSLContext *ssl_ctx = (PySSLContext *) args;
3201
3202 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003203 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003204 *len = 0;
3205 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003206 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003207 *len = ssl_ctx->npn_protocols_len;
3208 }
3209
3210 return SSL_TLSEXT_ERR_OK;
3211}
3212/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3213static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003214_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003215 unsigned char **out, unsigned char *outlen,
3216 const unsigned char *server, unsigned int server_len,
3217 void *args)
3218{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003219 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003220 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003221 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003222}
3223#endif
3224
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003225/*[clinic input]
3226_ssl._SSLContext._set_npn_protocols
3227 protos: Py_buffer
3228 /
3229[clinic start generated code]*/
3230
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003231static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003232_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3233 Py_buffer *protos)
3234/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003235{
Christian Heimes29eab552018-02-25 12:31:33 +01003236#if HAVE_NPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003237 PyMem_Free(self->npn_protocols);
3238 self->npn_protocols = PyMem_Malloc(protos->len);
3239 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003240 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003241 memcpy(self->npn_protocols, protos->buf, protos->len);
3242 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003243
3244 /* set both server and client callbacks, because the context can
3245 * be used to create both types of sockets */
3246 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3247 _advertiseNPN_cb,
3248 self);
3249 SSL_CTX_set_next_proto_select_cb(self->ctx,
3250 _selectNPN_cb,
3251 self);
3252
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003253 Py_RETURN_NONE;
3254#else
3255 PyErr_SetString(PyExc_NotImplementedError,
3256 "The NPN extension requires OpenSSL 1.0.1 or later.");
3257 return NULL;
3258#endif
3259}
3260
Christian Heimes29eab552018-02-25 12:31:33 +01003261#if HAVE_ALPN
Benjamin Petersoncca27322015-01-23 16:35:37 -05003262static int
3263_selectALPN_cb(SSL *s,
3264 const unsigned char **out, unsigned char *outlen,
3265 const unsigned char *client_protocols, unsigned int client_protocols_len,
3266 void *args)
3267{
3268 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003269 return do_protocol_selection(1, (unsigned char **)out, outlen,
3270 ctx->alpn_protocols, ctx->alpn_protocols_len,
3271 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003272}
3273#endif
3274
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003275/*[clinic input]
3276_ssl._SSLContext._set_alpn_protocols
3277 protos: Py_buffer
3278 /
3279[clinic start generated code]*/
3280
Benjamin Petersoncca27322015-01-23 16:35:37 -05003281static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003282_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3283 Py_buffer *protos)
3284/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003285{
Christian Heimes29eab552018-02-25 12:31:33 +01003286#if HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003287 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003288 PyErr_Format(PyExc_OverflowError,
3289 "protocols longer than %d bytes", UINT_MAX);
3290 return NULL;
3291 }
3292
Benjamin Petersoncca27322015-01-23 16:35:37 -05003293 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003294 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003295 if (!self->alpn_protocols)
3296 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003297 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003298 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003299
3300 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3301 return PyErr_NoMemory();
3302 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3303
Benjamin Petersoncca27322015-01-23 16:35:37 -05003304 Py_RETURN_NONE;
3305#else
3306 PyErr_SetString(PyExc_NotImplementedError,
3307 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3308 return NULL;
3309#endif
3310}
3311
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312static PyObject *
3313get_verify_mode(PySSLContext *self, void *c)
3314{
3315 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3316 case SSL_VERIFY_NONE:
3317 return PyLong_FromLong(PY_SSL_CERT_NONE);
3318 case SSL_VERIFY_PEER:
3319 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3320 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3321 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3322 }
3323 PyErr_SetString(PySSLErrorObject,
3324 "invalid return value from SSL_CTX_get_verify_mode");
3325 return NULL;
3326}
3327
3328static int
3329set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3330{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003331 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003332 if (!PyArg_Parse(arg, "i", &n))
3333 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003334 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003335 PyErr_SetString(PyExc_ValueError,
3336 "Cannot set verify_mode to CERT_NONE when "
3337 "check_hostname is enabled.");
3338 return -1;
3339 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003340 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003341}
3342
3343static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003344get_verify_flags(PySSLContext *self, void *c)
3345{
Christian Heimes598894f2016-09-05 23:19:05 +02003346 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003347 unsigned long flags;
3348
Christian Heimes61d478c2018-01-27 15:51:38 +01003349 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003350 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003351 return PyLong_FromUnsignedLong(flags);
3352}
3353
3354static int
3355set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3356{
Christian Heimes598894f2016-09-05 23:19:05 +02003357 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003358 unsigned long new_flags, flags, set, clear;
3359
3360 if (!PyArg_Parse(arg, "k", &new_flags))
3361 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003362 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003363 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003364 clear = flags & ~new_flags;
3365 set = ~flags & new_flags;
3366 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003367 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003368 _setSSLError(NULL, 0, __FILE__, __LINE__);
3369 return -1;
3370 }
3371 }
3372 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003373 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003374 _setSSLError(NULL, 0, __FILE__, __LINE__);
3375 return -1;
3376 }
3377 }
3378 return 0;
3379}
3380
Christian Heimes698dde12018-02-27 11:54:43 +01003381/* Getter and setter for protocol version */
3382#if defined(SSL_CTRL_GET_MAX_PROTO_VERSION)
3383
3384
3385static int
3386set_min_max_proto_version(PySSLContext *self, PyObject *arg, int what)
3387{
3388 long v;
3389 int result;
3390
3391 if (!PyArg_Parse(arg, "l", &v))
3392 return -1;
3393 if (v > INT_MAX) {
3394 PyErr_SetString(PyExc_OverflowError, "Option is too long");
3395 return -1;
3396 }
3397
3398 switch(self->protocol) {
3399 case PY_SSL_VERSION_TLS_CLIENT: /* fall through */
3400 case PY_SSL_VERSION_TLS_SERVER: /* fall through */
3401 case PY_SSL_VERSION_TLS:
3402 break;
3403 default:
3404 PyErr_SetString(
3405 PyExc_ValueError,
3406 "The context's protocol doesn't support modification of "
3407 "highest and lowest version."
3408 );
3409 return -1;
3410 }
3411
3412 if (what == 0) {
3413 switch(v) {
3414 case PY_PROTO_MINIMUM_SUPPORTED:
3415 v = 0;
3416 break;
3417 case PY_PROTO_MAXIMUM_SUPPORTED:
3418 /* Emulate max for set_min_proto_version */
3419 v = PY_PROTO_MAXIMUM_AVAILABLE;
3420 break;
3421 default:
3422 break;
3423 }
3424 result = SSL_CTX_set_min_proto_version(self->ctx, v);
3425 }
3426 else {
3427 switch(v) {
3428 case PY_PROTO_MAXIMUM_SUPPORTED:
3429 v = 0;
3430 break;
3431 case PY_PROTO_MINIMUM_SUPPORTED:
3432 /* Emulate max for set_min_proto_version */
3433 v = PY_PROTO_MINIMUM_AVAILABLE;
3434 break;
3435 default:
3436 break;
3437 }
3438 result = SSL_CTX_set_max_proto_version(self->ctx, v);
3439 }
3440 if (result == 0) {
3441 PyErr_Format(PyExc_ValueError,
3442 "Unsupported protocol version 0x%x", v);
3443 return -1;
3444 }
3445 return 0;
3446}
3447
3448static PyObject *
3449get_minimum_version(PySSLContext *self, void *c)
3450{
3451 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MIN_PROTO_VERSION, 0, NULL);
3452 if (v == 0) {
3453 v = PY_PROTO_MINIMUM_SUPPORTED;
3454 }
3455 return PyLong_FromLong(v);
3456}
3457
3458static int
3459set_minimum_version(PySSLContext *self, PyObject *arg, void *c)
3460{
3461 return set_min_max_proto_version(self, arg, 0);
3462}
3463
3464static PyObject *
3465get_maximum_version(PySSLContext *self, void *c)
3466{
3467 int v = SSL_CTX_ctrl(self->ctx, SSL_CTRL_GET_MAX_PROTO_VERSION, 0, NULL);
3468 if (v == 0) {
3469 v = PY_PROTO_MAXIMUM_SUPPORTED;
3470 }
3471 return PyLong_FromLong(v);
3472}
3473
3474static int
3475set_maximum_version(PySSLContext *self, PyObject *arg, void *c)
3476{
3477 return set_min_max_proto_version(self, arg, 1);
3478}
3479#endif /* SSL_CTRL_GET_MAX_PROTO_VERSION */
3480
Christian Heimes22587792013-11-21 23:56:13 +01003481static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003482get_options(PySSLContext *self, void *c)
3483{
3484 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3485}
3486
3487static int
3488set_options(PySSLContext *self, PyObject *arg, void *c)
3489{
3490 long new_opts, opts, set, clear;
3491 if (!PyArg_Parse(arg, "l", &new_opts))
3492 return -1;
3493 opts = SSL_CTX_get_options(self->ctx);
3494 clear = opts & ~new_opts;
3495 set = ~opts & new_opts;
3496 if (clear) {
3497#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3498 SSL_CTX_clear_options(self->ctx, clear);
3499#else
3500 PyErr_SetString(PyExc_ValueError,
3501 "can't clear options before OpenSSL 0.9.8m");
3502 return -1;
3503#endif
3504 }
3505 if (set)
3506 SSL_CTX_set_options(self->ctx, set);
3507 return 0;
3508}
3509
Christian Heimes1aa9a752013-12-02 02:41:19 +01003510static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003511get_host_flags(PySSLContext *self, void *c)
3512{
3513 return PyLong_FromUnsignedLong(self->hostflags);
3514}
3515
3516static int
3517set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3518{
3519 X509_VERIFY_PARAM *param;
3520 unsigned int new_flags = 0;
3521
3522 if (!PyArg_Parse(arg, "I", &new_flags))
3523 return -1;
3524
3525 param = SSL_CTX_get0_param(self->ctx);
3526 self->hostflags = new_flags;
3527 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3528 return 0;
3529}
3530
3531static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003532get_check_hostname(PySSLContext *self, void *c)
3533{
3534 return PyBool_FromLong(self->check_hostname);
3535}
3536
3537static int
3538set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3539{
3540 int check_hostname;
3541 if (!PyArg_Parse(arg, "p", &check_hostname))
3542 return -1;
3543 if (check_hostname &&
3544 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003545 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3546 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3547 return -1;
3548 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003549 }
3550 self->check_hostname = check_hostname;
3551 return 0;
3552}
3553
Christian Heimes11a14932018-02-24 02:35:08 +01003554static PyObject *
3555get_protocol(PySSLContext *self, void *c) {
3556 return PyLong_FromLong(self->protocol);
3557}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003558
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003559typedef struct {
3560 PyThreadState *thread_state;
3561 PyObject *callable;
3562 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003563 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003564 int error;
3565} _PySSLPasswordInfo;
3566
3567static int
3568_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3569 const char *bad_type_error)
3570{
3571 /* Set the password and size fields of a _PySSLPasswordInfo struct
3572 from a unicode, bytes, or byte array object.
3573 The password field will be dynamically allocated and must be freed
3574 by the caller */
3575 PyObject *password_bytes = NULL;
3576 const char *data = NULL;
3577 Py_ssize_t size;
3578
3579 if (PyUnicode_Check(password)) {
3580 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3581 if (!password_bytes) {
3582 goto error;
3583 }
3584 data = PyBytes_AS_STRING(password_bytes);
3585 size = PyBytes_GET_SIZE(password_bytes);
3586 } else if (PyBytes_Check(password)) {
3587 data = PyBytes_AS_STRING(password);
3588 size = PyBytes_GET_SIZE(password);
3589 } else if (PyByteArray_Check(password)) {
3590 data = PyByteArray_AS_STRING(password);
3591 size = PyByteArray_GET_SIZE(password);
3592 } else {
3593 PyErr_SetString(PyExc_TypeError, bad_type_error);
3594 goto error;
3595 }
3596
Victor Stinner9ee02032013-06-23 15:08:23 +02003597 if (size > (Py_ssize_t)INT_MAX) {
3598 PyErr_Format(PyExc_ValueError,
3599 "password cannot be longer than %d bytes", INT_MAX);
3600 goto error;
3601 }
3602
Victor Stinner11ebff22013-07-07 17:07:52 +02003603 PyMem_Free(pw_info->password);
3604 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003605 if (!pw_info->password) {
3606 PyErr_SetString(PyExc_MemoryError,
3607 "unable to allocate password buffer");
3608 goto error;
3609 }
3610 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003611 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003612
3613 Py_XDECREF(password_bytes);
3614 return 1;
3615
3616error:
3617 Py_XDECREF(password_bytes);
3618 return 0;
3619}
3620
3621static int
3622_password_callback(char *buf, int size, int rwflag, void *userdata)
3623{
3624 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3625 PyObject *fn_ret = NULL;
3626
3627 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3628
3629 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003630 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003631 if (!fn_ret) {
3632 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3633 core python API, so we could use it to add a frame here */
3634 goto error;
3635 }
3636
3637 if (!_pwinfo_set(pw_info, fn_ret,
3638 "password callback must return a string")) {
3639 goto error;
3640 }
3641 Py_CLEAR(fn_ret);
3642 }
3643
3644 if (pw_info->size > size) {
3645 PyErr_Format(PyExc_ValueError,
3646 "password cannot be longer than %d bytes", size);
3647 goto error;
3648 }
3649
3650 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3651 memcpy(buf, pw_info->password, pw_info->size);
3652 return pw_info->size;
3653
3654error:
3655 Py_XDECREF(fn_ret);
3656 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3657 pw_info->error = 1;
3658 return -1;
3659}
3660
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003661/*[clinic input]
3662_ssl._SSLContext.load_cert_chain
3663 certfile: object
3664 keyfile: object = NULL
3665 password: object = NULL
3666
3667[clinic start generated code]*/
3668
Antoine Pitroub5218772010-05-21 09:56:06 +00003669static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003670_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3671 PyObject *keyfile, PyObject *password)
3672/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003673{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003674 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003675 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3676 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003677 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003678 int r;
3679
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003680 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003681 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003682 if (keyfile == Py_None)
3683 keyfile = NULL;
3684 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3685 PyErr_SetString(PyExc_TypeError,
3686 "certfile should be a valid filesystem path");
3687 return NULL;
3688 }
3689 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3690 PyErr_SetString(PyExc_TypeError,
3691 "keyfile should be a valid filesystem path");
3692 goto error;
3693 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003694 if (password && password != Py_None) {
3695 if (PyCallable_Check(password)) {
3696 pw_info.callable = password;
3697 } else if (!_pwinfo_set(&pw_info, password,
3698 "password should be a string or callable")) {
3699 goto error;
3700 }
3701 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3702 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3703 }
3704 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003705 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3706 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003707 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003709 if (pw_info.error) {
3710 ERR_clear_error();
3711 /* the password callback has already set the error information */
3712 }
3713 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003714 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003715 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003716 }
3717 else {
3718 _setSSLError(NULL, 0, __FILE__, __LINE__);
3719 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003720 goto error;
3721 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003722 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003723 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003724 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3725 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003726 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3727 Py_CLEAR(keyfile_bytes);
3728 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003729 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003730 if (pw_info.error) {
3731 ERR_clear_error();
3732 /* the password callback has already set the error information */
3733 }
3734 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003735 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003736 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003737 }
3738 else {
3739 _setSSLError(NULL, 0, __FILE__, __LINE__);
3740 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003741 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003742 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003743 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003744 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003745 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003746 if (r != 1) {
3747 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003748 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003749 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003750 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3751 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003752 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003753 Py_RETURN_NONE;
3754
3755error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003756 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3757 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003758 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003759 Py_XDECREF(keyfile_bytes);
3760 Py_XDECREF(certfile_bytes);
3761 return NULL;
3762}
3763
Christian Heimesefff7062013-11-21 03:35:02 +01003764/* internal helper function, returns -1 on error
3765 */
3766static int
3767_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3768 int filetype)
3769{
3770 BIO *biobuf = NULL;
3771 X509_STORE *store;
3772 int retval = 0, err, loaded = 0;
3773
3774 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3775
3776 if (len <= 0) {
3777 PyErr_SetString(PyExc_ValueError,
3778 "Empty certificate data");
3779 return -1;
3780 } else if (len > INT_MAX) {
3781 PyErr_SetString(PyExc_OverflowError,
3782 "Certificate data is too long.");
3783 return -1;
3784 }
3785
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003786 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003787 if (biobuf == NULL) {
3788 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3789 return -1;
3790 }
3791
3792 store = SSL_CTX_get_cert_store(self->ctx);
3793 assert(store != NULL);
3794
3795 while (1) {
3796 X509 *cert = NULL;
3797 int r;
3798
3799 if (filetype == SSL_FILETYPE_ASN1) {
3800 cert = d2i_X509_bio(biobuf, NULL);
3801 } else {
3802 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003803 SSL_CTX_get_default_passwd_cb(self->ctx),
3804 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3805 );
Christian Heimesefff7062013-11-21 03:35:02 +01003806 }
3807 if (cert == NULL) {
3808 break;
3809 }
3810 r = X509_STORE_add_cert(store, cert);
3811 X509_free(cert);
3812 if (!r) {
3813 err = ERR_peek_last_error();
3814 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3815 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3816 /* cert already in hash table, not an error */
3817 ERR_clear_error();
3818 } else {
3819 break;
3820 }
3821 }
3822 loaded++;
3823 }
3824
3825 err = ERR_peek_last_error();
3826 if ((filetype == SSL_FILETYPE_ASN1) &&
3827 (loaded > 0) &&
3828 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3829 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3830 /* EOF ASN1 file, not an error */
3831 ERR_clear_error();
3832 retval = 0;
3833 } else if ((filetype == SSL_FILETYPE_PEM) &&
3834 (loaded > 0) &&
3835 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3836 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3837 /* EOF PEM file, not an error */
3838 ERR_clear_error();
3839 retval = 0;
3840 } else {
3841 _setSSLError(NULL, 0, __FILE__, __LINE__);
3842 retval = -1;
3843 }
3844
3845 BIO_free(biobuf);
3846 return retval;
3847}
3848
3849
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003850/*[clinic input]
3851_ssl._SSLContext.load_verify_locations
3852 cafile: object = NULL
3853 capath: object = NULL
3854 cadata: object = NULL
3855
3856[clinic start generated code]*/
3857
Antoine Pitrou152efa22010-05-16 18:19:27 +00003858static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003859_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3860 PyObject *cafile,
3861 PyObject *capath,
3862 PyObject *cadata)
3863/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003864{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003865 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3866 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003867 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003868
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003869 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003870 if (cafile == Py_None)
3871 cafile = NULL;
3872 if (capath == Py_None)
3873 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003874 if (cadata == Py_None)
3875 cadata = NULL;
3876
3877 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003878 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003879 "cafile, capath and cadata cannot be all omitted");
3880 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003881 }
3882 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3883 PyErr_SetString(PyExc_TypeError,
3884 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003885 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003886 }
3887 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003888 PyErr_SetString(PyExc_TypeError,
3889 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003890 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003891 }
Christian Heimesefff7062013-11-21 03:35:02 +01003892
3893 /* validata cadata type and load cadata */
3894 if (cadata) {
3895 Py_buffer buf;
3896 PyObject *cadata_ascii = NULL;
3897
3898 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3899 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3900 PyBuffer_Release(&buf);
3901 PyErr_SetString(PyExc_TypeError,
3902 "cadata should be a contiguous buffer with "
3903 "a single dimension");
3904 goto error;
3905 }
3906 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3907 PyBuffer_Release(&buf);
3908 if (r == -1) {
3909 goto error;
3910 }
3911 } else {
3912 PyErr_Clear();
3913 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3914 if (cadata_ascii == NULL) {
3915 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003916 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003917 "bytes-like object");
3918 goto error;
3919 }
3920 r = _add_ca_certs(self,
3921 PyBytes_AS_STRING(cadata_ascii),
3922 PyBytes_GET_SIZE(cadata_ascii),
3923 SSL_FILETYPE_PEM);
3924 Py_DECREF(cadata_ascii);
3925 if (r == -1) {
3926 goto error;
3927 }
3928 }
3929 }
3930
3931 /* load cafile or capath */
3932 if (cafile || capath) {
3933 if (cafile)
3934 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3935 if (capath)
3936 capath_buf = PyBytes_AS_STRING(capath_bytes);
3937 PySSL_BEGIN_ALLOW_THREADS
3938 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3939 PySSL_END_ALLOW_THREADS
3940 if (r != 1) {
3941 ok = 0;
3942 if (errno != 0) {
3943 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003944 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003945 }
3946 else {
3947 _setSSLError(NULL, 0, __FILE__, __LINE__);
3948 }
3949 goto error;
3950 }
3951 }
3952 goto end;
3953
3954 error:
3955 ok = 0;
3956 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003957 Py_XDECREF(cafile_bytes);
3958 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003959 if (ok) {
3960 Py_RETURN_NONE;
3961 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003962 return NULL;
3963 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003964}
3965
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003966/*[clinic input]
3967_ssl._SSLContext.load_dh_params
3968 path as filepath: object
3969 /
3970
3971[clinic start generated code]*/
3972
Antoine Pitrou152efa22010-05-16 18:19:27 +00003973static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003974_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3975/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003976{
3977 FILE *f;
3978 DH *dh;
3979
Victor Stinnerdaf45552013-08-28 00:53:59 +02003980 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003981 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003982 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003983
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003984 errno = 0;
3985 PySSL_BEGIN_ALLOW_THREADS
3986 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003987 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003988 PySSL_END_ALLOW_THREADS
3989 if (dh == NULL) {
3990 if (errno != 0) {
3991 ERR_clear_error();
3992 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3993 }
3994 else {
3995 _setSSLError(NULL, 0, __FILE__, __LINE__);
3996 }
3997 return NULL;
3998 }
3999 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
4000 _setSSLError(NULL, 0, __FILE__, __LINE__);
4001 DH_free(dh);
4002 Py_RETURN_NONE;
4003}
4004
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004005/*[clinic input]
4006_ssl._SSLContext._wrap_socket
4007 sock: object(subclass_of="PySocketModule.Sock_Type")
4008 server_side: int
4009 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004010 *
4011 owner: object = None
4012 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004013
4014[clinic start generated code]*/
4015
Antoine Pitrou0e576f12011-12-22 10:03:38 +01004016static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004017_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Christian Heimes141c5e82018-02-24 21:10:57 +01004018 int server_side, PyObject *hostname_obj,
4019 PyObject *owner, PyObject *session)
4020/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021{
Antoine Pitroud5323212010-10-22 18:19:07 +00004022 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004023 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004024
Antoine Pitroud5323212010-10-22 18:19:07 +00004025 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004026 as IDN A-label (ASCII str) without NULL bytes. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004027 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004028 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00004029 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00004030 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00004031
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004032 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
4033 server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004034 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004035 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00004036 if (hostname != NULL)
4037 PyMem_Free(hostname);
4038 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00004039}
4040
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004041/*[clinic input]
4042_ssl._SSLContext._wrap_bio
4043 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4044 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
4045 server_side: int
4046 server_hostname as hostname_obj: object = None
Christian Heimes141c5e82018-02-24 21:10:57 +01004047 *
4048 owner: object = None
4049 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004050
4051[clinic start generated code]*/
4052
Antoine Pitroub0182c82010-10-12 20:09:02 +00004053static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004054_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
4055 PySSLMemoryBIO *outgoing, int server_side,
Christian Heimes141c5e82018-02-24 21:10:57 +01004056 PyObject *hostname_obj, PyObject *owner,
4057 PyObject *session)
4058/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004059{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004060 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004061 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004062
4063 /* server_hostname is either None (or absent), or to be encoded
Christian Heimesd02ac252018-03-25 12:36:13 +02004064 as IDN A-label (ASCII str) without NULL bytes. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004065 if (hostname_obj != Py_None) {
Christian Heimes11a14932018-02-24 02:35:08 +01004066 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004067 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004068 }
4069
4070 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Christian Heimes141c5e82018-02-24 21:10:57 +01004071 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004072 incoming, outgoing);
4073
4074 PyMem_Free(hostname);
4075 return res;
4076}
4077
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004078/*[clinic input]
4079_ssl._SSLContext.session_stats
4080[clinic start generated code]*/
4081
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004082static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004083_ssl__SSLContext_session_stats_impl(PySSLContext *self)
4084/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00004085{
4086 int r;
4087 PyObject *value, *stats = PyDict_New();
4088 if (!stats)
4089 return NULL;
4090
4091#define ADD_STATS(SSL_NAME, KEY_NAME) \
4092 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
4093 if (value == NULL) \
4094 goto error; \
4095 r = PyDict_SetItemString(stats, KEY_NAME, value); \
4096 Py_DECREF(value); \
4097 if (r < 0) \
4098 goto error;
4099
4100 ADD_STATS(number, "number");
4101 ADD_STATS(connect, "connect");
4102 ADD_STATS(connect_good, "connect_good");
4103 ADD_STATS(connect_renegotiate, "connect_renegotiate");
4104 ADD_STATS(accept, "accept");
4105 ADD_STATS(accept_good, "accept_good");
4106 ADD_STATS(accept_renegotiate, "accept_renegotiate");
4107 ADD_STATS(accept, "accept");
4108 ADD_STATS(hits, "hits");
4109 ADD_STATS(misses, "misses");
4110 ADD_STATS(timeouts, "timeouts");
4111 ADD_STATS(cache_full, "cache_full");
4112
4113#undef ADD_STATS
4114
4115 return stats;
4116
4117error:
4118 Py_DECREF(stats);
4119 return NULL;
4120}
4121
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004122/*[clinic input]
4123_ssl._SSLContext.set_default_verify_paths
4124[clinic start generated code]*/
4125
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004126static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004127_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
4128/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00004129{
4130 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
4131 _setSSLError(NULL, 0, __FILE__, __LINE__);
4132 return NULL;
4133 }
4134 Py_RETURN_NONE;
4135}
4136
Antoine Pitrou501da612011-12-21 09:27:41 +01004137#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138/*[clinic input]
4139_ssl._SSLContext.set_ecdh_curve
4140 name: object
4141 /
4142
4143[clinic start generated code]*/
4144
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004145static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004146_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
4147/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004148{
4149 PyObject *name_bytes;
4150 int nid;
4151 EC_KEY *key;
4152
4153 if (!PyUnicode_FSConverter(name, &name_bytes))
4154 return NULL;
4155 assert(PyBytes_Check(name_bytes));
4156 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
4157 Py_DECREF(name_bytes);
4158 if (nid == 0) {
4159 PyErr_Format(PyExc_ValueError,
4160 "unknown elliptic curve name %R", name);
4161 return NULL;
4162 }
4163 key = EC_KEY_new_by_curve_name(nid);
4164 if (key == NULL) {
4165 _setSSLError(NULL, 0, __FILE__, __LINE__);
4166 return NULL;
4167 }
4168 SSL_CTX_set_tmp_ecdh(self->ctx, key);
4169 EC_KEY_free(key);
4170 Py_RETURN_NONE;
4171}
Antoine Pitrou501da612011-12-21 09:27:41 +01004172#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004173
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004174#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004175static int
4176_servername_callback(SSL *s, int *al, void *args)
4177{
4178 int ret;
4179 PySSLContext *ssl_ctx = (PySSLContext *) args;
4180 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004181 PyObject *result;
4182 /* The high-level ssl.SSLSocket object */
4183 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004184 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004185 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004186
Christian Heimes11a14932018-02-24 02:35:08 +01004187 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004188 /* remove race condition in this the call back while if removing the
4189 * callback is in progress */
4190 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004191 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004192 }
4193
4194 ssl = SSL_get_app_data(s);
4195 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004196
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004197 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198 * SSL connection and that has a .context attribute that can be changed to
4199 * identify the requested hostname. Since the official API is the Python
4200 * level API we want to pass the callback a Python level object rather than
4201 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4202 * SSLObject) that will be passed. Otherwise if there's a socket then that
4203 * will be passed. If both do not exist only then the C-level object is
4204 * passed. */
4205 if (ssl->owner)
4206 ssl_socket = PyWeakref_GetObject(ssl->owner);
4207 else if (ssl->Socket)
4208 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4209 else
4210 ssl_socket = (PyObject *) ssl;
4211
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004212 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004214 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004215
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004216 if (servername == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004217 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004218 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004219 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004220 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004221 PyObject *servername_bytes;
4222 PyObject *servername_str;
4223
4224 servername_bytes = PyBytes_FromString(servername);
4225 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004226 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4227 goto error;
4228 }
Christian Heimes11a14932018-02-24 02:35:08 +01004229 /* server_hostname was encoded to an A-label by our caller; put it
4230 * back into a str object, but still as an A-label (bpo-28414)
4231 */
4232 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4233 Py_DECREF(servername_bytes);
4234 if (servername_str == NULL) {
4235 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004236 goto error;
4237 }
Christian Heimes11a14932018-02-24 02:35:08 +01004238 result = PyObject_CallFunctionObjArgs(
4239 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4240 ssl_ctx, NULL);
4241 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004242 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004243 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004244
4245 if (result == NULL) {
Christian Heimes11a14932018-02-24 02:35:08 +01004246 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004247 *al = SSL_AD_HANDSHAKE_FAILURE;
4248 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4249 }
4250 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004251 /* Result may be None, a SSLContext or an integer
4252 * None and SSLContext are OK, integer or other values are an error.
4253 */
4254 if (result == Py_None) {
4255 ret = SSL_TLSEXT_ERR_OK;
4256 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004257 *al = (int) PyLong_AsLong(result);
4258 if (PyErr_Occurred()) {
4259 PyErr_WriteUnraisable(result);
4260 *al = SSL_AD_INTERNAL_ERROR;
4261 }
4262 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4263 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004264 Py_DECREF(result);
4265 }
4266
4267 PyGILState_Release(gstate);
4268 return ret;
4269
4270error:
4271 Py_DECREF(ssl_socket);
4272 *al = SSL_AD_INTERNAL_ERROR;
4273 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4274 PyGILState_Release(gstate);
4275 return ret;
4276}
Antoine Pitroua5963382013-03-30 16:39:00 +01004277#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004278
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004279static PyObject *
Christian Heimes11a14932018-02-24 02:35:08 +01004280get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004281{
Christian Heimes11a14932018-02-24 02:35:08 +01004282 PyObject *cb = self->set_sni_cb;
4283 if (cb == NULL) {
4284 Py_RETURN_NONE;
4285 }
4286 Py_INCREF(cb);
4287 return cb;
4288}
4289
4290static int
4291set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4292{
4293 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4294 PyErr_SetString(PyExc_ValueError,
4295 "sni_callback cannot be set on TLS_CLIENT context");
4296 return -1;
4297 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004298#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Christian Heimes11a14932018-02-24 02:35:08 +01004299 Py_CLEAR(self->set_sni_cb);
4300 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004301 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4302 }
4303 else {
Christian Heimes11a14932018-02-24 02:35:08 +01004304 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004305 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4306 PyErr_SetString(PyExc_TypeError,
4307 "not a callable object");
Christian Heimes11a14932018-02-24 02:35:08 +01004308 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004309 }
Christian Heimes11a14932018-02-24 02:35:08 +01004310 Py_INCREF(arg);
4311 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004312 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4313 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4314 }
Christian Heimes11a14932018-02-24 02:35:08 +01004315 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004316#else
4317 PyErr_SetString(PyExc_NotImplementedError,
4318 "The TLS extension servername callback, "
4319 "SSL_CTX_set_tlsext_servername_callback, "
4320 "is not in the current OpenSSL library.");
Christian Heimes11a14932018-02-24 02:35:08 +01004321 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004322#endif
4323}
4324
Christian Heimes11a14932018-02-24 02:35:08 +01004325PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4326"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4327\n\
4328If the argument is None then the callback is disabled. The method is called\n\
4329with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4330See RFC 6066 for details of the SNI extension.");
4331
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004332/*[clinic input]
4333_ssl._SSLContext.cert_store_stats
4334
4335Returns quantities of loaded X.509 certificates.
4336
4337X.509 certificates with a CA extension and certificate revocation lists
4338inside the context's cert store.
4339
4340NOTE: Certificates in a capath directory aren't loaded unless they have
4341been used at least once.
4342[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004343
4344static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004345_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4346/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004347{
4348 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004349 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004350 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004351 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004352
4353 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004354 objs = X509_STORE_get0_objects(store);
4355 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4356 obj = sk_X509_OBJECT_value(objs, i);
4357 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004358 case X509_LU_X509:
4359 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004360 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004361 ca++;
4362 }
4363 break;
4364 case X509_LU_CRL:
4365 crl++;
4366 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004367 default:
4368 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4369 * As far as I can tell they are internal states and never
4370 * stored in a cert store */
4371 break;
4372 }
4373 }
4374 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4375 "x509_ca", ca);
4376}
4377
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004378/*[clinic input]
4379_ssl._SSLContext.get_ca_certs
4380 binary_form: bool = False
4381
4382Returns a list of dicts with information of loaded CA certs.
4383
4384If the optional argument is True, returns a DER-encoded copy of the CA
4385certificate.
4386
4387NOTE: Certificates in a capath directory aren't loaded unless they have
4388been used at least once.
4389[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004390
4391static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004392_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4393/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004394{
4395 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004396 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004397 PyObject *ci = NULL, *rlist = NULL;
4398 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004399
4400 if ((rlist = PyList_New(0)) == NULL) {
4401 return NULL;
4402 }
4403
4404 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004405 objs = X509_STORE_get0_objects(store);
4406 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004407 X509_OBJECT *obj;
4408 X509 *cert;
4409
Christian Heimes598894f2016-09-05 23:19:05 +02004410 obj = sk_X509_OBJECT_value(objs, i);
4411 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004412 /* not a x509 cert */
4413 continue;
4414 }
4415 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004416 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004417 if (!X509_check_ca(cert)) {
4418 continue;
4419 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004420 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004421 ci = _certificate_to_der(cert);
4422 } else {
4423 ci = _decode_certificate(cert);
4424 }
4425 if (ci == NULL) {
4426 goto error;
4427 }
4428 if (PyList_Append(rlist, ci) == -1) {
4429 goto error;
4430 }
4431 Py_CLEAR(ci);
4432 }
4433 return rlist;
4434
4435 error:
4436 Py_XDECREF(ci);
4437 Py_XDECREF(rlist);
4438 return NULL;
4439}
4440
4441
Antoine Pitrou152efa22010-05-16 18:19:27 +00004442static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004443 {"check_hostname", (getter) get_check_hostname,
4444 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004445 {"_host_flags", (getter) get_host_flags,
4446 (setter) set_host_flags, NULL},
Christian Heimes698dde12018-02-27 11:54:43 +01004447#if SSL_CTRL_GET_MAX_PROTO_VERSION
4448 {"minimum_version", (getter) get_minimum_version,
4449 (setter) set_minimum_version, NULL},
4450 {"maximum_version", (getter) get_maximum_version,
4451 (setter) set_maximum_version, NULL},
4452#endif
Christian Heimes11a14932018-02-24 02:35:08 +01004453 {"sni_callback", (getter) get_sni_callback,
Christian Heimes698dde12018-02-27 11:54:43 +01004454 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004455 {"options", (getter) get_options,
4456 (setter) set_options, NULL},
Christian Heimes11a14932018-02-24 02:35:08 +01004457 {"protocol", (getter) get_protocol,
4458 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004459 {"verify_flags", (getter) get_verify_flags,
4460 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004461 {"verify_mode", (getter) get_verify_mode,
4462 (setter) set_verify_mode, NULL},
4463 {NULL}, /* sentinel */
4464};
4465
4466static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004467 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4468 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4469 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4470 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4471 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4472 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4473 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4474 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4475 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4476 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4477 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004478 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4479 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004480 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004481 {NULL, NULL} /* sentinel */
4482};
4483
4484static PyTypeObject PySSLContext_Type = {
4485 PyVarObject_HEAD_INIT(NULL, 0)
4486 "_ssl._SSLContext", /*tp_name*/
4487 sizeof(PySSLContext), /*tp_basicsize*/
4488 0, /*tp_itemsize*/
4489 (destructor)context_dealloc, /*tp_dealloc*/
4490 0, /*tp_print*/
4491 0, /*tp_getattr*/
4492 0, /*tp_setattr*/
4493 0, /*tp_reserved*/
4494 0, /*tp_repr*/
4495 0, /*tp_as_number*/
4496 0, /*tp_as_sequence*/
4497 0, /*tp_as_mapping*/
4498 0, /*tp_hash*/
4499 0, /*tp_call*/
4500 0, /*tp_str*/
4501 0, /*tp_getattro*/
4502 0, /*tp_setattro*/
4503 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004504 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004505 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004506 (traverseproc) context_traverse, /*tp_traverse*/
4507 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004508 0, /*tp_richcompare*/
4509 0, /*tp_weaklistoffset*/
4510 0, /*tp_iter*/
4511 0, /*tp_iternext*/
4512 context_methods, /*tp_methods*/
4513 0, /*tp_members*/
4514 context_getsetlist, /*tp_getset*/
4515 0, /*tp_base*/
4516 0, /*tp_dict*/
4517 0, /*tp_descr_get*/
4518 0, /*tp_descr_set*/
4519 0, /*tp_dictoffset*/
4520 0, /*tp_init*/
4521 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004522 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004523};
4524
4525
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004526/*
4527 * MemoryBIO objects
4528 */
4529
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004530/*[clinic input]
4531@classmethod
4532_ssl.MemoryBIO.__new__
4533
4534[clinic start generated code]*/
4535
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004536static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004537_ssl_MemoryBIO_impl(PyTypeObject *type)
4538/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004539{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004540 BIO *bio;
4541 PySSLMemoryBIO *self;
4542
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004543 bio = BIO_new(BIO_s_mem());
4544 if (bio == NULL) {
4545 PyErr_SetString(PySSLErrorObject,
4546 "failed to allocate BIO");
4547 return NULL;
4548 }
4549 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4550 * just that no data is currently available. The SSL routines should retry
4551 * the read, which we can achieve by calling BIO_set_retry_read(). */
4552 BIO_set_retry_read(bio);
4553 BIO_set_mem_eof_return(bio, -1);
4554
4555 assert(type != NULL && type->tp_alloc != NULL);
4556 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4557 if (self == NULL) {
4558 BIO_free(bio);
4559 return NULL;
4560 }
4561 self->bio = bio;
4562 self->eof_written = 0;
4563
4564 return (PyObject *) self;
4565}
4566
4567static void
4568memory_bio_dealloc(PySSLMemoryBIO *self)
4569{
4570 BIO_free(self->bio);
4571 Py_TYPE(self)->tp_free(self);
4572}
4573
4574static PyObject *
4575memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4576{
Segev Finer5cff6372017-07-27 01:19:17 +03004577 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004578}
4579
4580PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4581"The number of bytes pending in the memory BIO.");
4582
4583static PyObject *
4584memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4585{
4586 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4587 && self->eof_written);
4588}
4589
4590PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4591"Whether the memory BIO is at EOF.");
4592
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004593/*[clinic input]
4594_ssl.MemoryBIO.read
4595 size as len: int = -1
4596 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004597
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004598Read up to size bytes from the memory BIO.
4599
4600If size is not specified, read the entire buffer.
4601If the return value is an empty bytes instance, this means either
4602EOF or that no data is available. Use the "eof" property to
4603distinguish between the two.
4604[clinic start generated code]*/
4605
4606static PyObject *
4607_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4608/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4609{
4610 int avail, nbytes;
4611 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004612
Segev Finer5cff6372017-07-27 01:19:17 +03004613 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004614 if ((len < 0) || (len > avail))
4615 len = avail;
4616
4617 result = PyBytes_FromStringAndSize(NULL, len);
4618 if ((result == NULL) || (len == 0))
4619 return result;
4620
4621 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4622 /* There should never be any short reads but check anyway. */
4623 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4624 Py_DECREF(result);
4625 return NULL;
4626 }
4627
4628 return result;
4629}
4630
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004631/*[clinic input]
4632_ssl.MemoryBIO.write
4633 b: Py_buffer
4634 /
4635
4636Writes the bytes b into the memory BIO.
4637
4638Returns the number of bytes written.
4639[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004640
4641static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004642_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4643/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004644{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004645 int nbytes;
4646
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004647 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004648 PyErr_Format(PyExc_OverflowError,
4649 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004650 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004651 }
4652
4653 if (self->eof_written) {
4654 PyErr_SetString(PySSLErrorObject,
4655 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004656 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004657 }
4658
Segev Finer5cff6372017-07-27 01:19:17 +03004659 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004660 if (nbytes < 0) {
4661 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004662 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004663 }
4664
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004665 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004666}
4667
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004668/*[clinic input]
4669_ssl.MemoryBIO.write_eof
4670
4671Write an EOF marker to the memory BIO.
4672
4673When all data has been read, the "eof" property will be True.
4674[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004675
4676static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004677_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4678/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004679{
4680 self->eof_written = 1;
4681 /* After an EOF is written, a zero return from read() should be a real EOF
4682 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4683 BIO_clear_retry_flags(self->bio);
4684 BIO_set_mem_eof_return(self->bio, 0);
4685
4686 Py_RETURN_NONE;
4687}
4688
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004689static PyGetSetDef memory_bio_getsetlist[] = {
4690 {"pending", (getter) memory_bio_get_pending, NULL,
4691 PySSL_memory_bio_pending_doc},
4692 {"eof", (getter) memory_bio_get_eof, NULL,
4693 PySSL_memory_bio_eof_doc},
4694 {NULL}, /* sentinel */
4695};
4696
4697static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004698 _SSL_MEMORYBIO_READ_METHODDEF
4699 _SSL_MEMORYBIO_WRITE_METHODDEF
4700 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004701 {NULL, NULL} /* sentinel */
4702};
4703
4704static PyTypeObject PySSLMemoryBIO_Type = {
4705 PyVarObject_HEAD_INIT(NULL, 0)
4706 "_ssl.MemoryBIO", /*tp_name*/
4707 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4708 0, /*tp_itemsize*/
4709 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4710 0, /*tp_print*/
4711 0, /*tp_getattr*/
4712 0, /*tp_setattr*/
4713 0, /*tp_reserved*/
4714 0, /*tp_repr*/
4715 0, /*tp_as_number*/
4716 0, /*tp_as_sequence*/
4717 0, /*tp_as_mapping*/
4718 0, /*tp_hash*/
4719 0, /*tp_call*/
4720 0, /*tp_str*/
4721 0, /*tp_getattro*/
4722 0, /*tp_setattro*/
4723 0, /*tp_as_buffer*/
4724 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4725 0, /*tp_doc*/
4726 0, /*tp_traverse*/
4727 0, /*tp_clear*/
4728 0, /*tp_richcompare*/
4729 0, /*tp_weaklistoffset*/
4730 0, /*tp_iter*/
4731 0, /*tp_iternext*/
4732 memory_bio_methods, /*tp_methods*/
4733 0, /*tp_members*/
4734 memory_bio_getsetlist, /*tp_getset*/
4735 0, /*tp_base*/
4736 0, /*tp_dict*/
4737 0, /*tp_descr_get*/
4738 0, /*tp_descr_set*/
4739 0, /*tp_dictoffset*/
4740 0, /*tp_init*/
4741 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004742 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004743};
4744
Antoine Pitrou152efa22010-05-16 18:19:27 +00004745
Christian Heimes99a65702016-09-10 23:44:53 +02004746/*
4747 * SSL Session object
4748 */
4749
4750static void
4751PySSLSession_dealloc(PySSLSession *self)
4752{
INADA Naokia6296d32017-08-24 14:55:17 +09004753 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004754 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004755 Py_XDECREF(self->ctx);
4756 if (self->session != NULL) {
4757 SSL_SESSION_free(self->session);
4758 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004759 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004760}
4761
4762static PyObject *
4763PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4764{
4765 int result;
4766
4767 if (left == NULL || right == NULL) {
4768 PyErr_BadInternalCall();
4769 return NULL;
4770 }
4771
4772 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4773 Py_RETURN_NOTIMPLEMENTED;
4774 }
4775
4776 if (left == right) {
4777 result = 0;
4778 } else {
4779 const unsigned char *left_id, *right_id;
4780 unsigned int left_len, right_len;
4781 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4782 &left_len);
4783 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4784 &right_len);
4785 if (left_len == right_len) {
4786 result = memcmp(left_id, right_id, left_len);
4787 } else {
4788 result = 1;
4789 }
4790 }
4791
4792 switch (op) {
4793 case Py_EQ:
4794 if (result == 0) {
4795 Py_RETURN_TRUE;
4796 } else {
4797 Py_RETURN_FALSE;
4798 }
4799 break;
4800 case Py_NE:
4801 if (result != 0) {
4802 Py_RETURN_TRUE;
4803 } else {
4804 Py_RETURN_FALSE;
4805 }
4806 break;
4807 case Py_LT:
4808 case Py_LE:
4809 case Py_GT:
4810 case Py_GE:
4811 Py_RETURN_NOTIMPLEMENTED;
4812 break;
4813 default:
4814 PyErr_BadArgument();
4815 return NULL;
4816 }
4817}
4818
4819static int
4820PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4821{
4822 Py_VISIT(self->ctx);
4823 return 0;
4824}
4825
4826static int
4827PySSLSession_clear(PySSLSession *self)
4828{
4829 Py_CLEAR(self->ctx);
4830 return 0;
4831}
4832
4833
4834static PyObject *
4835PySSLSession_get_time(PySSLSession *self, void *closure) {
4836 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4837}
4838
4839PyDoc_STRVAR(PySSLSession_get_time_doc,
4840"Session creation time (seconds since epoch).");
4841
4842
4843static PyObject *
4844PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4845 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4846}
4847
4848PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4849"Session timeout (delta in seconds).");
4850
4851
4852static PyObject *
4853PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4854 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4855 return PyLong_FromUnsignedLong(hint);
4856}
4857
4858PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4859"Ticket life time hint.");
4860
4861
4862static PyObject *
4863PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4864 const unsigned char *id;
4865 unsigned int len;
4866 id = SSL_SESSION_get_id(self->session, &len);
4867 return PyBytes_FromStringAndSize((const char *)id, len);
4868}
4869
4870PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4871"Session id");
4872
4873
4874static PyObject *
4875PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4876 if (SSL_SESSION_has_ticket(self->session)) {
4877 Py_RETURN_TRUE;
4878 } else {
4879 Py_RETURN_FALSE;
4880 }
4881}
4882
4883PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4884"Does the session contain a ticket?");
4885
4886
4887static PyGetSetDef PySSLSession_getsetlist[] = {
4888 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4889 PySSLSession_get_has_ticket_doc},
4890 {"id", (getter) PySSLSession_get_session_id, NULL,
4891 PySSLSession_get_session_id_doc},
4892 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4893 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4894 {"time", (getter) PySSLSession_get_time, NULL,
4895 PySSLSession_get_time_doc},
4896 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4897 PySSLSession_get_timeout_doc},
4898 {NULL}, /* sentinel */
4899};
4900
4901static PyTypeObject PySSLSession_Type = {
4902 PyVarObject_HEAD_INIT(NULL, 0)
4903 "_ssl.Session", /*tp_name*/
4904 sizeof(PySSLSession), /*tp_basicsize*/
4905 0, /*tp_itemsize*/
4906 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4907 0, /*tp_print*/
4908 0, /*tp_getattr*/
4909 0, /*tp_setattr*/
4910 0, /*tp_reserved*/
4911 0, /*tp_repr*/
4912 0, /*tp_as_number*/
4913 0, /*tp_as_sequence*/
4914 0, /*tp_as_mapping*/
4915 0, /*tp_hash*/
4916 0, /*tp_call*/
4917 0, /*tp_str*/
4918 0, /*tp_getattro*/
4919 0, /*tp_setattro*/
4920 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004921 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004922 0, /*tp_doc*/
4923 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4924 (inquiry)PySSLSession_clear, /*tp_clear*/
4925 PySSLSession_richcompare, /*tp_richcompare*/
4926 0, /*tp_weaklistoffset*/
4927 0, /*tp_iter*/
4928 0, /*tp_iternext*/
4929 0, /*tp_methods*/
4930 0, /*tp_members*/
4931 PySSLSession_getsetlist, /*tp_getset*/
4932};
4933
4934
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004935/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004936/*[clinic input]
4937_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004938 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004939 entropy: double
4940 /
4941
4942Mix string into the OpenSSL PRNG state.
4943
4944entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304945string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004946[clinic start generated code]*/
4947
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004948static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004949_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004950/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004951{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004952 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004953 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004954
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004955 buf = (const char *)view->buf;
4956 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004957 do {
4958 written = Py_MIN(len, INT_MAX);
4959 RAND_add(buf, (int)written, entropy);
4960 buf += written;
4961 len -= written;
4962 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004963 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004964}
4965
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004966static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004967PySSL_RAND(int len, int pseudo)
4968{
4969 int ok;
4970 PyObject *bytes;
4971 unsigned long err;
4972 const char *errstr;
4973 PyObject *v;
4974
Victor Stinner1e81a392013-12-19 16:47:04 +01004975 if (len < 0) {
4976 PyErr_SetString(PyExc_ValueError, "num must be positive");
4977 return NULL;
4978 }
4979
Victor Stinner99c8b162011-05-24 12:05:19 +02004980 bytes = PyBytes_FromStringAndSize(NULL, len);
4981 if (bytes == NULL)
4982 return NULL;
4983 if (pseudo) {
4984 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4985 if (ok == 0 || ok == 1)
4986 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4987 }
4988 else {
4989 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4990 if (ok == 1)
4991 return bytes;
4992 }
4993 Py_DECREF(bytes);
4994
4995 err = ERR_get_error();
4996 errstr = ERR_reason_error_string(err);
4997 v = Py_BuildValue("(ks)", err, errstr);
4998 if (v != NULL) {
4999 PyErr_SetObject(PySSLErrorObject, v);
5000 Py_DECREF(v);
5001 }
5002 return NULL;
5003}
5004
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005005/*[clinic input]
5006_ssl.RAND_bytes
5007 n: int
5008 /
5009
5010Generate n cryptographically strong pseudo-random bytes.
5011[clinic start generated code]*/
5012
Victor Stinner99c8b162011-05-24 12:05:19 +02005013static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005014_ssl_RAND_bytes_impl(PyObject *module, int n)
5015/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005016{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005017 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02005018}
5019
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005020/*[clinic input]
5021_ssl.RAND_pseudo_bytes
5022 n: int
5023 /
5024
5025Generate n pseudo-random bytes.
5026
5027Return a pair (bytes, is_cryptographic). is_cryptographic is True
5028if the bytes generated are cryptographically strong.
5029[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005030
5031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005032_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
5033/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005034{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005035 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02005036}
5037
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005038/*[clinic input]
5039_ssl.RAND_status
5040
5041Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
5042
5043It is necessary to seed the PRNG with RAND_add() on some platforms before
5044using the ssl() function.
5045[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02005046
5047static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005048_ssl_RAND_status_impl(PyObject *module)
5049/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005050{
Christian Heimes217cfd12007-12-02 14:31:20 +00005051 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005052}
5053
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005054#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02005055/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005056/*[clinic input]
5057_ssl.RAND_egd
5058 path: object(converter="PyUnicode_FSConverter")
5059 /
5060
5061Queries the entropy gather daemon (EGD) on the socket named by 'path'.
5062
5063Returns number of bytes read. Raises SSLError if connection to EGD
5064fails or if it does not provide enough data to seed PRNG.
5065[clinic start generated code]*/
5066
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005067static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005068_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
5069/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005070{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005071 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00005072 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005073 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00005074 PyErr_SetString(PySSLErrorObject,
5075 "EGD connection failed or EGD did not return "
5076 "enough data to seed the PRNG");
5077 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005078 }
Christian Heimes217cfd12007-12-02 14:31:20 +00005079 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005080}
Christian Heimesa5d07652016-09-24 10:48:05 +02005081/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07005082#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005083
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005084
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005085
5086/*[clinic input]
5087_ssl.get_default_verify_paths
5088
5089Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
5090
5091The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
5092[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005093
5094static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005095_ssl_get_default_verify_paths_impl(PyObject *module)
5096/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02005097{
5098 PyObject *ofile_env = NULL;
5099 PyObject *ofile = NULL;
5100 PyObject *odir_env = NULL;
5101 PyObject *odir = NULL;
5102
Benjamin Petersond113c962015-07-18 10:59:13 -07005103#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02005104 const char *tmp = (info); \
5105 target = NULL; \
5106 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
5107 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
5108 target = PyBytes_FromString(tmp); } \
5109 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08005110 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02005111
Benjamin Petersond113c962015-07-18 10:59:13 -07005112 CONVERT(X509_get_default_cert_file_env(), ofile_env);
5113 CONVERT(X509_get_default_cert_file(), ofile);
5114 CONVERT(X509_get_default_cert_dir_env(), odir_env);
5115 CONVERT(X509_get_default_cert_dir(), odir);
5116#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02005117
Christian Heimes200bb1b2013-06-14 15:14:29 +02005118 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02005119
5120 error:
5121 Py_XDECREF(ofile_env);
5122 Py_XDECREF(ofile);
5123 Py_XDECREF(odir_env);
5124 Py_XDECREF(odir);
5125 return NULL;
5126}
5127
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005128static PyObject*
5129asn1obj2py(ASN1_OBJECT *obj)
5130{
5131 int nid;
5132 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005133
5134 nid = OBJ_obj2nid(obj);
5135 if (nid == NID_undef) {
5136 PyErr_Format(PyExc_ValueError, "Unknown object");
5137 return NULL;
5138 }
5139 sn = OBJ_nid2sn(nid);
5140 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03005141 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005142}
5143
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005144/*[clinic input]
5145_ssl.txt2obj
5146 txt: str
5147 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005148
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005149Lookup NID, short name, long name and OID of an ASN1_OBJECT.
5150
5151By default objects are looked up by OID. With name=True short and
5152long name are also matched.
5153[clinic start generated code]*/
5154
5155static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005156_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
5157/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005158{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005159 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005160 ASN1_OBJECT *obj;
5161
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005162 obj = OBJ_txt2obj(txt, name ? 0 : 1);
5163 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005164 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005165 return NULL;
5166 }
5167 result = asn1obj2py(obj);
5168 ASN1_OBJECT_free(obj);
5169 return result;
5170}
5171
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005172/*[clinic input]
5173_ssl.nid2obj
5174 nid: int
5175 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005176
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005177Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
5178[clinic start generated code]*/
5179
5180static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005181_ssl_nid2obj_impl(PyObject *module, int nid)
5182/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005183{
5184 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005185 ASN1_OBJECT *obj;
5186
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005187 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005188 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005189 return NULL;
5190 }
5191 obj = OBJ_nid2obj(nid);
5192 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005193 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005194 return NULL;
5195 }
5196 result = asn1obj2py(obj);
5197 ASN1_OBJECT_free(obj);
5198 return result;
5199}
5200
Christian Heimes46bebee2013-06-09 19:03:31 +02005201#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005202
5203static PyObject*
5204certEncodingType(DWORD encodingType)
5205{
5206 static PyObject *x509_asn = NULL;
5207 static PyObject *pkcs_7_asn = NULL;
5208
5209 if (x509_asn == NULL) {
5210 x509_asn = PyUnicode_InternFromString("x509_asn");
5211 if (x509_asn == NULL)
5212 return NULL;
5213 }
5214 if (pkcs_7_asn == NULL) {
5215 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5216 if (pkcs_7_asn == NULL)
5217 return NULL;
5218 }
5219 switch(encodingType) {
5220 case X509_ASN_ENCODING:
5221 Py_INCREF(x509_asn);
5222 return x509_asn;
5223 case PKCS_7_ASN_ENCODING:
5224 Py_INCREF(pkcs_7_asn);
5225 return pkcs_7_asn;
5226 default:
5227 return PyLong_FromLong(encodingType);
5228 }
5229}
5230
5231static PyObject*
5232parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5233{
5234 CERT_ENHKEY_USAGE *usage;
5235 DWORD size, error, i;
5236 PyObject *retval;
5237
5238 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5239 error = GetLastError();
5240 if (error == CRYPT_E_NOT_FOUND) {
5241 Py_RETURN_TRUE;
5242 }
5243 return PyErr_SetFromWindowsErr(error);
5244 }
5245
5246 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5247 if (usage == NULL) {
5248 return PyErr_NoMemory();
5249 }
5250
5251 /* Now get the actual enhanced usage property */
5252 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5253 PyMem_Free(usage);
5254 error = GetLastError();
5255 if (error == CRYPT_E_NOT_FOUND) {
5256 Py_RETURN_TRUE;
5257 }
5258 return PyErr_SetFromWindowsErr(error);
5259 }
5260 retval = PySet_New(NULL);
5261 if (retval == NULL) {
5262 goto error;
5263 }
5264 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5265 if (usage->rgpszUsageIdentifier[i]) {
5266 PyObject *oid;
5267 int err;
5268 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5269 if (oid == NULL) {
5270 Py_CLEAR(retval);
5271 goto error;
5272 }
5273 err = PySet_Add(retval, oid);
5274 Py_DECREF(oid);
5275 if (err == -1) {
5276 Py_CLEAR(retval);
5277 goto error;
5278 }
5279 }
5280 }
5281 error:
5282 PyMem_Free(usage);
5283 return retval;
5284}
5285
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005286/*[clinic input]
5287_ssl.enum_certificates
5288 store_name: str
5289
5290Retrieve certificates from Windows' cert store.
5291
5292store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5293more cert storages, too. The function returns a list of (bytes,
5294encoding_type, trust) tuples. The encoding_type flag can be interpreted
5295with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5296a set of OIDs or the boolean True.
5297[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005298
Christian Heimes46bebee2013-06-09 19:03:31 +02005299static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005300_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5301/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005302{
Christian Heimes46bebee2013-06-09 19:03:31 +02005303 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005304 PCCERT_CONTEXT pCertCtx = NULL;
5305 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005306 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005307
Christian Heimes44109d72013-11-22 01:51:30 +01005308 result = PyList_New(0);
5309 if (result == NULL) {
5310 return NULL;
5311 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005312 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5313 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5314 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005315 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005316 Py_DECREF(result);
5317 return PyErr_SetFromWindowsErr(GetLastError());
5318 }
5319
Christian Heimes44109d72013-11-22 01:51:30 +01005320 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5321 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5322 pCertCtx->cbCertEncoded);
5323 if (!cert) {
5324 Py_CLEAR(result);
5325 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005326 }
Christian Heimes44109d72013-11-22 01:51:30 +01005327 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5328 Py_CLEAR(result);
5329 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005330 }
Christian Heimes44109d72013-11-22 01:51:30 +01005331 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5332 if (keyusage == Py_True) {
5333 Py_DECREF(keyusage);
5334 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005335 }
Christian Heimes44109d72013-11-22 01:51:30 +01005336 if (keyusage == NULL) {
5337 Py_CLEAR(result);
5338 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005339 }
Christian Heimes44109d72013-11-22 01:51:30 +01005340 if ((tup = PyTuple_New(3)) == NULL) {
5341 Py_CLEAR(result);
5342 break;
5343 }
5344 PyTuple_SET_ITEM(tup, 0, cert);
5345 cert = NULL;
5346 PyTuple_SET_ITEM(tup, 1, enc);
5347 enc = NULL;
5348 PyTuple_SET_ITEM(tup, 2, keyusage);
5349 keyusage = NULL;
5350 if (PyList_Append(result, tup) < 0) {
5351 Py_CLEAR(result);
5352 break;
5353 }
5354 Py_CLEAR(tup);
5355 }
5356 if (pCertCtx) {
5357 /* loop ended with an error, need to clean up context manually */
5358 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005359 }
5360
5361 /* In error cases cert, enc and tup may not be NULL */
5362 Py_XDECREF(cert);
5363 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005364 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005365 Py_XDECREF(tup);
5366
5367 if (!CertCloseStore(hStore, 0)) {
5368 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005369 Py_XDECREF(result);
5370 return PyErr_SetFromWindowsErr(GetLastError());
5371 }
5372 return result;
5373}
5374
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005375/*[clinic input]
5376_ssl.enum_crls
5377 store_name: str
5378
5379Retrieve CRLs from Windows' cert store.
5380
5381store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5382more cert storages, too. The function returns a list of (bytes,
5383encoding_type) tuples. The encoding_type flag can be interpreted with
5384X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5385[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005386
5387static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005388_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5389/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005390{
Christian Heimes44109d72013-11-22 01:51:30 +01005391 HCERTSTORE hStore = NULL;
5392 PCCRL_CONTEXT pCrlCtx = NULL;
5393 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5394 PyObject *result = NULL;
5395
Christian Heimes44109d72013-11-22 01:51:30 +01005396 result = PyList_New(0);
5397 if (result == NULL) {
5398 return NULL;
5399 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005400 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5401 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5402 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005403 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005404 Py_DECREF(result);
5405 return PyErr_SetFromWindowsErr(GetLastError());
5406 }
Christian Heimes44109d72013-11-22 01:51:30 +01005407
5408 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5409 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5410 pCrlCtx->cbCrlEncoded);
5411 if (!crl) {
5412 Py_CLEAR(result);
5413 break;
5414 }
5415 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5416 Py_CLEAR(result);
5417 break;
5418 }
5419 if ((tup = PyTuple_New(2)) == NULL) {
5420 Py_CLEAR(result);
5421 break;
5422 }
5423 PyTuple_SET_ITEM(tup, 0, crl);
5424 crl = NULL;
5425 PyTuple_SET_ITEM(tup, 1, enc);
5426 enc = NULL;
5427
5428 if (PyList_Append(result, tup) < 0) {
5429 Py_CLEAR(result);
5430 break;
5431 }
5432 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005433 }
Christian Heimes44109d72013-11-22 01:51:30 +01005434 if (pCrlCtx) {
5435 /* loop ended with an error, need to clean up context manually */
5436 CertFreeCRLContext(pCrlCtx);
5437 }
5438
5439 /* In error cases cert, enc and tup may not be NULL */
5440 Py_XDECREF(crl);
5441 Py_XDECREF(enc);
5442 Py_XDECREF(tup);
5443
5444 if (!CertCloseStore(hStore, 0)) {
5445 /* This error case might shadow another exception.*/
5446 Py_XDECREF(result);
5447 return PyErr_SetFromWindowsErr(GetLastError());
5448 }
5449 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005450}
Christian Heimes44109d72013-11-22 01:51:30 +01005451
5452#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005453
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005454/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005455static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005456 _SSL__TEST_DECODE_CERT_METHODDEF
5457 _SSL_RAND_ADD_METHODDEF
5458 _SSL_RAND_BYTES_METHODDEF
5459 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5460 _SSL_RAND_EGD_METHODDEF
5461 _SSL_RAND_STATUS_METHODDEF
5462 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5463 _SSL_ENUM_CERTIFICATES_METHODDEF
5464 _SSL_ENUM_CRLS_METHODDEF
5465 _SSL_TXT2OBJ_METHODDEF
5466 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005467 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005468};
5469
5470
Christian Heimes598894f2016-09-05 23:19:05 +02005471#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005472
5473/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005474 * of the Python C thread library
5475 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5476 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005477
5478static PyThread_type_lock *_ssl_locks = NULL;
5479
Christian Heimes4d98ca92013-08-19 17:36:29 +02005480#if OPENSSL_VERSION_NUMBER >= 0x10000000
5481/* use new CRYPTO_THREADID API. */
5482static void
5483_ssl_threadid_callback(CRYPTO_THREADID *id)
5484{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005485 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005486}
5487#else
5488/* deprecated CRYPTO_set_id_callback() API. */
5489static unsigned long
5490_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005491 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005492}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005493#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005494
Bill Janssen6e027db2007-11-15 22:23:56 +00005495static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005496 (int mode, int n, const char *file, int line) {
5497 /* this function is needed to perform locking on shared data
5498 structures. (Note that OpenSSL uses a number of global data
5499 structures that will be implicitly shared whenever multiple
5500 threads use OpenSSL.) Multi-threaded applications will
5501 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005502
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005503 locking_function() must be able to handle up to
5504 CRYPTO_num_locks() different mutex locks. It sets the n-th
5505 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005506
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005507 file and line are the file number of the function setting the
5508 lock. They can be useful for debugging.
5509 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005511 if ((_ssl_locks == NULL) ||
5512 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5513 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005514
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005515 if (mode & CRYPTO_LOCK) {
5516 PyThread_acquire_lock(_ssl_locks[n], 1);
5517 } else {
5518 PyThread_release_lock(_ssl_locks[n]);
5519 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005520}
5521
5522static int _setup_ssl_threads(void) {
5523
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005524 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005525
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005526 if (_ssl_locks == NULL) {
5527 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005528 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5529 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005530 if (_ssl_locks == NULL) {
5531 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005532 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005533 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005534 for (i = 0; i < _ssl_locks_count; i++) {
5535 _ssl_locks[i] = PyThread_allocate_lock();
5536 if (_ssl_locks[i] == NULL) {
5537 unsigned int j;
5538 for (j = 0; j < i; j++) {
5539 PyThread_free_lock(_ssl_locks[j]);
5540 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005541 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005542 return 0;
5543 }
5544 }
5545 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005546#if OPENSSL_VERSION_NUMBER >= 0x10000000
5547 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5548#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005549 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005550#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005551 }
5552 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005553}
5554
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005555#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005556
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005557PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005558"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005559for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005560
Martin v. Löwis1a214512008-06-11 05:26:20 +00005561
5562static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005563 PyModuleDef_HEAD_INIT,
5564 "_ssl",
5565 module_doc,
5566 -1,
5567 PySSL_methods,
5568 NULL,
5569 NULL,
5570 NULL,
5571 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005572};
5573
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005574
5575static void
5576parse_openssl_version(unsigned long libver,
5577 unsigned int *major, unsigned int *minor,
5578 unsigned int *fix, unsigned int *patch,
5579 unsigned int *status)
5580{
5581 *status = libver & 0xF;
5582 libver >>= 4;
5583 *patch = libver & 0xFF;
5584 libver >>= 8;
5585 *fix = libver & 0xFF;
5586 libver >>= 8;
5587 *minor = libver & 0xFF;
5588 libver >>= 8;
5589 *major = libver & 0xFF;
5590}
5591
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005592PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005593PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005594{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005595 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005596 unsigned long libver;
5597 unsigned int major, minor, fix, patch, status;
5598 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005599 struct py_ssl_error_code *errcode;
5600 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005601
Antoine Pitrou152efa22010-05-16 18:19:27 +00005602 if (PyType_Ready(&PySSLContext_Type) < 0)
5603 return NULL;
5604 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005605 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005606 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5607 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005608 if (PyType_Ready(&PySSLSession_Type) < 0)
5609 return NULL;
5610
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005612 m = PyModule_Create(&_sslmodule);
5613 if (m == NULL)
5614 return NULL;
5615 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005616
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005617 /* Load _socket module and its C API */
5618 socket_api = PySocketModule_ImportModuleAndAPI();
5619 if (!socket_api)
5620 return NULL;
5621 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005622
Christian Heimesc941e622017-09-05 15:47:11 +02005623#ifndef OPENSSL_VERSION_1_1
5624 /* Load all algorithms and initialize cpuid */
5625 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005626 /* Init OpenSSL */
5627 SSL_load_error_strings();
5628 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005629#endif
5630
Christian Heimes598894f2016-09-05 23:19:05 +02005631#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005632 /* note that this will start threading if not already started */
5633 if (!_setup_ssl_threads()) {
5634 return NULL;
5635 }
Christian Heimes598894f2016-09-05 23:19:05 +02005636#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5637 /* OpenSSL 1.1.0 builtin thread support is enabled */
5638 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005639#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005640
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005641 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005642 sslerror_type_slots[0].pfunc = PyExc_OSError;
5643 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005644 if (PySSLErrorObject == NULL)
5645 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005646
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005647 /* ssl.CertificateError used to be a subclass of ValueError */
5648 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5649 if (bases == NULL)
5650 return NULL;
5651 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5652 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5653 bases, NULL);
5654 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005655 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5656 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5657 PySSLErrorObject, NULL);
5658 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5659 "ssl.SSLWantReadError", SSLWantReadError_doc,
5660 PySSLErrorObject, NULL);
5661 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5662 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5663 PySSLErrorObject, NULL);
5664 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5665 "ssl.SSLSyscallError", SSLSyscallError_doc,
5666 PySSLErrorObject, NULL);
5667 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5668 "ssl.SSLEOFError", SSLEOFError_doc,
5669 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005670 if (PySSLCertVerificationErrorObject == NULL
5671 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005672 || PySSLWantReadErrorObject == NULL
5673 || PySSLWantWriteErrorObject == NULL
5674 || PySSLSyscallErrorObject == NULL
5675 || PySSLEOFErrorObject == NULL)
5676 return NULL;
5677 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005678 || PyDict_SetItemString(d, "SSLCertVerificationError",
5679 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005680 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5681 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5682 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5683 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5684 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005685 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005686 if (PyDict_SetItemString(d, "_SSLContext",
5687 (PyObject *)&PySSLContext_Type) != 0)
5688 return NULL;
5689 if (PyDict_SetItemString(d, "_SSLSocket",
5690 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005691 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005692 if (PyDict_SetItemString(d, "MemoryBIO",
5693 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5694 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005695 if (PyDict_SetItemString(d, "SSLSession",
5696 (PyObject *)&PySSLSession_Type) != 0)
5697 return NULL;
5698
Christian Heimes892d66e2018-01-29 14:10:18 +01005699 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5700 PY_SSL_DEFAULT_CIPHER_STRING);
5701
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005702 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5703 PY_SSL_ERROR_ZERO_RETURN);
5704 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5705 PY_SSL_ERROR_WANT_READ);
5706 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5707 PY_SSL_ERROR_WANT_WRITE);
5708 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5709 PY_SSL_ERROR_WANT_X509_LOOKUP);
5710 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5711 PY_SSL_ERROR_SYSCALL);
5712 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5713 PY_SSL_ERROR_SSL);
5714 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5715 PY_SSL_ERROR_WANT_CONNECT);
5716 /* non ssl.h errorcodes */
5717 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5718 PY_SSL_ERROR_EOF);
5719 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5720 PY_SSL_ERROR_INVALID_ERROR_CODE);
5721 /* cert requirements */
5722 PyModule_AddIntConstant(m, "CERT_NONE",
5723 PY_SSL_CERT_NONE);
5724 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5725 PY_SSL_CERT_OPTIONAL);
5726 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5727 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005728 /* CRL verification for verification_flags */
5729 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5730 0);
5731 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5732 X509_V_FLAG_CRL_CHECK);
5733 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5734 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5735 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5736 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005737#ifdef X509_V_FLAG_TRUSTED_FIRST
5738 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5739 X509_V_FLAG_TRUSTED_FIRST);
5740#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005741
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005742 /* Alert Descriptions from ssl.h */
5743 /* note RESERVED constants no longer intended for use have been removed */
5744 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5745
5746#define ADD_AD_CONSTANT(s) \
5747 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5748 SSL_AD_##s)
5749
5750 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5751 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5752 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5753 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5754 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5755 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5756 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5757 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5758 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5759 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5760 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5761 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5762 ADD_AD_CONSTANT(UNKNOWN_CA);
5763 ADD_AD_CONSTANT(ACCESS_DENIED);
5764 ADD_AD_CONSTANT(DECODE_ERROR);
5765 ADD_AD_CONSTANT(DECRYPT_ERROR);
5766 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5767 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5768 ADD_AD_CONSTANT(INTERNAL_ERROR);
5769 ADD_AD_CONSTANT(USER_CANCELLED);
5770 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005771 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005772#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5773 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5774#endif
5775#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5776 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5777#endif
5778#ifdef SSL_AD_UNRECOGNIZED_NAME
5779 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5780#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005781#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5782 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5783#endif
5784#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5785 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5786#endif
5787#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5788 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5789#endif
5790
5791#undef ADD_AD_CONSTANT
5792
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005793 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005794#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005795 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5796 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005797#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005798#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005799 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5800 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005801#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005802 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005803 PY_SSL_VERSION_TLS);
5804 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5805 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005806 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5807 PY_SSL_VERSION_TLS_CLIENT);
5808 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5809 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005810 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5811 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005812#if HAVE_TLSv1_2
5813 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5814 PY_SSL_VERSION_TLS1_1);
5815 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5816 PY_SSL_VERSION_TLS1_2);
5817#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005818
Antoine Pitroub5218772010-05-21 09:56:06 +00005819 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005820 PyModule_AddIntConstant(m, "OP_ALL",
5821 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005822 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5823 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5824 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005825#if HAVE_TLSv1_2
5826 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5827 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5828#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005829#ifdef SSL_OP_NO_TLSv1_3
5830 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5831#else
5832 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5833#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005834 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5835 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005836 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005837 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005838#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005839 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005840#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005841#ifdef SSL_OP_NO_COMPRESSION
5842 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5843 SSL_OP_NO_COMPRESSION);
5844#endif
Christian Heimes05d9fe32018-02-27 08:55:39 +01005845#ifdef SSL_OP_ENABLE_MIDDLEBOX_COMPAT
5846 PyModule_AddIntConstant(m, "OP_ENABLE_MIDDLEBOX_COMPAT",
5847 SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
5848#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005849
Christian Heimes61d478c2018-01-27 15:51:38 +01005850#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5851 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5852 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5853#endif
5854#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5855 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5856 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5857#endif
5858#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5859 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5860 X509_CHECK_FLAG_NO_WILDCARDS);
5861#endif
5862#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5863 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5864 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5865#endif
5866#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5867 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5868 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5869#endif
5870#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5871 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5872 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5873#endif
5874
Christian Heimes698dde12018-02-27 11:54:43 +01005875 /* protocol versions */
5876 PyModule_AddIntConstant(m, "PROTO_MINIMUM_SUPPORTED",
5877 PY_PROTO_MINIMUM_SUPPORTED);
5878 PyModule_AddIntConstant(m, "PROTO_MAXIMUM_SUPPORTED",
5879 PY_PROTO_MAXIMUM_SUPPORTED);
5880 PyModule_AddIntConstant(m, "PROTO_SSLv3", PY_PROTO_SSLv3);
5881 PyModule_AddIntConstant(m, "PROTO_TLSv1", PY_PROTO_TLSv1);
5882 PyModule_AddIntConstant(m, "PROTO_TLSv1_1", PY_PROTO_TLSv1_1);
5883 PyModule_AddIntConstant(m, "PROTO_TLSv1_2", PY_PROTO_TLSv1_2);
5884 PyModule_AddIntConstant(m, "PROTO_TLSv1_3", PY_PROTO_TLSv1_3);
Antoine Pitroud5323212010-10-22 18:19:07 +00005885
Christian Heimes698dde12018-02-27 11:54:43 +01005886#define addbool(m, v, b) \
5887 Py_INCREF((b) ? Py_True : Py_False); \
5888 PyModule_AddObject((m), (v), (b) ? Py_True : Py_False);
5889
5890#if HAVE_SNI
5891 addbool(m, "HAS_SNI", 1);
Antoine Pitrou501da612011-12-21 09:27:41 +01005892#else
Christian Heimes698dde12018-02-27 11:54:43 +01005893 addbool(m, "HAS_SNI", 0);
Antoine Pitrou501da612011-12-21 09:27:41 +01005894#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005895
5896 addbool(m, "HAS_TLS_UNIQUE", 1);
5897
5898#ifndef OPENSSL_NO_ECDH
5899 addbool(m, "HAS_ECDH", 1);
5900#else
5901 addbool(m, "HAS_ECDH", 0);
5902#endif
Antoine Pitrou501da612011-12-21 09:27:41 +01005903
Christian Heimes29eab552018-02-25 12:31:33 +01005904#if HAVE_NPN
Christian Heimes698dde12018-02-27 11:54:43 +01005905 addbool(m, "HAS_NPN", 1);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005906#else
Christian Heimes698dde12018-02-27 11:54:43 +01005907 addbool(m, "HAS_NPN", 0);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005908#endif
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005909
Christian Heimes29eab552018-02-25 12:31:33 +01005910#if HAVE_ALPN
Christian Heimes698dde12018-02-27 11:54:43 +01005911 addbool(m, "HAS_ALPN", 1);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005912#else
Christian Heimes698dde12018-02-27 11:54:43 +01005913 addbool(m, "HAS_ALPN", 0);
Benjamin Petersoncca27322015-01-23 16:35:37 -05005914#endif
Christian Heimes698dde12018-02-27 11:54:43 +01005915
5916#if defined(SSL2_VERSION) && !defined(OPENSSL_NO_SSL2)
5917 addbool(m, "HAS_SSLv2", 1);
5918#else
5919 addbool(m, "HAS_SSLv2", 0);
5920#endif
5921
5922#if defined(SSL3_VERSION) && !defined(OPENSSL_NO_SSL3)
5923 addbool(m, "HAS_SSLv3", 1);
5924#else
5925 addbool(m, "HAS_SSLv3", 0);
5926#endif
5927
5928#if defined(TLS1_VERSION) && !defined(OPENSSL_NO_TLS1)
5929 addbool(m, "HAS_TLSv1", 1);
5930#else
5931 addbool(m, "HAS_TLSv1", 0);
5932#endif
5933
5934#if defined(TLS1_1_VERSION) && !defined(OPENSSL_NO_TLS1_1)
5935 addbool(m, "HAS_TLSv1_1", 1);
5936#else
5937 addbool(m, "HAS_TLSv1_1", 0);
5938#endif
5939
5940#if defined(TLS1_2_VERSION) && !defined(OPENSSL_NO_TLS1_2)
5941 addbool(m, "HAS_TLSv1_2", 1);
5942#else
5943 addbool(m, "HAS_TLSv1_2", 0);
5944#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05005945
Christian Heimescb5b68a2017-09-07 18:07:00 -07005946#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
Christian Heimes698dde12018-02-27 11:54:43 +01005947 addbool(m, "HAS_TLSv1_3", 1);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005948#else
Christian Heimes698dde12018-02-27 11:54:43 +01005949 addbool(m, "HAS_TLSv1_3", 0);
Christian Heimescb5b68a2017-09-07 18:07:00 -07005950#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005951
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005952 /* Mappings for error codes */
5953 err_codes_to_names = PyDict_New();
5954 err_names_to_codes = PyDict_New();
5955 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5956 return NULL;
5957 errcode = error_codes;
5958 while (errcode->mnemonic != NULL) {
5959 PyObject *mnemo, *key;
5960 mnemo = PyUnicode_FromString(errcode->mnemonic);
5961 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5962 if (mnemo == NULL || key == NULL)
5963 return NULL;
5964 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5965 return NULL;
5966 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5967 return NULL;
5968 Py_DECREF(key);
5969 Py_DECREF(mnemo);
5970 errcode++;
5971 }
5972 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5973 return NULL;
5974 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5975 return NULL;
5976
5977 lib_codes_to_names = PyDict_New();
5978 if (lib_codes_to_names == NULL)
5979 return NULL;
5980 libcode = library_codes;
5981 while (libcode->library != NULL) {
5982 PyObject *mnemo, *key;
5983 key = PyLong_FromLong(libcode->code);
5984 mnemo = PyUnicode_FromString(libcode->library);
5985 if (key == NULL || mnemo == NULL)
5986 return NULL;
5987 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5988 return NULL;
5989 Py_DECREF(key);
5990 Py_DECREF(mnemo);
5991 libcode++;
5992 }
5993 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5994 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005996 /* OpenSSL version */
5997 /* SSLeay() gives us the version of the library linked against,
5998 which could be different from the headers version.
5999 */
6000 libver = SSLeay();
6001 r = PyLong_FromUnsignedLong(libver);
6002 if (r == NULL)
6003 return NULL;
6004 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
6005 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006006 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006007 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6008 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
6009 return NULL;
6010 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
6011 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
6012 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00006013
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02006014 libver = OPENSSL_VERSION_NUMBER;
6015 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
6016 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
6017 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
6018 return NULL;
6019
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00006020 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00006021}