blob: 7545e91babdb3fe90743254587c8b78eaefa2006 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066
Christian Heimesff5be6e2018-01-20 13:19:21 +010067#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010068# ifdef LIBRESSL_VERSION_NUMBER
69# error "LibreSSL is missing X509_VERIFY_PARAM_set1_host(), see https://github.com/libressl-portable/portable/issues/381"
70# elif OPENSSL_VERSION_NUMBER > 0x1000200fL
Christian Heimesff5be6e2018-01-20 13:19:21 +010071# define HAVE_X509_VERIFY_PARAM_SET1_HOST
Christian Heimes61d478c2018-01-27 15:51:38 +010072# else
73# error "libssl is too old and does not support X509_VERIFY_PARAM_set1_host()"
Christian Heimesff5be6e2018-01-20 13:19:21 +010074# endif
75#endif
76
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077/* SSL error object */
78static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070079static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010080static PyObject *PySSLZeroReturnErrorObject;
81static PyObject *PySSLWantReadErrorObject;
82static PyObject *PySSLWantWriteErrorObject;
83static PyObject *PySSLSyscallErrorObject;
84static PyObject *PySSLEOFErrorObject;
85
86/* Error mappings */
87static PyObject *err_codes_to_names;
88static PyObject *err_names_to_codes;
89static PyObject *lib_codes_to_names;
90
91struct py_ssl_error_code {
92 const char *mnemonic;
93 int library, reason;
94};
95struct py_ssl_library_code {
96 const char *library;
97 int code;
98};
99
Steve Dower68d663c2017-07-17 11:15:48 +0200100#if defined(MS_WINDOWS) && defined(Py_DEBUG)
101/* Debug builds on Windows rely on getting errno directly from OpenSSL.
102 * However, because it uses a different CRT, we need to transfer the
103 * value of errno from OpenSSL into our debug CRT.
104 *
105 * Don't be fooled - this is horribly ugly code. The only reasonable
106 * alternative is to do both debug and release builds of OpenSSL, which
107 * requires much uglier code to transform their automatically generated
108 * makefile. This is the lesser of all the evils.
109 */
110
111static void _PySSLFixErrno(void) {
112 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
113 if (!ucrtbase) {
114 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
115 * have a catastrophic failure, but this function is not the
116 * place to raise it. */
117 return;
118 }
119
120 typedef int *(__stdcall *errno_func)(void);
121 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
122 if (ssl_errno) {
123 errno = *ssl_errno();
124 *ssl_errno() = 0;
125 } else {
126 errno = ENOTRECOVERABLE;
127 }
128}
129
130#undef _PySSL_FIX_ERRNO
131#define _PySSL_FIX_ERRNO _PySSLFixErrno()
132#endif
133
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100134/* Include generated data (error codes) */
135#include "_ssl_data.h"
136
Christian Heimes598894f2016-09-05 23:19:05 +0200137#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
138# define OPENSSL_VERSION_1_1 1
139#endif
140
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100141/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
142 http://www.openssl.org/news/changelog.html
143 */
144#if OPENSSL_VERSION_NUMBER >= 0x10001000L
145# define HAVE_TLSv1_2 1
146#else
147# define HAVE_TLSv1_2 0
148#endif
149
Christian Heimes470fba12013-11-28 15:12:15 +0100150/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100151 * This includes the SSL_set_SSL_CTX() function.
152 */
153#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
154# define HAVE_SNI 1
155#else
156# define HAVE_SNI 0
157#endif
158
Benjamin Petersond3308222015-09-27 00:09:02 -0700159#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500160# define HAVE_ALPN
161#endif
162
Victor Stinner524714e2016-07-22 17:43:59 +0200163#ifndef INVALID_SOCKET /* MS defines this */
164#define INVALID_SOCKET (-1)
165#endif
166
Christian Heimes598894f2016-09-05 23:19:05 +0200167#ifdef OPENSSL_VERSION_1_1
168/* OpenSSL 1.1.0+ */
169#ifndef OPENSSL_NO_SSL2
170#define OPENSSL_NO_SSL2
171#endif
172#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200173#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200174
175#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200176#define TLS_client_method SSLv23_client_method
177#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200178
179static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
180{
181 return ne->set;
182}
183
184#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200185/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200186static int COMP_get_type(const COMP_METHOD *meth)
187{
188 return meth->type;
189}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200190/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200191#endif
192
193static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
194{
195 return ctx->default_passwd_callback;
196}
197
198static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
199{
200 return ctx->default_passwd_callback_userdata;
201}
202
203static int X509_OBJECT_get_type(X509_OBJECT *x)
204{
205 return x->type;
206}
207
208static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
209{
210 return x->data.x509;
211}
212
213static int BIO_up_ref(BIO *b)
214{
215 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
216 return 1;
217}
218
219static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
220 return store->objs;
221}
222
Christian Heimes99a65702016-09-10 23:44:53 +0200223static int
224SSL_SESSION_has_ticket(const SSL_SESSION *s)
225{
226 return (s->tlsext_ticklen > 0) ? 1 : 0;
227}
228
229static unsigned long
230SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
231{
232 return s->tlsext_tick_lifetime_hint;
233}
234
Christian Heimes598894f2016-09-05 23:19:05 +0200235#endif /* OpenSSL < 1.1.0 or LibreSSL */
236
Christian Heimes892d66e2018-01-29 14:10:18 +0100237/* Default cipher suites */
238#ifndef PY_SSL_DEFAULT_CIPHERS
239#define PY_SSL_DEFAULT_CIPHERS 1
240#endif
241
242#if PY_SSL_DEFAULT_CIPHERS == 0
243 #ifndef PY_SSL_DEFAULT_CIPHER_STRING
244 #error "Py_SSL_DEFAULT_CIPHERS 0 needs Py_SSL_DEFAULT_CIPHER_STRING"
245 #endif
246#elif PY_SSL_DEFAULT_CIPHERS == 1
247/* Python custom selection of sensible ciper suites
248 * DEFAULT: OpenSSL's default cipher list. Since 1.0.2 the list is in sensible order.
249 * !aNULL:!eNULL: really no NULL ciphers
250 * !MD5:!3DES:!DES:!RC4:!IDEA:!SEED: no weak or broken algorithms on old OpenSSL versions.
251 * !aDSS: no authentication with discrete logarithm DSA algorithm
252 * !SRP:!PSK: no secure remote password or pre-shared key authentication
253 */
254 #define PY_SSL_DEFAULT_CIPHER_STRING "DEFAULT:!aNULL:!eNULL:!MD5:!3DES:!DES:!RC4:!IDEA:!SEED:!aDSS:!SRP:!PSK"
255#elif PY_SSL_DEFAULT_CIPHERS == 2
256/* Ignored in SSLContext constructor, only used to as _ssl.DEFAULT_CIPHER_STRING */
257 #define PY_SSL_DEFAULT_CIPHER_STRING SSL_DEFAULT_CIPHER_LIST
258#else
259 #error "Unsupported PY_SSL_DEFAULT_CIPHERS"
260#endif
261
Christian Heimes598894f2016-09-05 23:19:05 +0200262
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000263enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000264 /* these mirror ssl.h */
265 PY_SSL_ERROR_NONE,
266 PY_SSL_ERROR_SSL,
267 PY_SSL_ERROR_WANT_READ,
268 PY_SSL_ERROR_WANT_WRITE,
269 PY_SSL_ERROR_WANT_X509_LOOKUP,
270 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
271 PY_SSL_ERROR_ZERO_RETURN,
272 PY_SSL_ERROR_WANT_CONNECT,
273 /* start of non ssl.h errorcodes */
274 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
275 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
276 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000277};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000278
Thomas Woutersed03b412007-08-28 21:37:11 +0000279enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000280 PY_SSL_CLIENT,
281 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000282};
283
284enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000285 PY_SSL_CERT_NONE,
286 PY_SSL_CERT_OPTIONAL,
287 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000288};
289
290enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000291 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200292 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200293 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100294#if HAVE_TLSv1_2
295 PY_SSL_VERSION_TLS1,
296 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200297 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100298#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200299 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000300#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200301 PY_SSL_VERSION_TLS_CLIENT=0x10,
302 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100303};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200304
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000305/* serves as a flag to see whether we've initialized the SSL thread support. */
306/* 0 means no, greater than 0 means yes */
307
308static unsigned int _ssl_locks_count = 0;
309
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000310/* SSL socket object */
311
312#define X509_NAME_MAXLEN 256
313
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000314/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
315 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
316 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
317#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000318# define HAVE_SSL_CTX_CLEAR_OPTIONS
319#else
320# undef HAVE_SSL_CTX_CLEAR_OPTIONS
321#endif
322
Antoine Pitroud6494802011-07-21 01:11:30 +0200323/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
324 * older SSL, but let's be safe */
325#define PySSL_CB_MAXLEN 128
326
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100327
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000328typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000329 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000330 SSL_CTX *ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +0200331#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500332 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100333 int npn_protocols_len;
334#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500335#ifdef HAVE_ALPN
336 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300337 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500338#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100339#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200340 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100341#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100342 int check_hostname;
Christian Heimes61d478c2018-01-27 15:51:38 +0100343 /* OpenSSL has no API to get hostflags from X509_VERIFY_PARAM* struct.
344 * We have to maintain our own copy. OpenSSL's hostflags default to 0.
345 */
346 unsigned int hostflags;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000347} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000348
Antoine Pitrou152efa22010-05-16 18:19:27 +0000349typedef struct {
350 PyObject_HEAD
351 PyObject *Socket; /* weakref to socket on which we're layered */
352 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100353 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200354 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200355 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200356 PyObject *owner; /* Python level "owner" passed to servername callback */
357 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700358 int ssl_errno; /* last seen error from SSL */
359 int c_errno; /* last seen error from libc */
360#ifdef MS_WINDOWS
361 int ws_errno; /* last seen error from winsock */
362#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000363} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000364
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200365typedef struct {
366 PyObject_HEAD
367 BIO *bio;
368 int eof_written;
369} PySSLMemoryBIO;
370
Christian Heimes99a65702016-09-10 23:44:53 +0200371typedef struct {
372 PyObject_HEAD
373 SSL_SESSION *session;
374 PySSLContext *ctx;
375} PySSLSession;
376
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377static PyTypeObject PySSLContext_Type;
378static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200379static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200380static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000381
Steve Dowere6eb48c2017-09-08 15:16:15 -0700382#ifdef MS_WINDOWS
383#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
384 (sock)->ws_errno = WSAGetLastError(); \
385 _PySSL_FIX_ERRNO; \
386 (sock)->c_errno = errno; \
387 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
388 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
389#else
390#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
391 (sock)->c_errno = errno; \
392 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
393 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
394#endif
395#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
396
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300397/*[clinic input]
398module _ssl
399class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
400class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
401class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200402class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300403[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200404/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300405
406#include "clinic/_ssl.c.h"
407
Victor Stinner14690702015-04-06 22:46:13 +0200408static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000409
Christian Heimes99a65702016-09-10 23:44:53 +0200410
Antoine Pitrou152efa22010-05-16 18:19:27 +0000411#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
412#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200413#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200414#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000415
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000416typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000417 SOCKET_IS_NONBLOCKING,
418 SOCKET_IS_BLOCKING,
419 SOCKET_HAS_TIMED_OUT,
420 SOCKET_HAS_BEEN_CLOSED,
421 SOCKET_TOO_LARGE_FOR_SELECT,
422 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000423} timeout_state;
424
Thomas Woutersed03b412007-08-28 21:37:11 +0000425/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000426#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200427#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000428
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200429/* Get the socket from a PySSLSocket, if it has one */
430#define GET_SOCKET(obj) ((obj)->Socket ? \
431 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200432
Victor Stinner14690702015-04-06 22:46:13 +0200433/* If sock is NULL, use a timeout of 0 second */
434#define GET_SOCKET_TIMEOUT(sock) \
435 ((sock != NULL) ? (sock)->sock_timeout : 0)
436
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200437/*
438 * SSL errors.
439 */
440
441PyDoc_STRVAR(SSLError_doc,
442"An error occurred in the SSL implementation.");
443
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700444PyDoc_STRVAR(SSLCertVerificationError_doc,
445"A certificate could not be verified.");
446
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447PyDoc_STRVAR(SSLZeroReturnError_doc,
448"SSL/TLS session closed cleanly.");
449
450PyDoc_STRVAR(SSLWantReadError_doc,
451"Non-blocking SSL socket needs to read more data\n"
452"before the requested operation can be completed.");
453
454PyDoc_STRVAR(SSLWantWriteError_doc,
455"Non-blocking SSL socket needs to write more data\n"
456"before the requested operation can be completed.");
457
458PyDoc_STRVAR(SSLSyscallError_doc,
459"System error when attempting SSL operation.");
460
461PyDoc_STRVAR(SSLEOFError_doc,
462"SSL/TLS connection terminated abruptly.");
463
464static PyObject *
465SSLError_str(PyOSErrorObject *self)
466{
467 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
468 Py_INCREF(self->strerror);
469 return self->strerror;
470 }
471 else
472 return PyObject_Str(self->args);
473}
474
475static PyType_Slot sslerror_type_slots[] = {
476 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
477 {Py_tp_doc, SSLError_doc},
478 {Py_tp_str, SSLError_str},
479 {0, 0},
480};
481
482static PyType_Spec sslerror_type_spec = {
483 "ssl.SSLError",
484 sizeof(PyOSErrorObject),
485 0,
486 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
487 sslerror_type_slots
488};
489
490static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700491fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
492 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200493{
494 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700495 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200496 PyObject *init_value, *msg, *key;
497 _Py_IDENTIFIER(reason);
498 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700499 _Py_IDENTIFIER(verify_message);
500 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200501
502 if (errcode != 0) {
503 int lib, reason;
504
505 lib = ERR_GET_LIB(errcode);
506 reason = ERR_GET_REASON(errcode);
507 key = Py_BuildValue("ii", lib, reason);
508 if (key == NULL)
509 goto fail;
510 reason_obj = PyDict_GetItem(err_codes_to_names, key);
511 Py_DECREF(key);
512 if (reason_obj == NULL) {
513 /* XXX if reason < 100, it might reflect a library number (!!) */
514 PyErr_Clear();
515 }
516 key = PyLong_FromLong(lib);
517 if (key == NULL)
518 goto fail;
519 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
520 Py_DECREF(key);
521 if (lib_obj == NULL) {
522 PyErr_Clear();
523 }
524 if (errstr == NULL)
525 errstr = ERR_reason_error_string(errcode);
526 }
527 if (errstr == NULL)
528 errstr = "unknown error";
529
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700530 /* verify code for cert validation error */
531 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
532 const char *verify_str = NULL;
533 long verify_code;
534
535 verify_code = SSL_get_verify_result(sslsock->ssl);
536 verify_code_obj = PyLong_FromLong(verify_code);
537 if (verify_code_obj == NULL) {
538 goto fail;
539 }
540
541 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700542#ifdef X509_V_ERR_HOSTNAME_MISMATCH
543 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700544 case X509_V_ERR_HOSTNAME_MISMATCH:
545 verify_obj = PyUnicode_FromFormat(
546 "Hostname mismatch, certificate is not valid for '%S'.",
547 sslsock->server_hostname
548 );
549 break;
Christian Heimes09153602017-09-08 14:47:58 -0700550#endif
551#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700552 case X509_V_ERR_IP_ADDRESS_MISMATCH:
553 verify_obj = PyUnicode_FromFormat(
554 "IP address mismatch, certificate is not valid for '%S'.",
555 sslsock->server_hostname
556 );
557 break;
Christian Heimes09153602017-09-08 14:47:58 -0700558#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700559 default:
560 verify_str = X509_verify_cert_error_string(verify_code);
561 if (verify_str != NULL) {
562 verify_obj = PyUnicode_FromString(verify_str);
563 } else {
564 verify_obj = Py_None;
565 Py_INCREF(verify_obj);
566 }
567 break;
568 }
569 if (verify_obj == NULL) {
570 goto fail;
571 }
572 }
573
574 if (verify_obj && reason_obj && lib_obj)
575 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
576 lib_obj, reason_obj, errstr, verify_obj,
577 lineno);
578 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
580 lib_obj, reason_obj, errstr, lineno);
581 else if (lib_obj)
582 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
583 lib_obj, errstr, lineno);
584 else
585 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200586 if (msg == NULL)
587 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100588
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200589 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100590 if (init_value == NULL)
591 goto fail;
592
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200593 err_value = PyObject_CallObject(type, init_value);
594 Py_DECREF(init_value);
595 if (err_value == NULL)
596 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100597
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200598 if (reason_obj == NULL)
599 reason_obj = Py_None;
600 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
601 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700602
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200603 if (lib_obj == NULL)
604 lib_obj = Py_None;
605 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
606 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700607
608 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
609 /* Only set verify code / message for SSLCertVerificationError */
610 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
611 verify_code_obj))
612 goto fail;
613 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
614 goto fail;
615 }
616
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200617 PyErr_SetObject(type, err_value);
618fail:
619 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700620 Py_XDECREF(verify_code_obj);
621 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200622}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000623
624static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700625PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000626{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200627 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200628 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 int err;
630 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200631 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200634 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000635
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700636 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700637 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000638
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000639 switch (err) {
640 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200641 errstr = "TLS/SSL connection has been closed (EOF)";
642 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000643 p = PY_SSL_ERROR_ZERO_RETURN;
644 break;
645 case SSL_ERROR_WANT_READ:
646 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200647 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000648 p = PY_SSL_ERROR_WANT_READ;
649 break;
650 case SSL_ERROR_WANT_WRITE:
651 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200652 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 errstr = "The operation did not complete (write)";
654 break;
655 case SSL_ERROR_WANT_X509_LOOKUP:
656 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000657 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000658 break;
659 case SSL_ERROR_WANT_CONNECT:
660 p = PY_SSL_ERROR_WANT_CONNECT;
661 errstr = "The operation did not complete (connect)";
662 break;
663 case SSL_ERROR_SYSCALL:
664 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000665 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700666 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000667 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000668 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200669 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000670 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200671 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000672 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000673 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700674#ifdef MS_WINDOWS
675 if (sslsock->ws_errno)
676 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
677#endif
678 if (sslsock->c_errno) {
679 errno = sslsock->c_errno;
680 return PyErr_SetFromErrno(PyExc_OSError);
681 }
682 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200683 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000684 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200685 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000687 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200688 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000689 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000690 }
691 } else {
692 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000693 }
694 break;
695 }
696 case SSL_ERROR_SSL:
697 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000698 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700699 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200700 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000701 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700702 }
703 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
704 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
705 type = PySSLCertVerificationErrorObject;
706 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000707 break;
708 }
709 default:
710 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
711 errstr = "Invalid error code";
712 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000713 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700714 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000715 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000716 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000717}
718
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000719static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200720_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000721
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200722 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200724 else
725 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700726 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000727 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000729}
730
Christian Heimes61d478c2018-01-27 15:51:38 +0100731/*
732 * SSL objects
733 */
734
735static int
736_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
737{
738 int retval = -1;
739 ASN1_OCTET_STRING *ip;
740 PyObject *hostname;
741 size_t len;
742
743 assert(server_hostname);
744
745 /* Disable OpenSSL's special mode with leading dot in hostname:
746 * When name starts with a dot (e.g ".example.com"), it will be
747 * matched by a certificate valid for any sub-domain of name.
748 */
749 len = strlen(server_hostname);
750 if (len == 0 || *server_hostname == '.') {
751 PyErr_SetString(
752 PyExc_ValueError,
753 "server_hostname cannot be an empty string or start with a "
754 "leading dot.");
755 return retval;
756 }
757
758 /* inet_pton is not available on all platforms. */
759 ip = a2i_IPADDRESS(server_hostname);
760 if (ip == NULL) {
761 ERR_clear_error();
762 }
763
764 hostname = PyUnicode_Decode(server_hostname, len, "idna", "strict");
765 if (hostname == NULL) {
766 goto error;
767 }
768 self->server_hostname = hostname;
769
770 /* Only send SNI extension for non-IP hostnames */
771 if (ip == NULL) {
772 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
773 _setSSLError(NULL, 0, __FILE__, __LINE__);
774 }
775 }
776 if (self->ctx->check_hostname) {
777 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
778 if (ip == NULL) {
779 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
780 _setSSLError(NULL, 0, __FILE__, __LINE__);
781 goto error;
782 }
783 } else {
784 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
785 ASN1_STRING_length(ip))) {
786 _setSSLError(NULL, 0, __FILE__, __LINE__);
787 goto error;
788 }
789 }
790 }
791 retval = 0;
792 error:
793 if (ip != NULL) {
794 ASN1_OCTET_STRING_free(ip);
795 }
796 return retval;
797}
798
Antoine Pitrou152efa22010-05-16 18:19:27 +0000799static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100800newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000801 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200802 char *server_hostname,
803 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000804{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000805 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100806 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200807 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000808
Antoine Pitrou152efa22010-05-16 18:19:27 +0000809 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000810 if (self == NULL)
811 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000812
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000814 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100815 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700816 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200817 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200818 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700819 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700820 self->ssl_errno = 0;
821 self->c_errno = 0;
822#ifdef MS_WINDOWS
823 self->ws_errno = 0;
824#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200825
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 /* Make sure the SSL error state is initialized */
827 (void) ERR_get_state();
828 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000831 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200833 SSL_set_app_data(self->ssl, self);
834 if (sock) {
835 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
836 } else {
837 /* BIOs are reference counted and SSL_set_bio borrows our reference.
838 * To prevent a double free in memory_bio_dealloc() we need to take an
839 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200840 BIO_up_ref(inbio->bio);
841 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200842 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
843 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200844 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000845#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200846 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000847#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200848 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000849
Christian Heimes61d478c2018-01-27 15:51:38 +0100850 if (server_hostname != NULL) {
851 if (_ssl_configure_hostname(self, server_hostname) < 0) {
852 Py_DECREF(self);
853 return NULL;
854 }
855 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000856 /* If the socket is in non-blocking mode or timeout mode, set the BIO
857 * to non-blocking mode (blocking is the default)
858 */
Victor Stinnere2452312015-03-28 03:00:46 +0100859 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000860 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
861 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
862 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 PySSL_BEGIN_ALLOW_THREADS
865 if (socket_type == PY_SSL_CLIENT)
866 SSL_set_connect_state(self->ssl);
867 else
868 SSL_set_accept_state(self->ssl);
869 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000870
Antoine Pitroud6494802011-07-21 01:11:30 +0200871 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200872 if (sock != NULL) {
873 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
874 if (self->Socket == NULL) {
875 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200876 return NULL;
877 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100878 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000880}
881
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000882/* SSL object methods */
883
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300884/*[clinic input]
885_ssl._SSLSocket.do_handshake
886[clinic start generated code]*/
887
888static PyObject *
889_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
890/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000891{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 int ret;
893 int err;
894 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200895 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200896 _PyTime_t timeout, deadline = 0;
897 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000898
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200899 if (sock) {
900 if (((PyObject*)sock) == Py_None) {
901 _setSSLError("Underlying socket connection gone",
902 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
903 return NULL;
904 }
905 Py_INCREF(sock);
906
907 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100908 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200909 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
910 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000911 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000912
Victor Stinner14690702015-04-06 22:46:13 +0200913 timeout = GET_SOCKET_TIMEOUT(sock);
914 has_timeout = (timeout > 0);
915 if (has_timeout)
916 deadline = _PyTime_GetMonotonicClock() + timeout;
917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 /* Actually negotiate SSL connection */
919 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000920 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000921 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000922 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700923 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700925 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200926
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000927 if (PyErr_CheckSignals())
928 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200929
Victor Stinner14690702015-04-06 22:46:13 +0200930 if (has_timeout)
931 timeout = deadline - _PyTime_GetMonotonicClock();
932
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000933 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200934 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200936 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 } else {
938 sockstate = SOCKET_OPERATION_OK;
939 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000942 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000943 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000944 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
946 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000947 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000948 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
950 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000951 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000952 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
954 break;
955 }
956 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200957 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000958 if (ret < 1)
959 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000960
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200961 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000962
963error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200964 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000965 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000966}
967
Thomas Woutersed03b412007-08-28 21:37:11 +0000968static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300969_asn1obj2py(const ASN1_OBJECT *name, int no_name)
970{
971 char buf[X509_NAME_MAXLEN];
972 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300974 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000975
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300976 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 if (buflen < 0) {
978 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300979 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300981 /* initial buffer is too small for oid + terminating null byte */
982 if (buflen > X509_NAME_MAXLEN - 1) {
983 /* make OBJ_obj2txt() calculate the required buflen */
984 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
985 /* allocate len + 1 for terminating NULL byte */
986 namebuf = PyMem_Malloc(buflen + 1);
987 if (namebuf == NULL) {
988 PyErr_NoMemory();
989 return NULL;
990 }
991 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
992 if (buflen < 0) {
993 _setSSLError(NULL, 0, __FILE__, __LINE__);
994 goto done;
995 }
996 }
997 if (!buflen && no_name) {
998 Py_INCREF(Py_None);
999 name_obj = Py_None;
1000 }
1001 else {
1002 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1003 }
1004
1005 done:
1006 if (buf != namebuf) {
1007 PyMem_Free(namebuf);
1008 }
1009 return name_obj;
1010}
1011
1012static PyObject *
1013_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1014{
1015 Py_ssize_t buflen;
1016 unsigned char *valuebuf = NULL;
1017 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001018
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001019 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1020 if (buflen < 0) {
1021 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001022 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001024 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001027}
1028
1029static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001030_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001031{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001032 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1033 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1034 PyObject *rdnt;
1035 PyObject *attr = NULL; /* tuple to hold an attribute */
1036 int entry_count = X509_NAME_entry_count(xname);
1037 X509_NAME_ENTRY *entry;
1038 ASN1_OBJECT *name;
1039 ASN1_STRING *value;
1040 int index_counter;
1041 int rdn_level = -1;
1042 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001043
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001044 dn = PyList_New(0);
1045 if (dn == NULL)
1046 return NULL;
1047 /* now create another tuple to hold the top-level RDN */
1048 rdn = PyList_New(0);
1049 if (rdn == NULL)
1050 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 for (index_counter = 0;
1053 index_counter < entry_count;
1054 index_counter++)
1055 {
1056 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 /* check to see if we've gotten to a new RDN */
1059 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001060 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 /* yes, new RDN */
1062 /* add old RDN to DN */
1063 rdnt = PyList_AsTuple(rdn);
1064 Py_DECREF(rdn);
1065 if (rdnt == NULL)
1066 goto fail0;
1067 retcode = PyList_Append(dn, rdnt);
1068 Py_DECREF(rdnt);
1069 if (retcode < 0)
1070 goto fail0;
1071 /* create new RDN */
1072 rdn = PyList_New(0);
1073 if (rdn == NULL)
1074 goto fail0;
1075 }
1076 }
Christian Heimes598894f2016-09-05 23:19:05 +02001077 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 /* now add this attribute to the current RDN */
1080 name = X509_NAME_ENTRY_get_object(entry);
1081 value = X509_NAME_ENTRY_get_data(entry);
1082 attr = _create_tuple_for_attribute(name, value);
1083 /*
1084 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1085 entry->set,
1086 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1087 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1088 */
1089 if (attr == NULL)
1090 goto fail1;
1091 retcode = PyList_Append(rdn, attr);
1092 Py_DECREF(attr);
1093 if (retcode < 0)
1094 goto fail1;
1095 }
1096 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001097 if (rdn != NULL) {
1098 if (PyList_GET_SIZE(rdn) > 0) {
1099 rdnt = PyList_AsTuple(rdn);
1100 Py_DECREF(rdn);
1101 if (rdnt == NULL)
1102 goto fail0;
1103 retcode = PyList_Append(dn, rdnt);
1104 Py_DECREF(rdnt);
1105 if (retcode < 0)
1106 goto fail0;
1107 }
1108 else {
1109 Py_DECREF(rdn);
1110 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 /* convert list to tuple */
1114 rdnt = PyList_AsTuple(dn);
1115 Py_DECREF(dn);
1116 if (rdnt == NULL)
1117 return NULL;
1118 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001119
1120 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001121 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001122
1123 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001124 Py_XDECREF(dn);
1125 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126}
1127
1128static PyObject *
1129_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 /* this code follows the procedure outlined in
1132 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1133 function to extract the STACK_OF(GENERAL_NAME),
1134 then iterates through the stack to add the
1135 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001137 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001139 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 GENERAL_NAMES *names = NULL;
1141 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001142 BIO *biobuf = NULL;
1143 char buf[2048];
1144 char *vptr;
1145 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001147 if (certificate == NULL)
1148 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001150 /* get a memory buffer */
1151 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001152
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001153 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1154 certificate, NID_subject_alt_name, NULL, NULL);
1155 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 if (peer_alt_names == Py_None) {
1157 peer_alt_names = PyList_New(0);
1158 if (peer_alt_names == NULL)
1159 goto fail;
1160 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001163 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001164 int gntype;
1165 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001167 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001168 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001169 switch (gntype) {
1170 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001171 /* we special-case DirName as a tuple of
1172 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001173
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 t = PyTuple_New(2);
1175 if (t == NULL) {
1176 goto fail;
1177 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 v = PyUnicode_FromString("DirName");
1180 if (v == NULL) {
1181 Py_DECREF(t);
1182 goto fail;
1183 }
1184 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001185
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001186 v = _create_tuple_for_X509_NAME (name->d.dirn);
1187 if (v == NULL) {
1188 Py_DECREF(t);
1189 goto fail;
1190 }
1191 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001192 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001193
Christian Heimes824f7f32013-08-17 00:54:47 +02001194 case GEN_EMAIL:
1195 case GEN_DNS:
1196 case GEN_URI:
1197 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1198 correctly, CVE-2013-4238 */
1199 t = PyTuple_New(2);
1200 if (t == NULL)
1201 goto fail;
1202 switch (gntype) {
1203 case GEN_EMAIL:
1204 v = PyUnicode_FromString("email");
1205 as = name->d.rfc822Name;
1206 break;
1207 case GEN_DNS:
1208 v = PyUnicode_FromString("DNS");
1209 as = name->d.dNSName;
1210 break;
1211 case GEN_URI:
1212 v = PyUnicode_FromString("URI");
1213 as = name->d.uniformResourceIdentifier;
1214 break;
1215 }
1216 if (v == NULL) {
1217 Py_DECREF(t);
1218 goto fail;
1219 }
1220 PyTuple_SET_ITEM(t, 0, v);
1221 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1222 ASN1_STRING_length(as));
1223 if (v == NULL) {
1224 Py_DECREF(t);
1225 goto fail;
1226 }
1227 PyTuple_SET_ITEM(t, 1, v);
1228 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001229
Christian Heimes1c03abd2016-09-06 23:25:35 +02001230 case GEN_RID:
1231 t = PyTuple_New(2);
1232 if (t == NULL)
1233 goto fail;
1234
1235 v = PyUnicode_FromString("Registered ID");
1236 if (v == NULL) {
1237 Py_DECREF(t);
1238 goto fail;
1239 }
1240 PyTuple_SET_ITEM(t, 0, v);
1241
1242 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1243 if (len < 0) {
1244 Py_DECREF(t);
1245 _setSSLError(NULL, 0, __FILE__, __LINE__);
1246 goto fail;
1247 } else if (len >= (int)sizeof(buf)) {
1248 v = PyUnicode_FromString("<INVALID>");
1249 } else {
1250 v = PyUnicode_FromStringAndSize(buf, len);
1251 }
1252 if (v == NULL) {
1253 Py_DECREF(t);
1254 goto fail;
1255 }
1256 PyTuple_SET_ITEM(t, 1, v);
1257 break;
1258
Christian Heimes824f7f32013-08-17 00:54:47 +02001259 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001260 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001261 switch (gntype) {
1262 /* check for new general name type */
1263 case GEN_OTHERNAME:
1264 case GEN_X400:
1265 case GEN_EDIPARTY:
1266 case GEN_IPADD:
1267 case GEN_RID:
1268 break;
1269 default:
1270 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1271 "Unknown general name type %d",
1272 gntype) == -1) {
1273 goto fail;
1274 }
1275 break;
1276 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001277 (void) BIO_reset(biobuf);
1278 GENERAL_NAME_print(biobuf, name);
1279 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1280 if (len < 0) {
1281 _setSSLError(NULL, 0, __FILE__, __LINE__);
1282 goto fail;
1283 }
1284 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001285 if (vptr == NULL) {
1286 PyErr_Format(PyExc_ValueError,
1287 "Invalid value %.200s",
1288 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001289 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001290 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 t = PyTuple_New(2);
1292 if (t == NULL)
1293 goto fail;
1294 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1295 if (v == NULL) {
1296 Py_DECREF(t);
1297 goto fail;
1298 }
1299 PyTuple_SET_ITEM(t, 0, v);
1300 v = PyUnicode_FromStringAndSize((vptr + 1),
1301 (len - (vptr - buf + 1)));
1302 if (v == NULL) {
1303 Py_DECREF(t);
1304 goto fail;
1305 }
1306 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001307 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001309
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001310 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001311
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001312 if (PyList_Append(peer_alt_names, t) < 0) {
1313 Py_DECREF(t);
1314 goto fail;
1315 }
1316 Py_DECREF(t);
1317 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001318 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 }
1320 BIO_free(biobuf);
1321 if (peer_alt_names != Py_None) {
1322 v = PyList_AsTuple(peer_alt_names);
1323 Py_DECREF(peer_alt_names);
1324 return v;
1325 } else {
1326 return peer_alt_names;
1327 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001328
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001329
1330 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001331 if (biobuf != NULL)
1332 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001333
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 if (peer_alt_names != Py_None) {
1335 Py_XDECREF(peer_alt_names);
1336 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001338 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001339}
1340
1341static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001342_get_aia_uri(X509 *certificate, int nid) {
1343 PyObject *lst = NULL, *ostr = NULL;
1344 int i, result;
1345 AUTHORITY_INFO_ACCESS *info;
1346
1347 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001348 if (info == NULL)
1349 return Py_None;
1350 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1351 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001352 return Py_None;
1353 }
1354
1355 if ((lst = PyList_New(0)) == NULL) {
1356 goto fail;
1357 }
1358
1359 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1360 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1361 ASN1_IA5STRING *uri;
1362
1363 if ((OBJ_obj2nid(ad->method) != nid) ||
1364 (ad->location->type != GEN_URI)) {
1365 continue;
1366 }
1367 uri = ad->location->d.uniformResourceIdentifier;
1368 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1369 uri->length);
1370 if (ostr == NULL) {
1371 goto fail;
1372 }
1373 result = PyList_Append(lst, ostr);
1374 Py_DECREF(ostr);
1375 if (result < 0) {
1376 goto fail;
1377 }
1378 }
1379 AUTHORITY_INFO_ACCESS_free(info);
1380
1381 /* convert to tuple or None */
1382 if (PyList_Size(lst) == 0) {
1383 Py_DECREF(lst);
1384 return Py_None;
1385 } else {
1386 PyObject *tup;
1387 tup = PyList_AsTuple(lst);
1388 Py_DECREF(lst);
1389 return tup;
1390 }
1391
1392 fail:
1393 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001394 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001395 return NULL;
1396}
1397
1398static PyObject *
1399_get_crl_dp(X509 *certificate) {
1400 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001401 int i, j;
1402 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001403
Christian Heimes598894f2016-09-05 23:19:05 +02001404 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001405
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001406 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001407 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001408
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001409 lst = PyList_New(0);
1410 if (lst == NULL)
1411 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001412
1413 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1414 DIST_POINT *dp;
1415 STACK_OF(GENERAL_NAME) *gns;
1416
1417 dp = sk_DIST_POINT_value(dps, i);
1418 gns = dp->distpoint->name.fullname;
1419
1420 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1421 GENERAL_NAME *gn;
1422 ASN1_IA5STRING *uri;
1423 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001424 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001425
1426 gn = sk_GENERAL_NAME_value(gns, j);
1427 if (gn->type != GEN_URI) {
1428 continue;
1429 }
1430 uri = gn->d.uniformResourceIdentifier;
1431 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1432 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001433 if (ouri == NULL)
1434 goto done;
1435
1436 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001437 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001438 if (err < 0)
1439 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001440 }
1441 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001442
1443 /* Convert to tuple. */
1444 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1445
1446 done:
1447 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001448 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001449 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001450}
1451
1452static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001453_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001454
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001455 PyObject *retval = NULL;
1456 BIO *biobuf = NULL;
1457 PyObject *peer;
1458 PyObject *peer_alt_names = NULL;
1459 PyObject *issuer;
1460 PyObject *version;
1461 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001462 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001463 ASN1_INTEGER *serialNumber;
1464 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001465 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 ASN1_TIME *notBefore, *notAfter;
1467 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 retval = PyDict_New();
1470 if (retval == NULL)
1471 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001472
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001473 peer = _create_tuple_for_X509_NAME(
1474 X509_get_subject_name(certificate));
1475 if (peer == NULL)
1476 goto fail0;
1477 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1478 Py_DECREF(peer);
1479 goto fail0;
1480 }
1481 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001482
Antoine Pitroufb046912010-11-09 20:21:19 +00001483 issuer = _create_tuple_for_X509_NAME(
1484 X509_get_issuer_name(certificate));
1485 if (issuer == NULL)
1486 goto fail0;
1487 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001488 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001489 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001490 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001491 Py_DECREF(issuer);
1492
1493 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001494 if (version == NULL)
1495 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001496 if (PyDict_SetItemString(retval, "version", version) < 0) {
1497 Py_DECREF(version);
1498 goto fail0;
1499 }
1500 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001501
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 /* get a memory buffer */
1503 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001504
Antoine Pitroufb046912010-11-09 20:21:19 +00001505 (void) BIO_reset(biobuf);
1506 serialNumber = X509_get_serialNumber(certificate);
1507 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1508 i2a_ASN1_INTEGER(biobuf, serialNumber);
1509 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1510 if (len < 0) {
1511 _setSSLError(NULL, 0, __FILE__, __LINE__);
1512 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001514 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1515 if (sn_obj == NULL)
1516 goto fail1;
1517 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1518 Py_DECREF(sn_obj);
1519 goto fail1;
1520 }
1521 Py_DECREF(sn_obj);
1522
1523 (void) BIO_reset(biobuf);
1524 notBefore = X509_get_notBefore(certificate);
1525 ASN1_TIME_print(biobuf, notBefore);
1526 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1527 if (len < 0) {
1528 _setSSLError(NULL, 0, __FILE__, __LINE__);
1529 goto fail1;
1530 }
1531 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1532 if (pnotBefore == NULL)
1533 goto fail1;
1534 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1535 Py_DECREF(pnotBefore);
1536 goto fail1;
1537 }
1538 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001539
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001540 (void) BIO_reset(biobuf);
1541 notAfter = X509_get_notAfter(certificate);
1542 ASN1_TIME_print(biobuf, notAfter);
1543 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1544 if (len < 0) {
1545 _setSSLError(NULL, 0, __FILE__, __LINE__);
1546 goto fail1;
1547 }
1548 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1549 if (pnotAfter == NULL)
1550 goto fail1;
1551 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1552 Py_DECREF(pnotAfter);
1553 goto fail1;
1554 }
1555 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001558
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 peer_alt_names = _get_peer_alt_names(certificate);
1560 if (peer_alt_names == NULL)
1561 goto fail1;
1562 else if (peer_alt_names != Py_None) {
1563 if (PyDict_SetItemString(retval, "subjectAltName",
1564 peer_alt_names) < 0) {
1565 Py_DECREF(peer_alt_names);
1566 goto fail1;
1567 }
1568 Py_DECREF(peer_alt_names);
1569 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001570
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001571 /* Authority Information Access: OCSP URIs */
1572 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1573 if (obj == NULL) {
1574 goto fail1;
1575 } else if (obj != Py_None) {
1576 result = PyDict_SetItemString(retval, "OCSP", obj);
1577 Py_DECREF(obj);
1578 if (result < 0) {
1579 goto fail1;
1580 }
1581 }
1582
1583 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1584 if (obj == NULL) {
1585 goto fail1;
1586 } else if (obj != Py_None) {
1587 result = PyDict_SetItemString(retval, "caIssuers", obj);
1588 Py_DECREF(obj);
1589 if (result < 0) {
1590 goto fail1;
1591 }
1592 }
1593
1594 /* CDP (CRL distribution points) */
1595 obj = _get_crl_dp(certificate);
1596 if (obj == NULL) {
1597 goto fail1;
1598 } else if (obj != Py_None) {
1599 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1600 Py_DECREF(obj);
1601 if (result < 0) {
1602 goto fail1;
1603 }
1604 }
1605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001606 BIO_free(biobuf);
1607 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001608
1609 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001610 if (biobuf != NULL)
1611 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001612 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 Py_XDECREF(retval);
1614 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001615}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001616
Christian Heimes9a5395a2013-06-17 15:44:12 +02001617static PyObject *
1618_certificate_to_der(X509 *certificate)
1619{
1620 unsigned char *bytes_buf = NULL;
1621 int len;
1622 PyObject *retval;
1623
1624 bytes_buf = NULL;
1625 len = i2d_X509(certificate, &bytes_buf);
1626 if (len < 0) {
1627 _setSSLError(NULL, 0, __FILE__, __LINE__);
1628 return NULL;
1629 }
1630 /* this is actually an immutable bytes sequence */
1631 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1632 OPENSSL_free(bytes_buf);
1633 return retval;
1634}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001635
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001636/*[clinic input]
1637_ssl._test_decode_cert
1638 path: object(converter="PyUnicode_FSConverter")
1639 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001640
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001641[clinic start generated code]*/
1642
1643static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001644_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1645/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001646{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 X509 *x=NULL;
1649 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001650
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001651 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1652 PyErr_SetString(PySSLErrorObject,
1653 "Can't malloc memory to read file");
1654 goto fail0;
1655 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001656
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001657 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001658 PyErr_SetString(PySSLErrorObject,
1659 "Can't open file");
1660 goto fail0;
1661 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001662
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1664 if (x == NULL) {
1665 PyErr_SetString(PySSLErrorObject,
1666 "Error decoding PEM-encoded file");
1667 goto fail0;
1668 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001669
Antoine Pitroufb046912010-11-09 20:21:19 +00001670 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001671 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672
1673 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001674 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001675 if (cert != NULL) BIO_free(cert);
1676 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001677}
1678
1679
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001680/*[clinic input]
1681_ssl._SSLSocket.peer_certificate
1682 der as binary_mode: bool = False
1683 /
1684
1685Returns the certificate for the peer.
1686
1687If no certificate was provided, returns None. If a certificate was
1688provided, but not validated, returns an empty dictionary. Otherwise
1689returns a dict containing information about the peer certificate.
1690
1691If the optional argument is True, returns a DER-encoded copy of the
1692peer certificate, or None if no certificate was provided. This will
1693return the certificate even if it wasn't validated.
1694[clinic start generated code]*/
1695
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001696static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001697_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1698/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001699{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001700 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001701 X509 *peer_cert;
1702 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001703
Christian Heimes66dc33b2017-05-23 16:02:02 -07001704 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001705 PyErr_SetString(PyExc_ValueError,
1706 "handshake not done yet");
1707 return NULL;
1708 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001709 peer_cert = SSL_get_peer_certificate(self->ssl);
1710 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001711 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001712
Antoine Pitrou721738f2012-08-15 23:20:39 +02001713 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001715 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001716 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001717 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001718 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001719 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001720 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001721 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001722 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001723 X509_free(peer_cert);
1724 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001725}
1726
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001727static PyObject *
1728cipher_to_tuple(const SSL_CIPHER *cipher)
1729{
1730 const char *cipher_name, *cipher_protocol;
1731 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 if (retval == NULL)
1733 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001734
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001735 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001737 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001738 PyTuple_SET_ITEM(retval, 0, Py_None);
1739 } else {
1740 v = PyUnicode_FromString(cipher_name);
1741 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001742 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001743 PyTuple_SET_ITEM(retval, 0, v);
1744 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001745
1746 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001747 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001748 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001749 PyTuple_SET_ITEM(retval, 1, Py_None);
1750 } else {
1751 v = PyUnicode_FromString(cipher_protocol);
1752 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001753 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001754 PyTuple_SET_ITEM(retval, 1, v);
1755 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001756
1757 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001758 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001759 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001760 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001761
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001762 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001763
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001764 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001765 Py_DECREF(retval);
1766 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001767}
1768
Christian Heimes25bfcd52016-09-06 00:04:45 +02001769#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1770static PyObject *
1771cipher_to_dict(const SSL_CIPHER *cipher)
1772{
1773 const char *cipher_name, *cipher_protocol;
1774
1775 unsigned long cipher_id;
1776 int alg_bits, strength_bits, len;
1777 char buf[512] = {0};
1778#if OPENSSL_VERSION_1_1
1779 int aead, nid;
1780 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1781#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001782
1783 /* can be NULL */
1784 cipher_name = SSL_CIPHER_get_name(cipher);
1785 cipher_protocol = SSL_CIPHER_get_version(cipher);
1786 cipher_id = SSL_CIPHER_get_id(cipher);
1787 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001788 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1789 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001790 if (len > 1 && buf[len-1] == '\n')
1791 buf[len-1] = '\0';
1792 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1793
1794#if OPENSSL_VERSION_1_1
1795 aead = SSL_CIPHER_is_aead(cipher);
1796 nid = SSL_CIPHER_get_cipher_nid(cipher);
1797 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1798 nid = SSL_CIPHER_get_digest_nid(cipher);
1799 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1800 nid = SSL_CIPHER_get_kx_nid(cipher);
1801 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1802 nid = SSL_CIPHER_get_auth_nid(cipher);
1803 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1804#endif
1805
Victor Stinner410b9882016-09-12 12:00:23 +02001806 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001807 "{sksssssssisi"
1808#if OPENSSL_VERSION_1_1
1809 "sOssssssss"
1810#endif
1811 "}",
1812 "id", cipher_id,
1813 "name", cipher_name,
1814 "protocol", cipher_protocol,
1815 "description", buf,
1816 "strength_bits", strength_bits,
1817 "alg_bits", alg_bits
1818#if OPENSSL_VERSION_1_1
1819 ,"aead", aead ? Py_True : Py_False,
1820 "symmetric", skcipher,
1821 "digest", digest,
1822 "kea", kx,
1823 "auth", auth
1824#endif
1825 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001826}
1827#endif
1828
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001829/*[clinic input]
1830_ssl._SSLSocket.shared_ciphers
1831[clinic start generated code]*/
1832
1833static PyObject *
1834_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1835/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001836{
1837 STACK_OF(SSL_CIPHER) *ciphers;
1838 int i;
1839 PyObject *res;
1840
Christian Heimes598894f2016-09-05 23:19:05 +02001841 ciphers = SSL_get_ciphers(self->ssl);
1842 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001843 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001844 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1845 if (!res)
1846 return NULL;
1847 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1848 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1849 if (!tup) {
1850 Py_DECREF(res);
1851 return NULL;
1852 }
1853 PyList_SET_ITEM(res, i, tup);
1854 }
1855 return res;
1856}
1857
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001858/*[clinic input]
1859_ssl._SSLSocket.cipher
1860[clinic start generated code]*/
1861
1862static PyObject *
1863_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1864/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001865{
1866 const SSL_CIPHER *current;
1867
1868 if (self->ssl == NULL)
1869 Py_RETURN_NONE;
1870 current = SSL_get_current_cipher(self->ssl);
1871 if (current == NULL)
1872 Py_RETURN_NONE;
1873 return cipher_to_tuple(current);
1874}
1875
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001876/*[clinic input]
1877_ssl._SSLSocket.version
1878[clinic start generated code]*/
1879
1880static PyObject *
1881_ssl__SSLSocket_version_impl(PySSLSocket *self)
1882/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001883{
1884 const char *version;
1885
1886 if (self->ssl == NULL)
1887 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001888 if (!SSL_is_init_finished(self->ssl)) {
1889 /* handshake not finished */
1890 Py_RETURN_NONE;
1891 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001892 version = SSL_get_version(self->ssl);
1893 if (!strcmp(version, "unknown"))
1894 Py_RETURN_NONE;
1895 return PyUnicode_FromString(version);
1896}
1897
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001898#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001899/*[clinic input]
1900_ssl._SSLSocket.selected_npn_protocol
1901[clinic start generated code]*/
1902
1903static PyObject *
1904_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1905/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1906{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001907 const unsigned char *out;
1908 unsigned int outlen;
1909
Victor Stinner4569cd52013-06-23 14:58:43 +02001910 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001911 &out, &outlen);
1912
1913 if (out == NULL)
1914 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001915 return PyUnicode_FromStringAndSize((char *)out, outlen);
1916}
1917#endif
1918
1919#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001920/*[clinic input]
1921_ssl._SSLSocket.selected_alpn_protocol
1922[clinic start generated code]*/
1923
1924static PyObject *
1925_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1926/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1927{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001928 const unsigned char *out;
1929 unsigned int outlen;
1930
1931 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1932
1933 if (out == NULL)
1934 Py_RETURN_NONE;
1935 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001936}
1937#endif
1938
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001939/*[clinic input]
1940_ssl._SSLSocket.compression
1941[clinic start generated code]*/
1942
1943static PyObject *
1944_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1945/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1946{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001947#ifdef OPENSSL_NO_COMP
1948 Py_RETURN_NONE;
1949#else
1950 const COMP_METHOD *comp_method;
1951 const char *short_name;
1952
1953 if (self->ssl == NULL)
1954 Py_RETURN_NONE;
1955 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001956 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001957 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001958 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001959 if (short_name == NULL)
1960 Py_RETURN_NONE;
1961 return PyUnicode_DecodeFSDefault(short_name);
1962#endif
1963}
1964
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001965static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1966 Py_INCREF(self->ctx);
1967 return self->ctx;
1968}
1969
1970static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1971 void *closure) {
1972
1973 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001974#if !HAVE_SNI
1975 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1976 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001977 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001978#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001979 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001980 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001981 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001982#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001983 } else {
1984 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1985 return -1;
1986 }
1987
1988 return 0;
1989}
1990
1991PyDoc_STRVAR(PySSL_set_context_doc,
1992"_setter_context(ctx)\n\
1993\
1994This changes the context associated with the SSLSocket. This is typically\n\
1995used from within a callback function set by the set_servername_callback\n\
1996on the SSLContext to change the certificate information associated with the\n\
1997SSLSocket before the cryptographic exchange handshake messages\n");
1998
1999
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002000static PyObject *
2001PySSL_get_server_side(PySSLSocket *self, void *c)
2002{
2003 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2004}
2005
2006PyDoc_STRVAR(PySSL_get_server_side_doc,
2007"Whether this is a server-side socket.");
2008
2009static PyObject *
2010PySSL_get_server_hostname(PySSLSocket *self, void *c)
2011{
2012 if (self->server_hostname == NULL)
2013 Py_RETURN_NONE;
2014 Py_INCREF(self->server_hostname);
2015 return self->server_hostname;
2016}
2017
2018PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2019"The currently set server hostname (for SNI).");
2020
2021static PyObject *
2022PySSL_get_owner(PySSLSocket *self, void *c)
2023{
2024 PyObject *owner;
2025
2026 if (self->owner == NULL)
2027 Py_RETURN_NONE;
2028
2029 owner = PyWeakref_GetObject(self->owner);
2030 Py_INCREF(owner);
2031 return owner;
2032}
2033
2034static int
2035PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2036{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002037 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002038 if (self->owner == NULL)
2039 return -1;
2040 return 0;
2041}
2042
2043PyDoc_STRVAR(PySSL_get_owner_doc,
2044"The Python-level owner of this object.\
2045Passed as \"self\" in servername callback.");
2046
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002047
Antoine Pitrou152efa22010-05-16 18:19:27 +00002048static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002049{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002050 if (self->ssl)
2051 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002053 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002054 Py_XDECREF(self->server_hostname);
2055 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002056 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002057}
2058
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002059/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002060 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002061 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002062 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002063
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002064static int
Victor Stinner14690702015-04-06 22:46:13 +02002065PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002066{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002067 int rc;
2068#ifdef HAVE_POLL
2069 struct pollfd pollfd;
2070 _PyTime_t ms;
2071#else
2072 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002073 fd_set fds;
2074 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002075#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002076
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002078 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002079 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002080 else if (timeout < 0) {
2081 if (s->sock_timeout > 0)
2082 return SOCKET_HAS_TIMED_OUT;
2083 else
2084 return SOCKET_IS_BLOCKING;
2085 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002088 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002089 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002090
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 /* Prefer poll, if available, since you can poll() any fd
2092 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002093#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002094 pollfd.fd = s->sock_fd;
2095 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002096
Victor Stinner14690702015-04-06 22:46:13 +02002097 /* timeout is in seconds, poll() uses milliseconds */
2098 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002099 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002100
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002101 PySSL_BEGIN_ALLOW_THREADS
2102 rc = poll(&pollfd, 1, (int)ms);
2103 PySSL_END_ALLOW_THREADS
2104#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002105 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002106 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002107 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002108
Victor Stinner14690702015-04-06 22:46:13 +02002109 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 FD_ZERO(&fds);
2112 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002113
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002114 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002116 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002117 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002118 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002120 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002121 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002122#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002123
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002124 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2125 (when we are able to write or when there's something to read) */
2126 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002127}
2128
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002129/*[clinic input]
2130_ssl._SSLSocket.write
2131 b: Py_buffer
2132 /
2133
2134Writes the bytes-like object b into the SSL object.
2135
2136Returns the number of bytes written.
2137[clinic start generated code]*/
2138
2139static PyObject *
2140_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2141/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002142{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 int len;
2144 int sockstate;
2145 int err;
2146 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002147 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002148 _PyTime_t timeout, deadline = 0;
2149 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002150
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002151 if (sock != NULL) {
2152 if (((PyObject*)sock) == Py_None) {
2153 _setSSLError("Underlying socket connection gone",
2154 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2155 return NULL;
2156 }
2157 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 }
2159
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002160 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002161 PyErr_Format(PyExc_OverflowError,
2162 "string longer than %d bytes", INT_MAX);
2163 goto error;
2164 }
2165
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002166 if (sock != NULL) {
2167 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002168 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002169 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2170 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2171 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172
Victor Stinner14690702015-04-06 22:46:13 +02002173 timeout = GET_SOCKET_TIMEOUT(sock);
2174 has_timeout = (timeout > 0);
2175 if (has_timeout)
2176 deadline = _PyTime_GetMonotonicClock() + timeout;
2177
2178 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002179 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002180 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 "The write operation timed out");
2182 goto error;
2183 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2184 PyErr_SetString(PySSLErrorObject,
2185 "Underlying socket has been closed.");
2186 goto error;
2187 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2188 PyErr_SetString(PySSLErrorObject,
2189 "Underlying socket too large for select().");
2190 goto error;
2191 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002192
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002194 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002195 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002196 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002197 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002198 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002199
2200 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002201 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002202
Victor Stinner14690702015-04-06 22:46:13 +02002203 if (has_timeout)
2204 timeout = deadline - _PyTime_GetMonotonicClock();
2205
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002207 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002209 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 } else {
2211 sockstate = SOCKET_OPERATION_OK;
2212 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002215 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 "The write operation timed out");
2217 goto error;
2218 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2219 PyErr_SetString(PySSLErrorObject,
2220 "Underlying socket has been closed.");
2221 goto error;
2222 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2223 break;
2224 }
2225 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002226
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002227 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 if (len > 0)
2229 return PyLong_FromLong(len);
2230 else
2231 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002232
2233error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002234 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002235 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002236}
2237
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002238/*[clinic input]
2239_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002240
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002241Returns the number of already decrypted bytes available for read, pending on the connection.
2242[clinic start generated code]*/
2243
2244static PyObject *
2245_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2246/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002247{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 PySSL_BEGIN_ALLOW_THREADS
2251 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002252 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 PySSL_END_ALLOW_THREADS
2254 if (count < 0)
2255 return PySSL_SetError(self, count, __FILE__, __LINE__);
2256 else
2257 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002258}
2259
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002260/*[clinic input]
2261_ssl._SSLSocket.read
2262 size as len: int
2263 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002264 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002265 ]
2266 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002267
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002268Read up to size bytes from the SSL socket.
2269[clinic start generated code]*/
2270
2271static PyObject *
2272_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2273 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002274/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002275{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002278 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 int sockstate;
2280 int err;
2281 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002282 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002283 _PyTime_t timeout, deadline = 0;
2284 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002285
Martin Panter5503d472016-03-27 05:35:19 +00002286 if (!group_right_1 && len < 0) {
2287 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2288 return NULL;
2289 }
2290
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002291 if (sock != NULL) {
2292 if (((PyObject*)sock) == Py_None) {
2293 _setSSLError("Underlying socket connection gone",
2294 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2295 return NULL;
2296 }
2297 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002298 }
2299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002300 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002301 dest = PyBytes_FromStringAndSize(NULL, len);
2302 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002303 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002304 if (len == 0) {
2305 Py_XDECREF(sock);
2306 return dest;
2307 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002308 mem = PyBytes_AS_STRING(dest);
2309 }
2310 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002311 mem = buffer->buf;
2312 if (len <= 0 || len > buffer->len) {
2313 len = (int) buffer->len;
2314 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002315 PyErr_SetString(PyExc_OverflowError,
2316 "maximum length can't fit in a C 'int'");
2317 goto error;
2318 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002319 if (len == 0) {
2320 count = 0;
2321 goto done;
2322 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002323 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002324 }
2325
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002326 if (sock != NULL) {
2327 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002328 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002329 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2330 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2331 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332
Victor Stinner14690702015-04-06 22:46:13 +02002333 timeout = GET_SOCKET_TIMEOUT(sock);
2334 has_timeout = (timeout > 0);
2335 if (has_timeout)
2336 deadline = _PyTime_GetMonotonicClock() + timeout;
2337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 PySSL_BEGIN_ALLOW_THREADS
2340 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002341 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002344 if (PyErr_CheckSignals())
2345 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002346
Victor Stinner14690702015-04-06 22:46:13 +02002347 if (has_timeout)
2348 timeout = deadline - _PyTime_GetMonotonicClock();
2349
Steve Dowere6eb48c2017-09-08 15:16:15 -07002350 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002351 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002352 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002354 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002355 } else if (err == SSL_ERROR_ZERO_RETURN &&
2356 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002357 {
2358 count = 0;
2359 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002360 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002361 else
2362 sockstate = SOCKET_OPERATION_OK;
2363
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002365 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002366 "The read operation timed out");
2367 goto error;
2368 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2369 break;
2370 }
2371 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002373 if (count <= 0) {
2374 PySSL_SetError(self, count, __FILE__, __LINE__);
2375 goto error;
2376 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002377
2378done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002379 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002380 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002381 _PyBytes_Resize(&dest, count);
2382 return dest;
2383 }
2384 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002385 return PyLong_FromLong(count);
2386 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002387
2388error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002389 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002390 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002391 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002392 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002393}
2394
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002395/*[clinic input]
2396_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002397
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002398Does the SSL shutdown handshake with the remote end.
2399
2400Returns the underlying socket object.
2401[clinic start generated code]*/
2402
2403static PyObject *
2404_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2405/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002406{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002407 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002408 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002409 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002410 _PyTime_t timeout, deadline = 0;
2411 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002412
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002413 if (sock != NULL) {
2414 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002415 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002416 _setSSLError("Underlying socket connection gone",
2417 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2418 return NULL;
2419 }
2420 Py_INCREF(sock);
2421
2422 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002423 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002424 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2425 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002427
Victor Stinner14690702015-04-06 22:46:13 +02002428 timeout = GET_SOCKET_TIMEOUT(sock);
2429 has_timeout = (timeout > 0);
2430 if (has_timeout)
2431 deadline = _PyTime_GetMonotonicClock() + timeout;
2432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002433 while (1) {
2434 PySSL_BEGIN_ALLOW_THREADS
2435 /* Disable read-ahead so that unwrap can work correctly.
2436 * Otherwise OpenSSL might read in too much data,
2437 * eating clear text data that happens to be
2438 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002439 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002440 * function is used and the shutdown_seen_zero != 0
2441 * condition is met.
2442 */
2443 if (self->shutdown_seen_zero)
2444 SSL_set_read_ahead(self->ssl, 0);
2445 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002446 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002447 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002448
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002449 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2450 if (err > 0)
2451 break;
2452 if (err == 0) {
2453 /* Don't loop endlessly; instead preserve legacy
2454 behaviour of trying SSL_shutdown() only twice.
2455 This looks necessary for OpenSSL < 0.9.8m */
2456 if (++zeros > 1)
2457 break;
2458 /* Shutdown was sent, now try receiving */
2459 self->shutdown_seen_zero = 1;
2460 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002461 }
2462
Victor Stinner14690702015-04-06 22:46:13 +02002463 if (has_timeout)
2464 timeout = deadline - _PyTime_GetMonotonicClock();
2465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002466 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002467 _PySSL_UPDATE_ERRNO(self, err);
2468 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002469 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002470 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002471 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002472 else
2473 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002474
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002475 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002476 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002477 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002478 "The read operation timed out");
2479 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002480 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002481 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002482 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002483 }
2484 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2485 PyErr_SetString(PySSLErrorObject,
2486 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002487 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002488 }
2489 else if (sockstate != SOCKET_OPERATION_OK)
2490 /* Retain the SSL error code */
2491 break;
2492 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002493
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002494 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002495 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002497 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002498 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002499 /* It's already INCREF'ed */
2500 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002501 else
2502 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002503
2504error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002505 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002506 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002507}
2508
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002509/*[clinic input]
2510_ssl._SSLSocket.tls_unique_cb
2511
2512Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2513
2514If the TLS handshake is not yet complete, None is returned.
2515[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002516
Antoine Pitroud6494802011-07-21 01:11:30 +02002517static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002518_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2519/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002520{
2521 PyObject *retval = NULL;
2522 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002523 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002524
2525 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2526 /* if session is resumed XOR we are the client */
2527 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2528 }
2529 else {
2530 /* if a new session XOR we are the server */
2531 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2532 }
2533
2534 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002535 if (len == 0)
2536 Py_RETURN_NONE;
2537
2538 retval = PyBytes_FromStringAndSize(buf, len);
2539
2540 return retval;
2541}
2542
Christian Heimes99a65702016-09-10 23:44:53 +02002543#ifdef OPENSSL_VERSION_1_1
2544
2545static SSL_SESSION*
2546_ssl_session_dup(SSL_SESSION *session) {
2547 SSL_SESSION *newsession = NULL;
2548 int slen;
2549 unsigned char *senc = NULL, *p;
2550 const unsigned char *const_p;
2551
2552 if (session == NULL) {
2553 PyErr_SetString(PyExc_ValueError, "Invalid session");
2554 goto error;
2555 }
2556
2557 /* get length */
2558 slen = i2d_SSL_SESSION(session, NULL);
2559 if (slen == 0 || slen > 0xFF00) {
2560 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2561 goto error;
2562 }
2563 if ((senc = PyMem_Malloc(slen)) == NULL) {
2564 PyErr_NoMemory();
2565 goto error;
2566 }
2567 p = senc;
2568 if (!i2d_SSL_SESSION(session, &p)) {
2569 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2570 goto error;
2571 }
2572 const_p = senc;
2573 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2574 if (session == NULL) {
2575 goto error;
2576 }
2577 PyMem_Free(senc);
2578 return newsession;
2579 error:
2580 if (senc != NULL) {
2581 PyMem_Free(senc);
2582 }
2583 return NULL;
2584}
2585#endif
2586
2587static PyObject *
2588PySSL_get_session(PySSLSocket *self, void *closure) {
2589 /* get_session can return sessions from a server-side connection,
2590 * it does not check for handshake done or client socket. */
2591 PySSLSession *pysess;
2592 SSL_SESSION *session;
2593
2594#ifdef OPENSSL_VERSION_1_1
2595 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2596 * https://github.com/openssl/openssl/issues/1550 */
2597 session = SSL_get0_session(self->ssl); /* borrowed reference */
2598 if (session == NULL) {
2599 Py_RETURN_NONE;
2600 }
2601 if ((session = _ssl_session_dup(session)) == NULL) {
2602 return NULL;
2603 }
2604#else
2605 session = SSL_get1_session(self->ssl);
2606 if (session == NULL) {
2607 Py_RETURN_NONE;
2608 }
2609#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002610 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002611 if (pysess == NULL) {
2612 SSL_SESSION_free(session);
2613 return NULL;
2614 }
2615
2616 assert(self->ctx);
2617 pysess->ctx = self->ctx;
2618 Py_INCREF(pysess->ctx);
2619 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002620 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002621 return (PyObject *)pysess;
2622}
2623
2624static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2625 void *closure)
2626 {
2627 PySSLSession *pysess;
2628#ifdef OPENSSL_VERSION_1_1
2629 SSL_SESSION *session;
2630#endif
2631 int result;
2632
2633 if (!PySSLSession_Check(value)) {
2634 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2635 return -1;
2636 }
2637 pysess = (PySSLSession *)value;
2638
2639 if (self->ctx->ctx != pysess->ctx->ctx) {
2640 PyErr_SetString(PyExc_ValueError,
2641 "Session refers to a different SSLContext.");
2642 return -1;
2643 }
2644 if (self->socket_type != PY_SSL_CLIENT) {
2645 PyErr_SetString(PyExc_ValueError,
2646 "Cannot set session for server-side SSLSocket.");
2647 return -1;
2648 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002649 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002650 PyErr_SetString(PyExc_ValueError,
2651 "Cannot set session after handshake.");
2652 return -1;
2653 }
2654#ifdef OPENSSL_VERSION_1_1
2655 /* duplicate session */
2656 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2657 return -1;
2658 }
2659 result = SSL_set_session(self->ssl, session);
2660 /* free duplicate, SSL_set_session() bumps ref count */
2661 SSL_SESSION_free(session);
2662#else
2663 result = SSL_set_session(self->ssl, pysess->session);
2664#endif
2665 if (result == 0) {
2666 _setSSLError(NULL, 0, __FILE__, __LINE__);
2667 return -1;
2668 }
2669 return 0;
2670}
2671
2672PyDoc_STRVAR(PySSL_set_session_doc,
2673"_setter_session(session)\n\
2674\
2675Get / set SSLSession.");
2676
2677static PyObject *
2678PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2679 if (SSL_session_reused(self->ssl)) {
2680 Py_RETURN_TRUE;
2681 } else {
2682 Py_RETURN_FALSE;
2683 }
2684}
2685
2686PyDoc_STRVAR(PySSL_get_session_reused_doc,
2687"Was the client session reused during handshake?");
2688
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002689static PyGetSetDef ssl_getsetlist[] = {
2690 {"context", (getter) PySSL_get_context,
2691 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002692 {"server_side", (getter) PySSL_get_server_side, NULL,
2693 PySSL_get_server_side_doc},
2694 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2695 PySSL_get_server_hostname_doc},
2696 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2697 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002698 {"session", (getter) PySSL_get_session,
2699 (setter) PySSL_set_session, PySSL_set_session_doc},
2700 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2701 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002702 {NULL}, /* sentinel */
2703};
2704
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002705static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002706 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2707 _SSL__SSLSOCKET_WRITE_METHODDEF
2708 _SSL__SSLSOCKET_READ_METHODDEF
2709 _SSL__SSLSOCKET_PENDING_METHODDEF
2710 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2711 _SSL__SSLSOCKET_CIPHER_METHODDEF
2712 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2713 _SSL__SSLSOCKET_VERSION_METHODDEF
2714 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2715 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2716 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2717 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2718 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002719 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002720};
2721
Antoine Pitrou152efa22010-05-16 18:19:27 +00002722static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002723 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002724 "_ssl._SSLSocket", /*tp_name*/
2725 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002726 0, /*tp_itemsize*/
2727 /* methods */
2728 (destructor)PySSL_dealloc, /*tp_dealloc*/
2729 0, /*tp_print*/
2730 0, /*tp_getattr*/
2731 0, /*tp_setattr*/
2732 0, /*tp_reserved*/
2733 0, /*tp_repr*/
2734 0, /*tp_as_number*/
2735 0, /*tp_as_sequence*/
2736 0, /*tp_as_mapping*/
2737 0, /*tp_hash*/
2738 0, /*tp_call*/
2739 0, /*tp_str*/
2740 0, /*tp_getattro*/
2741 0, /*tp_setattro*/
2742 0, /*tp_as_buffer*/
2743 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2744 0, /*tp_doc*/
2745 0, /*tp_traverse*/
2746 0, /*tp_clear*/
2747 0, /*tp_richcompare*/
2748 0, /*tp_weaklistoffset*/
2749 0, /*tp_iter*/
2750 0, /*tp_iternext*/
2751 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002752 0, /*tp_members*/
2753 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002754};
2755
Antoine Pitrou152efa22010-05-16 18:19:27 +00002756
2757/*
2758 * _SSLContext objects
2759 */
2760
Christian Heimes5fe668c2016-09-12 00:01:11 +02002761static int
2762_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2763{
2764 int mode;
2765 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2766
2767 switch(n) {
2768 case PY_SSL_CERT_NONE:
2769 mode = SSL_VERIFY_NONE;
2770 break;
2771 case PY_SSL_CERT_OPTIONAL:
2772 mode = SSL_VERIFY_PEER;
2773 break;
2774 case PY_SSL_CERT_REQUIRED:
2775 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2776 break;
2777 default:
2778 PyErr_SetString(PyExc_ValueError,
2779 "invalid value for verify_mode");
2780 return -1;
2781 }
2782 /* keep current verify cb */
2783 verify_cb = SSL_CTX_get_verify_callback(ctx);
2784 SSL_CTX_set_verify(ctx, mode, verify_cb);
2785 return 0;
2786}
2787
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002788/*[clinic input]
2789@classmethod
2790_ssl._SSLContext.__new__
2791 protocol as proto_version: int
2792 /
2793[clinic start generated code]*/
2794
Antoine Pitrou152efa22010-05-16 18:19:27 +00002795static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002796_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2797/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002798{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002799 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002800 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002801 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002802 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002803 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002804#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002805 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002806#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807
Antoine Pitrou152efa22010-05-16 18:19:27 +00002808 PySSL_BEGIN_ALLOW_THREADS
2809 if (proto_version == PY_SSL_VERSION_TLS1)
2810 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002811#if HAVE_TLSv1_2
2812 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2813 ctx = SSL_CTX_new(TLSv1_1_method());
2814 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2815 ctx = SSL_CTX_new(TLSv1_2_method());
2816#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002817#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002818 else if (proto_version == PY_SSL_VERSION_SSL3)
2819 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002820#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002821#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002822 else if (proto_version == PY_SSL_VERSION_SSL2)
2823 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002824#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002825 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002826 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002827 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2828 ctx = SSL_CTX_new(TLS_client_method());
2829 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2830 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002831 else
2832 proto_version = -1;
2833 PySSL_END_ALLOW_THREADS
2834
2835 if (proto_version == -1) {
2836 PyErr_SetString(PyExc_ValueError,
2837 "invalid protocol version");
2838 return NULL;
2839 }
2840 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002841 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002842 return NULL;
2843 }
2844
2845 assert(type != NULL && type->tp_alloc != NULL);
2846 self = (PySSLContext *) type->tp_alloc(type, 0);
2847 if (self == NULL) {
2848 SSL_CTX_free(ctx);
2849 return NULL;
2850 }
2851 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002852 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002853#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002854 self->npn_protocols = NULL;
2855#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002856#ifdef HAVE_ALPN
2857 self->alpn_protocols = NULL;
2858#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002859#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002860 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002861#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002862 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002863 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2864 self->check_hostname = 1;
2865 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2866 Py_DECREF(self);
2867 return NULL;
2868 }
2869 } else {
2870 self->check_hostname = 0;
2871 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2872 Py_DECREF(self);
2873 return NULL;
2874 }
2875 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002876 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002877 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2878 if (proto_version != PY_SSL_VERSION_SSL2)
2879 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002880 if (proto_version != PY_SSL_VERSION_SSL3)
2881 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002882 /* Minimal security flags for server and client side context.
2883 * Client sockets ignore server-side parameters. */
2884#ifdef SSL_OP_NO_COMPRESSION
2885 options |= SSL_OP_NO_COMPRESSION;
2886#endif
2887#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2888 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2889#endif
2890#ifdef SSL_OP_SINGLE_DH_USE
2891 options |= SSL_OP_SINGLE_DH_USE;
2892#endif
2893#ifdef SSL_OP_SINGLE_ECDH_USE
2894 options |= SSL_OP_SINGLE_ECDH_USE;
2895#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002896 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897
Semen Zhydenko1295e112017-10-15 21:28:31 +02002898 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002899 * It's far from perfect but gives users a better head start. */
2900 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002901#if PY_SSL_DEFAULT_CIPHERS == 2
2902 /* stick to OpenSSL's default settings */
2903 result = 1;
2904#else
2905 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2906#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002907 } else {
2908 /* SSLv2 needs MD5 */
2909 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2910 }
2911 if (result == 0) {
2912 Py_DECREF(self);
2913 ERR_clear_error();
2914 PyErr_SetString(PySSLErrorObject,
2915 "No cipher can be selected.");
2916 return NULL;
2917 }
2918
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002919#if defined(SSL_MODE_RELEASE_BUFFERS)
2920 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2921 usage for no cost at all. However, don't do this for OpenSSL versions
2922 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2923 2014-0198. I can't find exactly which beta fixed this CVE, so be
2924 conservative and assume it wasn't fixed until release. We do this check
2925 at runtime to avoid problems from the dynamic linker.
2926 See #25672 for more on this. */
2927 libver = SSLeay();
2928 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2929 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2930 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2931 }
2932#endif
2933
2934
Donald Stufft8ae264c2017-03-02 11:45:29 -05002935#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002936 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2937 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002938 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2939 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002940#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002941 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2942#else
2943 {
2944 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2945 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2946 EC_KEY_free(key);
2947 }
2948#endif
2949#endif
2950
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002951#define SID_CTX "Python"
2952 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2953 sizeof(SID_CTX));
2954#undef SID_CTX
2955
Christian Heimes61d478c2018-01-27 15:51:38 +01002956 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002957#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01002958 /* Improve trust chain building when cross-signed intermediate
2959 certificates are present. See https://bugs.python.org/issue23476. */
2960 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002961#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01002962 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002963
Antoine Pitrou152efa22010-05-16 18:19:27 +00002964 return (PyObject *)self;
2965}
2966
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002967static int
2968context_traverse(PySSLContext *self, visitproc visit, void *arg)
2969{
2970#ifndef OPENSSL_NO_TLSEXT
2971 Py_VISIT(self->set_hostname);
2972#endif
2973 return 0;
2974}
2975
2976static int
2977context_clear(PySSLContext *self)
2978{
2979#ifndef OPENSSL_NO_TLSEXT
2980 Py_CLEAR(self->set_hostname);
2981#endif
2982 return 0;
2983}
2984
Antoine Pitrou152efa22010-05-16 18:19:27 +00002985static void
2986context_dealloc(PySSLContext *self)
2987{
INADA Naokia6296d32017-08-24 14:55:17 +09002988 /* bpo-31095: UnTrack is needed before calling any callbacks */
2989 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002990 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002991 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002992#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002993 PyMem_FREE(self->npn_protocols);
2994#endif
2995#ifdef HAVE_ALPN
2996 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002997#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002998 Py_TYPE(self)->tp_free(self);
2999}
3000
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003001/*[clinic input]
3002_ssl._SSLContext.set_ciphers
3003 cipherlist: str
3004 /
3005[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003006
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003007static PyObject *
3008_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3009/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3010{
3011 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003012 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003013 /* Clearing the error queue is necessary on some OpenSSL versions,
3014 otherwise the error will be reported again when another SSL call
3015 is done. */
3016 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003017 PyErr_SetString(PySSLErrorObject,
3018 "No cipher can be selected.");
3019 return NULL;
3020 }
3021 Py_RETURN_NONE;
3022}
3023
Christian Heimes25bfcd52016-09-06 00:04:45 +02003024#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3025/*[clinic input]
3026_ssl._SSLContext.get_ciphers
3027[clinic start generated code]*/
3028
3029static PyObject *
3030_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3031/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3032{
3033 SSL *ssl = NULL;
3034 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003035 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003036 int i=0;
3037 PyObject *result = NULL, *dct;
3038
3039 ssl = SSL_new(self->ctx);
3040 if (ssl == NULL) {
3041 _setSSLError(NULL, 0, __FILE__, __LINE__);
3042 goto exit;
3043 }
3044 sk = SSL_get_ciphers(ssl);
3045
3046 result = PyList_New(sk_SSL_CIPHER_num(sk));
3047 if (result == NULL) {
3048 goto exit;
3049 }
3050
3051 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3052 cipher = sk_SSL_CIPHER_value(sk, i);
3053 dct = cipher_to_dict(cipher);
3054 if (dct == NULL) {
3055 Py_CLEAR(result);
3056 goto exit;
3057 }
3058 PyList_SET_ITEM(result, i, dct);
3059 }
3060
3061 exit:
3062 if (ssl != NULL)
3063 SSL_free(ssl);
3064 return result;
3065
3066}
3067#endif
3068
3069
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003070#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003071static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003072do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3073 const unsigned char *server_protocols, unsigned int server_protocols_len,
3074 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003075{
Benjamin Peterson88615022015-01-23 17:30:26 -05003076 int ret;
3077 if (client_protocols == NULL) {
3078 client_protocols = (unsigned char *)"";
3079 client_protocols_len = 0;
3080 }
3081 if (server_protocols == NULL) {
3082 server_protocols = (unsigned char *)"";
3083 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003084 }
3085
Benjamin Peterson88615022015-01-23 17:30:26 -05003086 ret = SSL_select_next_proto(out, outlen,
3087 server_protocols, server_protocols_len,
3088 client_protocols, client_protocols_len);
3089 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3090 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003091
3092 return SSL_TLSEXT_ERR_OK;
3093}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003094#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003095
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003096#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003097/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3098static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003099_advertiseNPN_cb(SSL *s,
3100 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003101 void *args)
3102{
3103 PySSLContext *ssl_ctx = (PySSLContext *) args;
3104
3105 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003106 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003107 *len = 0;
3108 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003109 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003110 *len = ssl_ctx->npn_protocols_len;
3111 }
3112
3113 return SSL_TLSEXT_ERR_OK;
3114}
3115/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3116static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003117_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003118 unsigned char **out, unsigned char *outlen,
3119 const unsigned char *server, unsigned int server_len,
3120 void *args)
3121{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003122 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003123 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003124 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003125}
3126#endif
3127
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003128/*[clinic input]
3129_ssl._SSLContext._set_npn_protocols
3130 protos: Py_buffer
3131 /
3132[clinic start generated code]*/
3133
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003134static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003135_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3136 Py_buffer *protos)
3137/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003138{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003139#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003140 PyMem_Free(self->npn_protocols);
3141 self->npn_protocols = PyMem_Malloc(protos->len);
3142 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003143 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003144 memcpy(self->npn_protocols, protos->buf, protos->len);
3145 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003146
3147 /* set both server and client callbacks, because the context can
3148 * be used to create both types of sockets */
3149 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3150 _advertiseNPN_cb,
3151 self);
3152 SSL_CTX_set_next_proto_select_cb(self->ctx,
3153 _selectNPN_cb,
3154 self);
3155
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003156 Py_RETURN_NONE;
3157#else
3158 PyErr_SetString(PyExc_NotImplementedError,
3159 "The NPN extension requires OpenSSL 1.0.1 or later.");
3160 return NULL;
3161#endif
3162}
3163
Benjamin Petersoncca27322015-01-23 16:35:37 -05003164#ifdef HAVE_ALPN
3165static int
3166_selectALPN_cb(SSL *s,
3167 const unsigned char **out, unsigned char *outlen,
3168 const unsigned char *client_protocols, unsigned int client_protocols_len,
3169 void *args)
3170{
3171 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003172 return do_protocol_selection(1, (unsigned char **)out, outlen,
3173 ctx->alpn_protocols, ctx->alpn_protocols_len,
3174 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003175}
3176#endif
3177
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003178/*[clinic input]
3179_ssl._SSLContext._set_alpn_protocols
3180 protos: Py_buffer
3181 /
3182[clinic start generated code]*/
3183
Benjamin Petersoncca27322015-01-23 16:35:37 -05003184static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003185_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3186 Py_buffer *protos)
3187/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003188{
3189#ifdef HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003190 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003191 PyErr_Format(PyExc_OverflowError,
3192 "protocols longer than %d bytes", UINT_MAX);
3193 return NULL;
3194 }
3195
Benjamin Petersoncca27322015-01-23 16:35:37 -05003196 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003197 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003198 if (!self->alpn_protocols)
3199 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003200 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003201 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003202
3203 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3204 return PyErr_NoMemory();
3205 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3206
Benjamin Petersoncca27322015-01-23 16:35:37 -05003207 Py_RETURN_NONE;
3208#else
3209 PyErr_SetString(PyExc_NotImplementedError,
3210 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3211 return NULL;
3212#endif
3213}
3214
Antoine Pitrou152efa22010-05-16 18:19:27 +00003215static PyObject *
3216get_verify_mode(PySSLContext *self, void *c)
3217{
3218 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3219 case SSL_VERIFY_NONE:
3220 return PyLong_FromLong(PY_SSL_CERT_NONE);
3221 case SSL_VERIFY_PEER:
3222 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3223 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3224 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3225 }
3226 PyErr_SetString(PySSLErrorObject,
3227 "invalid return value from SSL_CTX_get_verify_mode");
3228 return NULL;
3229}
3230
3231static int
3232set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3233{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003234 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003235 if (!PyArg_Parse(arg, "i", &n))
3236 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003237 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003238 PyErr_SetString(PyExc_ValueError,
3239 "Cannot set verify_mode to CERT_NONE when "
3240 "check_hostname is enabled.");
3241 return -1;
3242 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003243 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003244}
3245
3246static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003247get_verify_flags(PySSLContext *self, void *c)
3248{
Christian Heimes598894f2016-09-05 23:19:05 +02003249 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003250 unsigned long flags;
3251
Christian Heimes61d478c2018-01-27 15:51:38 +01003252 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003253 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003254 return PyLong_FromUnsignedLong(flags);
3255}
3256
3257static int
3258set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3259{
Christian Heimes598894f2016-09-05 23:19:05 +02003260 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003261 unsigned long new_flags, flags, set, clear;
3262
3263 if (!PyArg_Parse(arg, "k", &new_flags))
3264 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003265 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003266 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003267 clear = flags & ~new_flags;
3268 set = ~flags & new_flags;
3269 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003270 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003271 _setSSLError(NULL, 0, __FILE__, __LINE__);
3272 return -1;
3273 }
3274 }
3275 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003276 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003277 _setSSLError(NULL, 0, __FILE__, __LINE__);
3278 return -1;
3279 }
3280 }
3281 return 0;
3282}
3283
3284static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003285get_options(PySSLContext *self, void *c)
3286{
3287 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3288}
3289
3290static int
3291set_options(PySSLContext *self, PyObject *arg, void *c)
3292{
3293 long new_opts, opts, set, clear;
3294 if (!PyArg_Parse(arg, "l", &new_opts))
3295 return -1;
3296 opts = SSL_CTX_get_options(self->ctx);
3297 clear = opts & ~new_opts;
3298 set = ~opts & new_opts;
3299 if (clear) {
3300#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3301 SSL_CTX_clear_options(self->ctx, clear);
3302#else
3303 PyErr_SetString(PyExc_ValueError,
3304 "can't clear options before OpenSSL 0.9.8m");
3305 return -1;
3306#endif
3307 }
3308 if (set)
3309 SSL_CTX_set_options(self->ctx, set);
3310 return 0;
3311}
3312
Christian Heimes1aa9a752013-12-02 02:41:19 +01003313static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003314get_host_flags(PySSLContext *self, void *c)
3315{
3316 return PyLong_FromUnsignedLong(self->hostflags);
3317}
3318
3319static int
3320set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3321{
3322 X509_VERIFY_PARAM *param;
3323 unsigned int new_flags = 0;
3324
3325 if (!PyArg_Parse(arg, "I", &new_flags))
3326 return -1;
3327
3328 param = SSL_CTX_get0_param(self->ctx);
3329 self->hostflags = new_flags;
3330 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3331 return 0;
3332}
3333
3334static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003335get_check_hostname(PySSLContext *self, void *c)
3336{
3337 return PyBool_FromLong(self->check_hostname);
3338}
3339
3340static int
3341set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3342{
3343 int check_hostname;
3344 if (!PyArg_Parse(arg, "p", &check_hostname))
3345 return -1;
3346 if (check_hostname &&
3347 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003348 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3349 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3350 return -1;
3351 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003352 }
3353 self->check_hostname = check_hostname;
3354 return 0;
3355}
3356
3357
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003358typedef struct {
3359 PyThreadState *thread_state;
3360 PyObject *callable;
3361 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003362 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003363 int error;
3364} _PySSLPasswordInfo;
3365
3366static int
3367_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3368 const char *bad_type_error)
3369{
3370 /* Set the password and size fields of a _PySSLPasswordInfo struct
3371 from a unicode, bytes, or byte array object.
3372 The password field will be dynamically allocated and must be freed
3373 by the caller */
3374 PyObject *password_bytes = NULL;
3375 const char *data = NULL;
3376 Py_ssize_t size;
3377
3378 if (PyUnicode_Check(password)) {
3379 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3380 if (!password_bytes) {
3381 goto error;
3382 }
3383 data = PyBytes_AS_STRING(password_bytes);
3384 size = PyBytes_GET_SIZE(password_bytes);
3385 } else if (PyBytes_Check(password)) {
3386 data = PyBytes_AS_STRING(password);
3387 size = PyBytes_GET_SIZE(password);
3388 } else if (PyByteArray_Check(password)) {
3389 data = PyByteArray_AS_STRING(password);
3390 size = PyByteArray_GET_SIZE(password);
3391 } else {
3392 PyErr_SetString(PyExc_TypeError, bad_type_error);
3393 goto error;
3394 }
3395
Victor Stinner9ee02032013-06-23 15:08:23 +02003396 if (size > (Py_ssize_t)INT_MAX) {
3397 PyErr_Format(PyExc_ValueError,
3398 "password cannot be longer than %d bytes", INT_MAX);
3399 goto error;
3400 }
3401
Victor Stinner11ebff22013-07-07 17:07:52 +02003402 PyMem_Free(pw_info->password);
3403 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003404 if (!pw_info->password) {
3405 PyErr_SetString(PyExc_MemoryError,
3406 "unable to allocate password buffer");
3407 goto error;
3408 }
3409 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003410 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003411
3412 Py_XDECREF(password_bytes);
3413 return 1;
3414
3415error:
3416 Py_XDECREF(password_bytes);
3417 return 0;
3418}
3419
3420static int
3421_password_callback(char *buf, int size, int rwflag, void *userdata)
3422{
3423 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3424 PyObject *fn_ret = NULL;
3425
3426 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3427
3428 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003429 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003430 if (!fn_ret) {
3431 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3432 core python API, so we could use it to add a frame here */
3433 goto error;
3434 }
3435
3436 if (!_pwinfo_set(pw_info, fn_ret,
3437 "password callback must return a string")) {
3438 goto error;
3439 }
3440 Py_CLEAR(fn_ret);
3441 }
3442
3443 if (pw_info->size > size) {
3444 PyErr_Format(PyExc_ValueError,
3445 "password cannot be longer than %d bytes", size);
3446 goto error;
3447 }
3448
3449 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3450 memcpy(buf, pw_info->password, pw_info->size);
3451 return pw_info->size;
3452
3453error:
3454 Py_XDECREF(fn_ret);
3455 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3456 pw_info->error = 1;
3457 return -1;
3458}
3459
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003460/*[clinic input]
3461_ssl._SSLContext.load_cert_chain
3462 certfile: object
3463 keyfile: object = NULL
3464 password: object = NULL
3465
3466[clinic start generated code]*/
3467
Antoine Pitroub5218772010-05-21 09:56:06 +00003468static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003469_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3470 PyObject *keyfile, PyObject *password)
3471/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003472{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003473 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003474 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3475 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003476 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003477 int r;
3478
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003479 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003480 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003481 if (keyfile == Py_None)
3482 keyfile = NULL;
3483 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3484 PyErr_SetString(PyExc_TypeError,
3485 "certfile should be a valid filesystem path");
3486 return NULL;
3487 }
3488 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3489 PyErr_SetString(PyExc_TypeError,
3490 "keyfile should be a valid filesystem path");
3491 goto error;
3492 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003493 if (password && password != Py_None) {
3494 if (PyCallable_Check(password)) {
3495 pw_info.callable = password;
3496 } else if (!_pwinfo_set(&pw_info, password,
3497 "password should be a string or callable")) {
3498 goto error;
3499 }
3500 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3501 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3502 }
3503 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003504 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3505 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003506 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003507 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003508 if (pw_info.error) {
3509 ERR_clear_error();
3510 /* the password callback has already set the error information */
3511 }
3512 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003513 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003514 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003515 }
3516 else {
3517 _setSSLError(NULL, 0, __FILE__, __LINE__);
3518 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003519 goto error;
3520 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003521 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003522 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003523 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3524 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003525 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3526 Py_CLEAR(keyfile_bytes);
3527 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003528 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003529 if (pw_info.error) {
3530 ERR_clear_error();
3531 /* the password callback has already set the error information */
3532 }
3533 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003534 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003535 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003536 }
3537 else {
3538 _setSSLError(NULL, 0, __FILE__, __LINE__);
3539 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003540 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003541 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003542 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003543 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003544 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545 if (r != 1) {
3546 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003547 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003548 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003549 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3550 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003551 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003552 Py_RETURN_NONE;
3553
3554error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003555 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3556 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003557 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003558 Py_XDECREF(keyfile_bytes);
3559 Py_XDECREF(certfile_bytes);
3560 return NULL;
3561}
3562
Christian Heimesefff7062013-11-21 03:35:02 +01003563/* internal helper function, returns -1 on error
3564 */
3565static int
3566_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3567 int filetype)
3568{
3569 BIO *biobuf = NULL;
3570 X509_STORE *store;
3571 int retval = 0, err, loaded = 0;
3572
3573 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3574
3575 if (len <= 0) {
3576 PyErr_SetString(PyExc_ValueError,
3577 "Empty certificate data");
3578 return -1;
3579 } else if (len > INT_MAX) {
3580 PyErr_SetString(PyExc_OverflowError,
3581 "Certificate data is too long.");
3582 return -1;
3583 }
3584
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003585 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003586 if (biobuf == NULL) {
3587 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3588 return -1;
3589 }
3590
3591 store = SSL_CTX_get_cert_store(self->ctx);
3592 assert(store != NULL);
3593
3594 while (1) {
3595 X509 *cert = NULL;
3596 int r;
3597
3598 if (filetype == SSL_FILETYPE_ASN1) {
3599 cert = d2i_X509_bio(biobuf, NULL);
3600 } else {
3601 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003602 SSL_CTX_get_default_passwd_cb(self->ctx),
3603 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3604 );
Christian Heimesefff7062013-11-21 03:35:02 +01003605 }
3606 if (cert == NULL) {
3607 break;
3608 }
3609 r = X509_STORE_add_cert(store, cert);
3610 X509_free(cert);
3611 if (!r) {
3612 err = ERR_peek_last_error();
3613 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3614 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3615 /* cert already in hash table, not an error */
3616 ERR_clear_error();
3617 } else {
3618 break;
3619 }
3620 }
3621 loaded++;
3622 }
3623
3624 err = ERR_peek_last_error();
3625 if ((filetype == SSL_FILETYPE_ASN1) &&
3626 (loaded > 0) &&
3627 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3628 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3629 /* EOF ASN1 file, not an error */
3630 ERR_clear_error();
3631 retval = 0;
3632 } else if ((filetype == SSL_FILETYPE_PEM) &&
3633 (loaded > 0) &&
3634 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3635 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3636 /* EOF PEM file, not an error */
3637 ERR_clear_error();
3638 retval = 0;
3639 } else {
3640 _setSSLError(NULL, 0, __FILE__, __LINE__);
3641 retval = -1;
3642 }
3643
3644 BIO_free(biobuf);
3645 return retval;
3646}
3647
3648
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003649/*[clinic input]
3650_ssl._SSLContext.load_verify_locations
3651 cafile: object = NULL
3652 capath: object = NULL
3653 cadata: object = NULL
3654
3655[clinic start generated code]*/
3656
Antoine Pitrou152efa22010-05-16 18:19:27 +00003657static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003658_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3659 PyObject *cafile,
3660 PyObject *capath,
3661 PyObject *cadata)
3662/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003663{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003664 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3665 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003666 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003667
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003668 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003669 if (cafile == Py_None)
3670 cafile = NULL;
3671 if (capath == Py_None)
3672 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003673 if (cadata == Py_None)
3674 cadata = NULL;
3675
3676 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003677 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003678 "cafile, capath and cadata cannot be all omitted");
3679 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003680 }
3681 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3682 PyErr_SetString(PyExc_TypeError,
3683 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003684 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003685 }
3686 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003687 PyErr_SetString(PyExc_TypeError,
3688 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003689 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003690 }
Christian Heimesefff7062013-11-21 03:35:02 +01003691
3692 /* validata cadata type and load cadata */
3693 if (cadata) {
3694 Py_buffer buf;
3695 PyObject *cadata_ascii = NULL;
3696
3697 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3698 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3699 PyBuffer_Release(&buf);
3700 PyErr_SetString(PyExc_TypeError,
3701 "cadata should be a contiguous buffer with "
3702 "a single dimension");
3703 goto error;
3704 }
3705 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3706 PyBuffer_Release(&buf);
3707 if (r == -1) {
3708 goto error;
3709 }
3710 } else {
3711 PyErr_Clear();
3712 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3713 if (cadata_ascii == NULL) {
3714 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003715 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003716 "bytes-like object");
3717 goto error;
3718 }
3719 r = _add_ca_certs(self,
3720 PyBytes_AS_STRING(cadata_ascii),
3721 PyBytes_GET_SIZE(cadata_ascii),
3722 SSL_FILETYPE_PEM);
3723 Py_DECREF(cadata_ascii);
3724 if (r == -1) {
3725 goto error;
3726 }
3727 }
3728 }
3729
3730 /* load cafile or capath */
3731 if (cafile || capath) {
3732 if (cafile)
3733 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3734 if (capath)
3735 capath_buf = PyBytes_AS_STRING(capath_bytes);
3736 PySSL_BEGIN_ALLOW_THREADS
3737 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3738 PySSL_END_ALLOW_THREADS
3739 if (r != 1) {
3740 ok = 0;
3741 if (errno != 0) {
3742 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003743 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003744 }
3745 else {
3746 _setSSLError(NULL, 0, __FILE__, __LINE__);
3747 }
3748 goto error;
3749 }
3750 }
3751 goto end;
3752
3753 error:
3754 ok = 0;
3755 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003756 Py_XDECREF(cafile_bytes);
3757 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003758 if (ok) {
3759 Py_RETURN_NONE;
3760 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003761 return NULL;
3762 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003763}
3764
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003765/*[clinic input]
3766_ssl._SSLContext.load_dh_params
3767 path as filepath: object
3768 /
3769
3770[clinic start generated code]*/
3771
Antoine Pitrou152efa22010-05-16 18:19:27 +00003772static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003773_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3774/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003775{
3776 FILE *f;
3777 DH *dh;
3778
Victor Stinnerdaf45552013-08-28 00:53:59 +02003779 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003780 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003781 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003782
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003783 errno = 0;
3784 PySSL_BEGIN_ALLOW_THREADS
3785 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003786 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003787 PySSL_END_ALLOW_THREADS
3788 if (dh == NULL) {
3789 if (errno != 0) {
3790 ERR_clear_error();
3791 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3792 }
3793 else {
3794 _setSSLError(NULL, 0, __FILE__, __LINE__);
3795 }
3796 return NULL;
3797 }
3798 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3799 _setSSLError(NULL, 0, __FILE__, __LINE__);
3800 DH_free(dh);
3801 Py_RETURN_NONE;
3802}
3803
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003804/*[clinic input]
3805_ssl._SSLContext._wrap_socket
3806 sock: object(subclass_of="PySocketModule.Sock_Type")
3807 server_side: int
3808 server_hostname as hostname_obj: object = None
3809
3810[clinic start generated code]*/
3811
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003812static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003813_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3814 int server_side, PyObject *hostname_obj)
3815/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003816{
Antoine Pitroud5323212010-10-22 18:19:07 +00003817 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003818 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003819
Antoine Pitroud5323212010-10-22 18:19:07 +00003820 /* server_hostname is either None (or absent), or to be encoded
3821 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003822 if (hostname_obj != Py_None) {
3823 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003824 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003825 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003826
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003827 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3828 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003829 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003830 if (hostname != NULL)
3831 PyMem_Free(hostname);
3832 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003833}
3834
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003835/*[clinic input]
3836_ssl._SSLContext._wrap_bio
3837 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3838 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3839 server_side: int
3840 server_hostname as hostname_obj: object = None
3841
3842[clinic start generated code]*/
3843
Antoine Pitroub0182c82010-10-12 20:09:02 +00003844static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003845_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3846 PySSLMemoryBIO *outgoing, int server_side,
3847 PyObject *hostname_obj)
3848/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003849{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003850 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003851 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003852
3853 /* server_hostname is either None (or absent), or to be encoded
3854 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003855 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003856 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3857 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003858 }
3859
3860 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3861 incoming, outgoing);
3862
3863 PyMem_Free(hostname);
3864 return res;
3865}
3866
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003867/*[clinic input]
3868_ssl._SSLContext.session_stats
3869[clinic start generated code]*/
3870
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003871static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003872_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3873/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003874{
3875 int r;
3876 PyObject *value, *stats = PyDict_New();
3877 if (!stats)
3878 return NULL;
3879
3880#define ADD_STATS(SSL_NAME, KEY_NAME) \
3881 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3882 if (value == NULL) \
3883 goto error; \
3884 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3885 Py_DECREF(value); \
3886 if (r < 0) \
3887 goto error;
3888
3889 ADD_STATS(number, "number");
3890 ADD_STATS(connect, "connect");
3891 ADD_STATS(connect_good, "connect_good");
3892 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3893 ADD_STATS(accept, "accept");
3894 ADD_STATS(accept_good, "accept_good");
3895 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3896 ADD_STATS(accept, "accept");
3897 ADD_STATS(hits, "hits");
3898 ADD_STATS(misses, "misses");
3899 ADD_STATS(timeouts, "timeouts");
3900 ADD_STATS(cache_full, "cache_full");
3901
3902#undef ADD_STATS
3903
3904 return stats;
3905
3906error:
3907 Py_DECREF(stats);
3908 return NULL;
3909}
3910
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003911/*[clinic input]
3912_ssl._SSLContext.set_default_verify_paths
3913[clinic start generated code]*/
3914
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003915static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003916_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3917/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003918{
3919 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3920 _setSSLError(NULL, 0, __FILE__, __LINE__);
3921 return NULL;
3922 }
3923 Py_RETURN_NONE;
3924}
3925
Antoine Pitrou501da612011-12-21 09:27:41 +01003926#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003927/*[clinic input]
3928_ssl._SSLContext.set_ecdh_curve
3929 name: object
3930 /
3931
3932[clinic start generated code]*/
3933
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003934static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003935_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3936/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003937{
3938 PyObject *name_bytes;
3939 int nid;
3940 EC_KEY *key;
3941
3942 if (!PyUnicode_FSConverter(name, &name_bytes))
3943 return NULL;
3944 assert(PyBytes_Check(name_bytes));
3945 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3946 Py_DECREF(name_bytes);
3947 if (nid == 0) {
3948 PyErr_Format(PyExc_ValueError,
3949 "unknown elliptic curve name %R", name);
3950 return NULL;
3951 }
3952 key = EC_KEY_new_by_curve_name(nid);
3953 if (key == NULL) {
3954 _setSSLError(NULL, 0, __FILE__, __LINE__);
3955 return NULL;
3956 }
3957 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3958 EC_KEY_free(key);
3959 Py_RETURN_NONE;
3960}
Antoine Pitrou501da612011-12-21 09:27:41 +01003961#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003962
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003963#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003964static int
3965_servername_callback(SSL *s, int *al, void *args)
3966{
3967 int ret;
3968 PySSLContext *ssl_ctx = (PySSLContext *) args;
3969 PySSLSocket *ssl;
3970 PyObject *servername_o;
3971 PyObject *servername_idna;
3972 PyObject *result;
3973 /* The high-level ssl.SSLSocket object */
3974 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003975 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003976 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003977
3978 if (ssl_ctx->set_hostname == NULL) {
3979 /* remove race condition in this the call back while if removing the
3980 * callback is in progress */
3981 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003982 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003983 }
3984
3985 ssl = SSL_get_app_data(s);
3986 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003987
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003988 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003989 * SSL connection and that has a .context attribute that can be changed to
3990 * identify the requested hostname. Since the official API is the Python
3991 * level API we want to pass the callback a Python level object rather than
3992 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3993 * SSLObject) that will be passed. Otherwise if there's a socket then that
3994 * will be passed. If both do not exist only then the C-level object is
3995 * passed. */
3996 if (ssl->owner)
3997 ssl_socket = PyWeakref_GetObject(ssl->owner);
3998 else if (ssl->Socket)
3999 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4000 else
4001 ssl_socket = (PyObject *) ssl;
4002
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004003 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004004 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004005 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004006
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004007 if (servername == NULL) {
4008 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
4009 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004010 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004011 else {
4012 servername_o = PyBytes_FromString(servername);
4013 if (servername_o == NULL) {
4014 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4015 goto error;
4016 }
4017 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
4018 if (servername_idna == NULL) {
4019 PyErr_WriteUnraisable(servername_o);
4020 Py_DECREF(servername_o);
4021 goto error;
4022 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004023 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004024 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
4025 servername_idna, ssl_ctx, NULL);
4026 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004027 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004028 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004029
4030 if (result == NULL) {
4031 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
4032 *al = SSL_AD_HANDSHAKE_FAILURE;
4033 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4034 }
4035 else {
4036 if (result != Py_None) {
4037 *al = (int) PyLong_AsLong(result);
4038 if (PyErr_Occurred()) {
4039 PyErr_WriteUnraisable(result);
4040 *al = SSL_AD_INTERNAL_ERROR;
4041 }
4042 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4043 }
4044 else {
4045 ret = SSL_TLSEXT_ERR_OK;
4046 }
4047 Py_DECREF(result);
4048 }
4049
4050 PyGILState_Release(gstate);
4051 return ret;
4052
4053error:
4054 Py_DECREF(ssl_socket);
4055 *al = SSL_AD_INTERNAL_ERROR;
4056 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4057 PyGILState_Release(gstate);
4058 return ret;
4059}
Antoine Pitroua5963382013-03-30 16:39:00 +01004060#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004061
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004062/*[clinic input]
4063_ssl._SSLContext.set_servername_callback
4064 method as cb: object
4065 /
4066
4067Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
4068
4069If the argument is None then the callback is disabled. The method is called
4070with the SSLSocket, the server name as a string, and the SSLContext object.
4071See RFC 6066 for details of the SNI extension.
4072[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004073
4074static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004075_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
4076/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004077{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004078#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004079 Py_CLEAR(self->set_hostname);
4080 if (cb == Py_None) {
4081 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4082 }
4083 else {
4084 if (!PyCallable_Check(cb)) {
4085 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4086 PyErr_SetString(PyExc_TypeError,
4087 "not a callable object");
4088 return NULL;
4089 }
4090 Py_INCREF(cb);
4091 self->set_hostname = cb;
4092 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4093 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4094 }
4095 Py_RETURN_NONE;
4096#else
4097 PyErr_SetString(PyExc_NotImplementedError,
4098 "The TLS extension servername callback, "
4099 "SSL_CTX_set_tlsext_servername_callback, "
4100 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01004101 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004102#endif
4103}
4104
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004105/*[clinic input]
4106_ssl._SSLContext.cert_store_stats
4107
4108Returns quantities of loaded X.509 certificates.
4109
4110X.509 certificates with a CA extension and certificate revocation lists
4111inside the context's cert store.
4112
4113NOTE: Certificates in a capath directory aren't loaded unless they have
4114been used at least once.
4115[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004116
4117static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004118_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4119/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004120{
4121 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004122 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004123 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004124 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004125
4126 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004127 objs = X509_STORE_get0_objects(store);
4128 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4129 obj = sk_X509_OBJECT_value(objs, i);
4130 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004131 case X509_LU_X509:
4132 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004133 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004134 ca++;
4135 }
4136 break;
4137 case X509_LU_CRL:
4138 crl++;
4139 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004140 default:
4141 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4142 * As far as I can tell they are internal states and never
4143 * stored in a cert store */
4144 break;
4145 }
4146 }
4147 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4148 "x509_ca", ca);
4149}
4150
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004151/*[clinic input]
4152_ssl._SSLContext.get_ca_certs
4153 binary_form: bool = False
4154
4155Returns a list of dicts with information of loaded CA certs.
4156
4157If the optional argument is True, returns a DER-encoded copy of the CA
4158certificate.
4159
4160NOTE: Certificates in a capath directory aren't loaded unless they have
4161been used at least once.
4162[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004163
4164static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004165_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4166/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004167{
4168 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004169 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004170 PyObject *ci = NULL, *rlist = NULL;
4171 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004172
4173 if ((rlist = PyList_New(0)) == NULL) {
4174 return NULL;
4175 }
4176
4177 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004178 objs = X509_STORE_get0_objects(store);
4179 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004180 X509_OBJECT *obj;
4181 X509 *cert;
4182
Christian Heimes598894f2016-09-05 23:19:05 +02004183 obj = sk_X509_OBJECT_value(objs, i);
4184 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004185 /* not a x509 cert */
4186 continue;
4187 }
4188 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004189 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004190 if (!X509_check_ca(cert)) {
4191 continue;
4192 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004193 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004194 ci = _certificate_to_der(cert);
4195 } else {
4196 ci = _decode_certificate(cert);
4197 }
4198 if (ci == NULL) {
4199 goto error;
4200 }
4201 if (PyList_Append(rlist, ci) == -1) {
4202 goto error;
4203 }
4204 Py_CLEAR(ci);
4205 }
4206 return rlist;
4207
4208 error:
4209 Py_XDECREF(ci);
4210 Py_XDECREF(rlist);
4211 return NULL;
4212}
4213
4214
Antoine Pitrou152efa22010-05-16 18:19:27 +00004215static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004216 {"check_hostname", (getter) get_check_hostname,
4217 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004218 {"_host_flags", (getter) get_host_flags,
4219 (setter) set_host_flags, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004220 {"options", (getter) get_options,
4221 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004222 {"verify_flags", (getter) get_verify_flags,
4223 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004224 {"verify_mode", (getter) get_verify_mode,
4225 (setter) set_verify_mode, NULL},
4226 {NULL}, /* sentinel */
4227};
4228
4229static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004230 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4231 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4232 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4233 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4234 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4235 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4236 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4237 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4238 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4239 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4240 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4241 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4242 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4243 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004244 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004245 {NULL, NULL} /* sentinel */
4246};
4247
4248static PyTypeObject PySSLContext_Type = {
4249 PyVarObject_HEAD_INIT(NULL, 0)
4250 "_ssl._SSLContext", /*tp_name*/
4251 sizeof(PySSLContext), /*tp_basicsize*/
4252 0, /*tp_itemsize*/
4253 (destructor)context_dealloc, /*tp_dealloc*/
4254 0, /*tp_print*/
4255 0, /*tp_getattr*/
4256 0, /*tp_setattr*/
4257 0, /*tp_reserved*/
4258 0, /*tp_repr*/
4259 0, /*tp_as_number*/
4260 0, /*tp_as_sequence*/
4261 0, /*tp_as_mapping*/
4262 0, /*tp_hash*/
4263 0, /*tp_call*/
4264 0, /*tp_str*/
4265 0, /*tp_getattro*/
4266 0, /*tp_setattro*/
4267 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004268 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004269 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004270 (traverseproc) context_traverse, /*tp_traverse*/
4271 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004272 0, /*tp_richcompare*/
4273 0, /*tp_weaklistoffset*/
4274 0, /*tp_iter*/
4275 0, /*tp_iternext*/
4276 context_methods, /*tp_methods*/
4277 0, /*tp_members*/
4278 context_getsetlist, /*tp_getset*/
4279 0, /*tp_base*/
4280 0, /*tp_dict*/
4281 0, /*tp_descr_get*/
4282 0, /*tp_descr_set*/
4283 0, /*tp_dictoffset*/
4284 0, /*tp_init*/
4285 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004286 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004287};
4288
4289
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004290/*
4291 * MemoryBIO objects
4292 */
4293
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004294/*[clinic input]
4295@classmethod
4296_ssl.MemoryBIO.__new__
4297
4298[clinic start generated code]*/
4299
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004300static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004301_ssl_MemoryBIO_impl(PyTypeObject *type)
4302/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004303{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004304 BIO *bio;
4305 PySSLMemoryBIO *self;
4306
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004307 bio = BIO_new(BIO_s_mem());
4308 if (bio == NULL) {
4309 PyErr_SetString(PySSLErrorObject,
4310 "failed to allocate BIO");
4311 return NULL;
4312 }
4313 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4314 * just that no data is currently available. The SSL routines should retry
4315 * the read, which we can achieve by calling BIO_set_retry_read(). */
4316 BIO_set_retry_read(bio);
4317 BIO_set_mem_eof_return(bio, -1);
4318
4319 assert(type != NULL && type->tp_alloc != NULL);
4320 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4321 if (self == NULL) {
4322 BIO_free(bio);
4323 return NULL;
4324 }
4325 self->bio = bio;
4326 self->eof_written = 0;
4327
4328 return (PyObject *) self;
4329}
4330
4331static void
4332memory_bio_dealloc(PySSLMemoryBIO *self)
4333{
4334 BIO_free(self->bio);
4335 Py_TYPE(self)->tp_free(self);
4336}
4337
4338static PyObject *
4339memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4340{
Segev Finer5cff6372017-07-27 01:19:17 +03004341 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004342}
4343
4344PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4345"The number of bytes pending in the memory BIO.");
4346
4347static PyObject *
4348memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4349{
4350 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4351 && self->eof_written);
4352}
4353
4354PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4355"Whether the memory BIO is at EOF.");
4356
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004357/*[clinic input]
4358_ssl.MemoryBIO.read
4359 size as len: int = -1
4360 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004361
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004362Read up to size bytes from the memory BIO.
4363
4364If size is not specified, read the entire buffer.
4365If the return value is an empty bytes instance, this means either
4366EOF or that no data is available. Use the "eof" property to
4367distinguish between the two.
4368[clinic start generated code]*/
4369
4370static PyObject *
4371_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4372/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4373{
4374 int avail, nbytes;
4375 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004376
Segev Finer5cff6372017-07-27 01:19:17 +03004377 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004378 if ((len < 0) || (len > avail))
4379 len = avail;
4380
4381 result = PyBytes_FromStringAndSize(NULL, len);
4382 if ((result == NULL) || (len == 0))
4383 return result;
4384
4385 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4386 /* There should never be any short reads but check anyway. */
4387 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4388 Py_DECREF(result);
4389 return NULL;
4390 }
4391
4392 return result;
4393}
4394
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004395/*[clinic input]
4396_ssl.MemoryBIO.write
4397 b: Py_buffer
4398 /
4399
4400Writes the bytes b into the memory BIO.
4401
4402Returns the number of bytes written.
4403[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004404
4405static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004406_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4407/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004408{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004409 int nbytes;
4410
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004411 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004412 PyErr_Format(PyExc_OverflowError,
4413 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004414 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004415 }
4416
4417 if (self->eof_written) {
4418 PyErr_SetString(PySSLErrorObject,
4419 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004420 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004421 }
4422
Segev Finer5cff6372017-07-27 01:19:17 +03004423 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004424 if (nbytes < 0) {
4425 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004426 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004427 }
4428
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004429 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004430}
4431
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004432/*[clinic input]
4433_ssl.MemoryBIO.write_eof
4434
4435Write an EOF marker to the memory BIO.
4436
4437When all data has been read, the "eof" property will be True.
4438[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004439
4440static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004441_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4442/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004443{
4444 self->eof_written = 1;
4445 /* After an EOF is written, a zero return from read() should be a real EOF
4446 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4447 BIO_clear_retry_flags(self->bio);
4448 BIO_set_mem_eof_return(self->bio, 0);
4449
4450 Py_RETURN_NONE;
4451}
4452
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004453static PyGetSetDef memory_bio_getsetlist[] = {
4454 {"pending", (getter) memory_bio_get_pending, NULL,
4455 PySSL_memory_bio_pending_doc},
4456 {"eof", (getter) memory_bio_get_eof, NULL,
4457 PySSL_memory_bio_eof_doc},
4458 {NULL}, /* sentinel */
4459};
4460
4461static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004462 _SSL_MEMORYBIO_READ_METHODDEF
4463 _SSL_MEMORYBIO_WRITE_METHODDEF
4464 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004465 {NULL, NULL} /* sentinel */
4466};
4467
4468static PyTypeObject PySSLMemoryBIO_Type = {
4469 PyVarObject_HEAD_INIT(NULL, 0)
4470 "_ssl.MemoryBIO", /*tp_name*/
4471 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4472 0, /*tp_itemsize*/
4473 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4474 0, /*tp_print*/
4475 0, /*tp_getattr*/
4476 0, /*tp_setattr*/
4477 0, /*tp_reserved*/
4478 0, /*tp_repr*/
4479 0, /*tp_as_number*/
4480 0, /*tp_as_sequence*/
4481 0, /*tp_as_mapping*/
4482 0, /*tp_hash*/
4483 0, /*tp_call*/
4484 0, /*tp_str*/
4485 0, /*tp_getattro*/
4486 0, /*tp_setattro*/
4487 0, /*tp_as_buffer*/
4488 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4489 0, /*tp_doc*/
4490 0, /*tp_traverse*/
4491 0, /*tp_clear*/
4492 0, /*tp_richcompare*/
4493 0, /*tp_weaklistoffset*/
4494 0, /*tp_iter*/
4495 0, /*tp_iternext*/
4496 memory_bio_methods, /*tp_methods*/
4497 0, /*tp_members*/
4498 memory_bio_getsetlist, /*tp_getset*/
4499 0, /*tp_base*/
4500 0, /*tp_dict*/
4501 0, /*tp_descr_get*/
4502 0, /*tp_descr_set*/
4503 0, /*tp_dictoffset*/
4504 0, /*tp_init*/
4505 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004506 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004507};
4508
Antoine Pitrou152efa22010-05-16 18:19:27 +00004509
Christian Heimes99a65702016-09-10 23:44:53 +02004510/*
4511 * SSL Session object
4512 */
4513
4514static void
4515PySSLSession_dealloc(PySSLSession *self)
4516{
INADA Naokia6296d32017-08-24 14:55:17 +09004517 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004518 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004519 Py_XDECREF(self->ctx);
4520 if (self->session != NULL) {
4521 SSL_SESSION_free(self->session);
4522 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004523 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004524}
4525
4526static PyObject *
4527PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4528{
4529 int result;
4530
4531 if (left == NULL || right == NULL) {
4532 PyErr_BadInternalCall();
4533 return NULL;
4534 }
4535
4536 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4537 Py_RETURN_NOTIMPLEMENTED;
4538 }
4539
4540 if (left == right) {
4541 result = 0;
4542 } else {
4543 const unsigned char *left_id, *right_id;
4544 unsigned int left_len, right_len;
4545 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4546 &left_len);
4547 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4548 &right_len);
4549 if (left_len == right_len) {
4550 result = memcmp(left_id, right_id, left_len);
4551 } else {
4552 result = 1;
4553 }
4554 }
4555
4556 switch (op) {
4557 case Py_EQ:
4558 if (result == 0) {
4559 Py_RETURN_TRUE;
4560 } else {
4561 Py_RETURN_FALSE;
4562 }
4563 break;
4564 case Py_NE:
4565 if (result != 0) {
4566 Py_RETURN_TRUE;
4567 } else {
4568 Py_RETURN_FALSE;
4569 }
4570 break;
4571 case Py_LT:
4572 case Py_LE:
4573 case Py_GT:
4574 case Py_GE:
4575 Py_RETURN_NOTIMPLEMENTED;
4576 break;
4577 default:
4578 PyErr_BadArgument();
4579 return NULL;
4580 }
4581}
4582
4583static int
4584PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4585{
4586 Py_VISIT(self->ctx);
4587 return 0;
4588}
4589
4590static int
4591PySSLSession_clear(PySSLSession *self)
4592{
4593 Py_CLEAR(self->ctx);
4594 return 0;
4595}
4596
4597
4598static PyObject *
4599PySSLSession_get_time(PySSLSession *self, void *closure) {
4600 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4601}
4602
4603PyDoc_STRVAR(PySSLSession_get_time_doc,
4604"Session creation time (seconds since epoch).");
4605
4606
4607static PyObject *
4608PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4609 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4610}
4611
4612PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4613"Session timeout (delta in seconds).");
4614
4615
4616static PyObject *
4617PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4618 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4619 return PyLong_FromUnsignedLong(hint);
4620}
4621
4622PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4623"Ticket life time hint.");
4624
4625
4626static PyObject *
4627PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4628 const unsigned char *id;
4629 unsigned int len;
4630 id = SSL_SESSION_get_id(self->session, &len);
4631 return PyBytes_FromStringAndSize((const char *)id, len);
4632}
4633
4634PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4635"Session id");
4636
4637
4638static PyObject *
4639PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4640 if (SSL_SESSION_has_ticket(self->session)) {
4641 Py_RETURN_TRUE;
4642 } else {
4643 Py_RETURN_FALSE;
4644 }
4645}
4646
4647PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4648"Does the session contain a ticket?");
4649
4650
4651static PyGetSetDef PySSLSession_getsetlist[] = {
4652 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4653 PySSLSession_get_has_ticket_doc},
4654 {"id", (getter) PySSLSession_get_session_id, NULL,
4655 PySSLSession_get_session_id_doc},
4656 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4657 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4658 {"time", (getter) PySSLSession_get_time, NULL,
4659 PySSLSession_get_time_doc},
4660 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4661 PySSLSession_get_timeout_doc},
4662 {NULL}, /* sentinel */
4663};
4664
4665static PyTypeObject PySSLSession_Type = {
4666 PyVarObject_HEAD_INIT(NULL, 0)
4667 "_ssl.Session", /*tp_name*/
4668 sizeof(PySSLSession), /*tp_basicsize*/
4669 0, /*tp_itemsize*/
4670 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4671 0, /*tp_print*/
4672 0, /*tp_getattr*/
4673 0, /*tp_setattr*/
4674 0, /*tp_reserved*/
4675 0, /*tp_repr*/
4676 0, /*tp_as_number*/
4677 0, /*tp_as_sequence*/
4678 0, /*tp_as_mapping*/
4679 0, /*tp_hash*/
4680 0, /*tp_call*/
4681 0, /*tp_str*/
4682 0, /*tp_getattro*/
4683 0, /*tp_setattro*/
4684 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004685 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004686 0, /*tp_doc*/
4687 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4688 (inquiry)PySSLSession_clear, /*tp_clear*/
4689 PySSLSession_richcompare, /*tp_richcompare*/
4690 0, /*tp_weaklistoffset*/
4691 0, /*tp_iter*/
4692 0, /*tp_iternext*/
4693 0, /*tp_methods*/
4694 0, /*tp_members*/
4695 PySSLSession_getsetlist, /*tp_getset*/
4696};
4697
4698
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004699/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004700/*[clinic input]
4701_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004702 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004703 entropy: double
4704 /
4705
4706Mix string into the OpenSSL PRNG state.
4707
4708entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304709string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004710[clinic start generated code]*/
4711
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004712static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004713_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004714/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004715{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004716 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004717 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004718
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004719 buf = (const char *)view->buf;
4720 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004721 do {
4722 written = Py_MIN(len, INT_MAX);
4723 RAND_add(buf, (int)written, entropy);
4724 buf += written;
4725 len -= written;
4726 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004727 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004728}
4729
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004730static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004731PySSL_RAND(int len, int pseudo)
4732{
4733 int ok;
4734 PyObject *bytes;
4735 unsigned long err;
4736 const char *errstr;
4737 PyObject *v;
4738
Victor Stinner1e81a392013-12-19 16:47:04 +01004739 if (len < 0) {
4740 PyErr_SetString(PyExc_ValueError, "num must be positive");
4741 return NULL;
4742 }
4743
Victor Stinner99c8b162011-05-24 12:05:19 +02004744 bytes = PyBytes_FromStringAndSize(NULL, len);
4745 if (bytes == NULL)
4746 return NULL;
4747 if (pseudo) {
4748 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4749 if (ok == 0 || ok == 1)
4750 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4751 }
4752 else {
4753 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4754 if (ok == 1)
4755 return bytes;
4756 }
4757 Py_DECREF(bytes);
4758
4759 err = ERR_get_error();
4760 errstr = ERR_reason_error_string(err);
4761 v = Py_BuildValue("(ks)", err, errstr);
4762 if (v != NULL) {
4763 PyErr_SetObject(PySSLErrorObject, v);
4764 Py_DECREF(v);
4765 }
4766 return NULL;
4767}
4768
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004769/*[clinic input]
4770_ssl.RAND_bytes
4771 n: int
4772 /
4773
4774Generate n cryptographically strong pseudo-random bytes.
4775[clinic start generated code]*/
4776
Victor Stinner99c8b162011-05-24 12:05:19 +02004777static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004778_ssl_RAND_bytes_impl(PyObject *module, int n)
4779/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004780{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004781 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004782}
4783
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004784/*[clinic input]
4785_ssl.RAND_pseudo_bytes
4786 n: int
4787 /
4788
4789Generate n pseudo-random bytes.
4790
4791Return a pair (bytes, is_cryptographic). is_cryptographic is True
4792if the bytes generated are cryptographically strong.
4793[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004794
4795static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004796_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4797/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004798{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004799 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004800}
4801
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004802/*[clinic input]
4803_ssl.RAND_status
4804
4805Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4806
4807It is necessary to seed the PRNG with RAND_add() on some platforms before
4808using the ssl() function.
4809[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004810
4811static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004812_ssl_RAND_status_impl(PyObject *module)
4813/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004814{
Christian Heimes217cfd12007-12-02 14:31:20 +00004815 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004816}
4817
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004818#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004819/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004820/*[clinic input]
4821_ssl.RAND_egd
4822 path: object(converter="PyUnicode_FSConverter")
4823 /
4824
4825Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4826
4827Returns number of bytes read. Raises SSLError if connection to EGD
4828fails or if it does not provide enough data to seed PRNG.
4829[clinic start generated code]*/
4830
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004831static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004832_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4833/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004834{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004835 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004836 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004837 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004838 PyErr_SetString(PySSLErrorObject,
4839 "EGD connection failed or EGD did not return "
4840 "enough data to seed the PRNG");
4841 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004842 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004843 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004844}
Christian Heimesa5d07652016-09-24 10:48:05 +02004845/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004846#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004847
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004848
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004849
4850/*[clinic input]
4851_ssl.get_default_verify_paths
4852
4853Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4854
4855The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4856[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004857
4858static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004859_ssl_get_default_verify_paths_impl(PyObject *module)
4860/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004861{
4862 PyObject *ofile_env = NULL;
4863 PyObject *ofile = NULL;
4864 PyObject *odir_env = NULL;
4865 PyObject *odir = NULL;
4866
Benjamin Petersond113c962015-07-18 10:59:13 -07004867#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004868 const char *tmp = (info); \
4869 target = NULL; \
4870 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4871 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4872 target = PyBytes_FromString(tmp); } \
4873 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004874 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004875
Benjamin Petersond113c962015-07-18 10:59:13 -07004876 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4877 CONVERT(X509_get_default_cert_file(), ofile);
4878 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4879 CONVERT(X509_get_default_cert_dir(), odir);
4880#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004881
Christian Heimes200bb1b2013-06-14 15:14:29 +02004882 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004883
4884 error:
4885 Py_XDECREF(ofile_env);
4886 Py_XDECREF(ofile);
4887 Py_XDECREF(odir_env);
4888 Py_XDECREF(odir);
4889 return NULL;
4890}
4891
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004892static PyObject*
4893asn1obj2py(ASN1_OBJECT *obj)
4894{
4895 int nid;
4896 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004897
4898 nid = OBJ_obj2nid(obj);
4899 if (nid == NID_undef) {
4900 PyErr_Format(PyExc_ValueError, "Unknown object");
4901 return NULL;
4902 }
4903 sn = OBJ_nid2sn(nid);
4904 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004905 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004906}
4907
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004908/*[clinic input]
4909_ssl.txt2obj
4910 txt: str
4911 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004912
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004913Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4914
4915By default objects are looked up by OID. With name=True short and
4916long name are also matched.
4917[clinic start generated code]*/
4918
4919static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004920_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4921/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004922{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004923 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004924 ASN1_OBJECT *obj;
4925
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004926 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4927 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004928 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004929 return NULL;
4930 }
4931 result = asn1obj2py(obj);
4932 ASN1_OBJECT_free(obj);
4933 return result;
4934}
4935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004936/*[clinic input]
4937_ssl.nid2obj
4938 nid: int
4939 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004940
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004941Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4942[clinic start generated code]*/
4943
4944static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004945_ssl_nid2obj_impl(PyObject *module, int nid)
4946/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004947{
4948 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004949 ASN1_OBJECT *obj;
4950
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004951 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004952 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004953 return NULL;
4954 }
4955 obj = OBJ_nid2obj(nid);
4956 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004957 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004958 return NULL;
4959 }
4960 result = asn1obj2py(obj);
4961 ASN1_OBJECT_free(obj);
4962 return result;
4963}
4964
Christian Heimes46bebee2013-06-09 19:03:31 +02004965#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004966
4967static PyObject*
4968certEncodingType(DWORD encodingType)
4969{
4970 static PyObject *x509_asn = NULL;
4971 static PyObject *pkcs_7_asn = NULL;
4972
4973 if (x509_asn == NULL) {
4974 x509_asn = PyUnicode_InternFromString("x509_asn");
4975 if (x509_asn == NULL)
4976 return NULL;
4977 }
4978 if (pkcs_7_asn == NULL) {
4979 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4980 if (pkcs_7_asn == NULL)
4981 return NULL;
4982 }
4983 switch(encodingType) {
4984 case X509_ASN_ENCODING:
4985 Py_INCREF(x509_asn);
4986 return x509_asn;
4987 case PKCS_7_ASN_ENCODING:
4988 Py_INCREF(pkcs_7_asn);
4989 return pkcs_7_asn;
4990 default:
4991 return PyLong_FromLong(encodingType);
4992 }
4993}
4994
4995static PyObject*
4996parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4997{
4998 CERT_ENHKEY_USAGE *usage;
4999 DWORD size, error, i;
5000 PyObject *retval;
5001
5002 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5003 error = GetLastError();
5004 if (error == CRYPT_E_NOT_FOUND) {
5005 Py_RETURN_TRUE;
5006 }
5007 return PyErr_SetFromWindowsErr(error);
5008 }
5009
5010 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5011 if (usage == NULL) {
5012 return PyErr_NoMemory();
5013 }
5014
5015 /* Now get the actual enhanced usage property */
5016 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5017 PyMem_Free(usage);
5018 error = GetLastError();
5019 if (error == CRYPT_E_NOT_FOUND) {
5020 Py_RETURN_TRUE;
5021 }
5022 return PyErr_SetFromWindowsErr(error);
5023 }
5024 retval = PySet_New(NULL);
5025 if (retval == NULL) {
5026 goto error;
5027 }
5028 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5029 if (usage->rgpszUsageIdentifier[i]) {
5030 PyObject *oid;
5031 int err;
5032 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5033 if (oid == NULL) {
5034 Py_CLEAR(retval);
5035 goto error;
5036 }
5037 err = PySet_Add(retval, oid);
5038 Py_DECREF(oid);
5039 if (err == -1) {
5040 Py_CLEAR(retval);
5041 goto error;
5042 }
5043 }
5044 }
5045 error:
5046 PyMem_Free(usage);
5047 return retval;
5048}
5049
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005050/*[clinic input]
5051_ssl.enum_certificates
5052 store_name: str
5053
5054Retrieve certificates from Windows' cert store.
5055
5056store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5057more cert storages, too. The function returns a list of (bytes,
5058encoding_type, trust) tuples. The encoding_type flag can be interpreted
5059with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5060a set of OIDs or the boolean True.
5061[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005062
Christian Heimes46bebee2013-06-09 19:03:31 +02005063static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005064_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5065/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005066{
Christian Heimes46bebee2013-06-09 19:03:31 +02005067 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005068 PCCERT_CONTEXT pCertCtx = NULL;
5069 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005070 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005071
Christian Heimes44109d72013-11-22 01:51:30 +01005072 result = PyList_New(0);
5073 if (result == NULL) {
5074 return NULL;
5075 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005076 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5077 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5078 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005079 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005080 Py_DECREF(result);
5081 return PyErr_SetFromWindowsErr(GetLastError());
5082 }
5083
Christian Heimes44109d72013-11-22 01:51:30 +01005084 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5085 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5086 pCertCtx->cbCertEncoded);
5087 if (!cert) {
5088 Py_CLEAR(result);
5089 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005090 }
Christian Heimes44109d72013-11-22 01:51:30 +01005091 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5092 Py_CLEAR(result);
5093 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005094 }
Christian Heimes44109d72013-11-22 01:51:30 +01005095 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5096 if (keyusage == Py_True) {
5097 Py_DECREF(keyusage);
5098 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005099 }
Christian Heimes44109d72013-11-22 01:51:30 +01005100 if (keyusage == NULL) {
5101 Py_CLEAR(result);
5102 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005103 }
Christian Heimes44109d72013-11-22 01:51:30 +01005104 if ((tup = PyTuple_New(3)) == NULL) {
5105 Py_CLEAR(result);
5106 break;
5107 }
5108 PyTuple_SET_ITEM(tup, 0, cert);
5109 cert = NULL;
5110 PyTuple_SET_ITEM(tup, 1, enc);
5111 enc = NULL;
5112 PyTuple_SET_ITEM(tup, 2, keyusage);
5113 keyusage = NULL;
5114 if (PyList_Append(result, tup) < 0) {
5115 Py_CLEAR(result);
5116 break;
5117 }
5118 Py_CLEAR(tup);
5119 }
5120 if (pCertCtx) {
5121 /* loop ended with an error, need to clean up context manually */
5122 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005123 }
5124
5125 /* In error cases cert, enc and tup may not be NULL */
5126 Py_XDECREF(cert);
5127 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005128 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005129 Py_XDECREF(tup);
5130
5131 if (!CertCloseStore(hStore, 0)) {
5132 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005133 Py_XDECREF(result);
5134 return PyErr_SetFromWindowsErr(GetLastError());
5135 }
5136 return result;
5137}
5138
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005139/*[clinic input]
5140_ssl.enum_crls
5141 store_name: str
5142
5143Retrieve CRLs from Windows' cert store.
5144
5145store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5146more cert storages, too. The function returns a list of (bytes,
5147encoding_type) tuples. The encoding_type flag can be interpreted with
5148X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5149[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005150
5151static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005152_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5153/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005154{
Christian Heimes44109d72013-11-22 01:51:30 +01005155 HCERTSTORE hStore = NULL;
5156 PCCRL_CONTEXT pCrlCtx = NULL;
5157 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5158 PyObject *result = NULL;
5159
Christian Heimes44109d72013-11-22 01:51:30 +01005160 result = PyList_New(0);
5161 if (result == NULL) {
5162 return NULL;
5163 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005164 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5165 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5166 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005167 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005168 Py_DECREF(result);
5169 return PyErr_SetFromWindowsErr(GetLastError());
5170 }
Christian Heimes44109d72013-11-22 01:51:30 +01005171
5172 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5173 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5174 pCrlCtx->cbCrlEncoded);
5175 if (!crl) {
5176 Py_CLEAR(result);
5177 break;
5178 }
5179 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5180 Py_CLEAR(result);
5181 break;
5182 }
5183 if ((tup = PyTuple_New(2)) == NULL) {
5184 Py_CLEAR(result);
5185 break;
5186 }
5187 PyTuple_SET_ITEM(tup, 0, crl);
5188 crl = NULL;
5189 PyTuple_SET_ITEM(tup, 1, enc);
5190 enc = NULL;
5191
5192 if (PyList_Append(result, tup) < 0) {
5193 Py_CLEAR(result);
5194 break;
5195 }
5196 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005197 }
Christian Heimes44109d72013-11-22 01:51:30 +01005198 if (pCrlCtx) {
5199 /* loop ended with an error, need to clean up context manually */
5200 CertFreeCRLContext(pCrlCtx);
5201 }
5202
5203 /* In error cases cert, enc and tup may not be NULL */
5204 Py_XDECREF(crl);
5205 Py_XDECREF(enc);
5206 Py_XDECREF(tup);
5207
5208 if (!CertCloseStore(hStore, 0)) {
5209 /* This error case might shadow another exception.*/
5210 Py_XDECREF(result);
5211 return PyErr_SetFromWindowsErr(GetLastError());
5212 }
5213 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005214}
Christian Heimes44109d72013-11-22 01:51:30 +01005215
5216#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005217
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005218/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005219static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005220 _SSL__TEST_DECODE_CERT_METHODDEF
5221 _SSL_RAND_ADD_METHODDEF
5222 _SSL_RAND_BYTES_METHODDEF
5223 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5224 _SSL_RAND_EGD_METHODDEF
5225 _SSL_RAND_STATUS_METHODDEF
5226 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5227 _SSL_ENUM_CERTIFICATES_METHODDEF
5228 _SSL_ENUM_CRLS_METHODDEF
5229 _SSL_TXT2OBJ_METHODDEF
5230 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005231 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005232};
5233
5234
Christian Heimes598894f2016-09-05 23:19:05 +02005235#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005236
5237/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005238 * of the Python C thread library
5239 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5240 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005241
5242static PyThread_type_lock *_ssl_locks = NULL;
5243
Christian Heimes4d98ca92013-08-19 17:36:29 +02005244#if OPENSSL_VERSION_NUMBER >= 0x10000000
5245/* use new CRYPTO_THREADID API. */
5246static void
5247_ssl_threadid_callback(CRYPTO_THREADID *id)
5248{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005249 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005250}
5251#else
5252/* deprecated CRYPTO_set_id_callback() API. */
5253static unsigned long
5254_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005255 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005256}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005257#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005258
Bill Janssen6e027db2007-11-15 22:23:56 +00005259static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005260 (int mode, int n, const char *file, int line) {
5261 /* this function is needed to perform locking on shared data
5262 structures. (Note that OpenSSL uses a number of global data
5263 structures that will be implicitly shared whenever multiple
5264 threads use OpenSSL.) Multi-threaded applications will
5265 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005266
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005267 locking_function() must be able to handle up to
5268 CRYPTO_num_locks() different mutex locks. It sets the n-th
5269 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005270
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005271 file and line are the file number of the function setting the
5272 lock. They can be useful for debugging.
5273 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005275 if ((_ssl_locks == NULL) ||
5276 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5277 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005279 if (mode & CRYPTO_LOCK) {
5280 PyThread_acquire_lock(_ssl_locks[n], 1);
5281 } else {
5282 PyThread_release_lock(_ssl_locks[n]);
5283 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005284}
5285
5286static int _setup_ssl_threads(void) {
5287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005288 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005290 if (_ssl_locks == NULL) {
5291 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005292 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5293 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005294 if (_ssl_locks == NULL) {
5295 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005296 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005297 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005298 for (i = 0; i < _ssl_locks_count; i++) {
5299 _ssl_locks[i] = PyThread_allocate_lock();
5300 if (_ssl_locks[i] == NULL) {
5301 unsigned int j;
5302 for (j = 0; j < i; j++) {
5303 PyThread_free_lock(_ssl_locks[j]);
5304 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005305 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005306 return 0;
5307 }
5308 }
5309 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005310#if OPENSSL_VERSION_NUMBER >= 0x10000000
5311 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5312#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005313 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005314#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005315 }
5316 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005317}
5318
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005319#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005320
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005321PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005322"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005323for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005324
Martin v. Löwis1a214512008-06-11 05:26:20 +00005325
5326static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005327 PyModuleDef_HEAD_INIT,
5328 "_ssl",
5329 module_doc,
5330 -1,
5331 PySSL_methods,
5332 NULL,
5333 NULL,
5334 NULL,
5335 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005336};
5337
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005338
5339static void
5340parse_openssl_version(unsigned long libver,
5341 unsigned int *major, unsigned int *minor,
5342 unsigned int *fix, unsigned int *patch,
5343 unsigned int *status)
5344{
5345 *status = libver & 0xF;
5346 libver >>= 4;
5347 *patch = libver & 0xFF;
5348 libver >>= 8;
5349 *fix = libver & 0xFF;
5350 libver >>= 8;
5351 *minor = libver & 0xFF;
5352 libver >>= 8;
5353 *major = libver & 0xFF;
5354}
5355
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005356PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005357PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005358{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005359 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005360 unsigned long libver;
5361 unsigned int major, minor, fix, patch, status;
5362 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005363 struct py_ssl_error_code *errcode;
5364 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005365
Antoine Pitrou152efa22010-05-16 18:19:27 +00005366 if (PyType_Ready(&PySSLContext_Type) < 0)
5367 return NULL;
5368 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005369 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005370 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5371 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005372 if (PyType_Ready(&PySSLSession_Type) < 0)
5373 return NULL;
5374
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005375
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005376 m = PyModule_Create(&_sslmodule);
5377 if (m == NULL)
5378 return NULL;
5379 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005381 /* Load _socket module and its C API */
5382 socket_api = PySocketModule_ImportModuleAndAPI();
5383 if (!socket_api)
5384 return NULL;
5385 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005386
Christian Heimesc941e622017-09-05 15:47:11 +02005387#ifndef OPENSSL_VERSION_1_1
5388 /* Load all algorithms and initialize cpuid */
5389 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005390 /* Init OpenSSL */
5391 SSL_load_error_strings();
5392 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005393#endif
5394
Christian Heimes598894f2016-09-05 23:19:05 +02005395#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005396 /* note that this will start threading if not already started */
5397 if (!_setup_ssl_threads()) {
5398 return NULL;
5399 }
Christian Heimes598894f2016-09-05 23:19:05 +02005400#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5401 /* OpenSSL 1.1.0 builtin thread support is enabled */
5402 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005403#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005404
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005405 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005406 sslerror_type_slots[0].pfunc = PyExc_OSError;
5407 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005408 if (PySSLErrorObject == NULL)
5409 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005410
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005411 /* ssl.CertificateError used to be a subclass of ValueError */
5412 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5413 if (bases == NULL)
5414 return NULL;
5415 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5416 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5417 bases, NULL);
5418 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005419 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5420 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5421 PySSLErrorObject, NULL);
5422 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5423 "ssl.SSLWantReadError", SSLWantReadError_doc,
5424 PySSLErrorObject, NULL);
5425 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5426 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5427 PySSLErrorObject, NULL);
5428 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5429 "ssl.SSLSyscallError", SSLSyscallError_doc,
5430 PySSLErrorObject, NULL);
5431 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5432 "ssl.SSLEOFError", SSLEOFError_doc,
5433 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005434 if (PySSLCertVerificationErrorObject == NULL
5435 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005436 || PySSLWantReadErrorObject == NULL
5437 || PySSLWantWriteErrorObject == NULL
5438 || PySSLSyscallErrorObject == NULL
5439 || PySSLEOFErrorObject == NULL)
5440 return NULL;
5441 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005442 || PyDict_SetItemString(d, "SSLCertVerificationError",
5443 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005444 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5445 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5446 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5447 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5448 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005449 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005450 if (PyDict_SetItemString(d, "_SSLContext",
5451 (PyObject *)&PySSLContext_Type) != 0)
5452 return NULL;
5453 if (PyDict_SetItemString(d, "_SSLSocket",
5454 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005455 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005456 if (PyDict_SetItemString(d, "MemoryBIO",
5457 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5458 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005459 if (PyDict_SetItemString(d, "SSLSession",
5460 (PyObject *)&PySSLSession_Type) != 0)
5461 return NULL;
5462
Christian Heimes892d66e2018-01-29 14:10:18 +01005463 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5464 PY_SSL_DEFAULT_CIPHER_STRING);
5465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005466 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5467 PY_SSL_ERROR_ZERO_RETURN);
5468 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5469 PY_SSL_ERROR_WANT_READ);
5470 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5471 PY_SSL_ERROR_WANT_WRITE);
5472 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5473 PY_SSL_ERROR_WANT_X509_LOOKUP);
5474 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5475 PY_SSL_ERROR_SYSCALL);
5476 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5477 PY_SSL_ERROR_SSL);
5478 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5479 PY_SSL_ERROR_WANT_CONNECT);
5480 /* non ssl.h errorcodes */
5481 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5482 PY_SSL_ERROR_EOF);
5483 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5484 PY_SSL_ERROR_INVALID_ERROR_CODE);
5485 /* cert requirements */
5486 PyModule_AddIntConstant(m, "CERT_NONE",
5487 PY_SSL_CERT_NONE);
5488 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5489 PY_SSL_CERT_OPTIONAL);
5490 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5491 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005492 /* CRL verification for verification_flags */
5493 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5494 0);
5495 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5496 X509_V_FLAG_CRL_CHECK);
5497 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5498 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5499 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5500 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005501#ifdef X509_V_FLAG_TRUSTED_FIRST
5502 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5503 X509_V_FLAG_TRUSTED_FIRST);
5504#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005505
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005506 /* Alert Descriptions from ssl.h */
5507 /* note RESERVED constants no longer intended for use have been removed */
5508 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5509
5510#define ADD_AD_CONSTANT(s) \
5511 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5512 SSL_AD_##s)
5513
5514 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5515 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5516 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5517 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5518 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5519 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5520 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5521 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5522 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5523 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5524 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5525 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5526 ADD_AD_CONSTANT(UNKNOWN_CA);
5527 ADD_AD_CONSTANT(ACCESS_DENIED);
5528 ADD_AD_CONSTANT(DECODE_ERROR);
5529 ADD_AD_CONSTANT(DECRYPT_ERROR);
5530 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5531 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5532 ADD_AD_CONSTANT(INTERNAL_ERROR);
5533 ADD_AD_CONSTANT(USER_CANCELLED);
5534 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005535 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005536#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5537 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5538#endif
5539#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5540 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5541#endif
5542#ifdef SSL_AD_UNRECOGNIZED_NAME
5543 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5544#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005545#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5546 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5547#endif
5548#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5549 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5550#endif
5551#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5552 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5553#endif
5554
5555#undef ADD_AD_CONSTANT
5556
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005557 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005558#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005559 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5560 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005561#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005562#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005563 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5564 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005565#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005566 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005567 PY_SSL_VERSION_TLS);
5568 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5569 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005570 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5571 PY_SSL_VERSION_TLS_CLIENT);
5572 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5573 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005574 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5575 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005576#if HAVE_TLSv1_2
5577 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5578 PY_SSL_VERSION_TLS1_1);
5579 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5580 PY_SSL_VERSION_TLS1_2);
5581#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005582
Antoine Pitroub5218772010-05-21 09:56:06 +00005583 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005584 PyModule_AddIntConstant(m, "OP_ALL",
5585 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005586 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5587 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5588 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005589#if HAVE_TLSv1_2
5590 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5591 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5592#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005593#ifdef SSL_OP_NO_TLSv1_3
5594 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5595#else
5596 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5597#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005598 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5599 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005600 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005601 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005602#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005603 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005604#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005605#ifdef SSL_OP_NO_COMPRESSION
5606 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5607 SSL_OP_NO_COMPRESSION);
5608#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005609
Christian Heimes61d478c2018-01-27 15:51:38 +01005610#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5611 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5612 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5613#endif
5614#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5615 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5616 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5617#endif
5618#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5619 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5620 X509_CHECK_FLAG_NO_WILDCARDS);
5621#endif
5622#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5623 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5624 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5625#endif
5626#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5627 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5628 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5629#endif
5630#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5631 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5632 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5633#endif
5634
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005635#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005636 r = Py_True;
5637#else
5638 r = Py_False;
5639#endif
5640 Py_INCREF(r);
5641 PyModule_AddObject(m, "HAS_SNI", r);
5642
Antoine Pitroud6494802011-07-21 01:11:30 +02005643 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005644 Py_INCREF(r);
5645 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5646
Antoine Pitrou501da612011-12-21 09:27:41 +01005647#ifdef OPENSSL_NO_ECDH
5648 r = Py_False;
5649#else
5650 r = Py_True;
5651#endif
5652 Py_INCREF(r);
5653 PyModule_AddObject(m, "HAS_ECDH", r);
5654
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005655#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005656 r = Py_True;
5657#else
5658 r = Py_False;
5659#endif
5660 Py_INCREF(r);
5661 PyModule_AddObject(m, "HAS_NPN", r);
5662
Benjamin Petersoncca27322015-01-23 16:35:37 -05005663#ifdef HAVE_ALPN
5664 r = Py_True;
5665#else
5666 r = Py_False;
5667#endif
5668 Py_INCREF(r);
5669 PyModule_AddObject(m, "HAS_ALPN", r);
5670
Christian Heimescb5b68a2017-09-07 18:07:00 -07005671#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5672 r = Py_True;
5673#else
5674 r = Py_False;
5675#endif
5676 Py_INCREF(r);
5677 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5678
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005679 /* Mappings for error codes */
5680 err_codes_to_names = PyDict_New();
5681 err_names_to_codes = PyDict_New();
5682 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5683 return NULL;
5684 errcode = error_codes;
5685 while (errcode->mnemonic != NULL) {
5686 PyObject *mnemo, *key;
5687 mnemo = PyUnicode_FromString(errcode->mnemonic);
5688 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5689 if (mnemo == NULL || key == NULL)
5690 return NULL;
5691 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5692 return NULL;
5693 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5694 return NULL;
5695 Py_DECREF(key);
5696 Py_DECREF(mnemo);
5697 errcode++;
5698 }
5699 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5700 return NULL;
5701 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5702 return NULL;
5703
5704 lib_codes_to_names = PyDict_New();
5705 if (lib_codes_to_names == NULL)
5706 return NULL;
5707 libcode = library_codes;
5708 while (libcode->library != NULL) {
5709 PyObject *mnemo, *key;
5710 key = PyLong_FromLong(libcode->code);
5711 mnemo = PyUnicode_FromString(libcode->library);
5712 if (key == NULL || mnemo == NULL)
5713 return NULL;
5714 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5715 return NULL;
5716 Py_DECREF(key);
5717 Py_DECREF(mnemo);
5718 libcode++;
5719 }
5720 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5721 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005722
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005723 /* OpenSSL version */
5724 /* SSLeay() gives us the version of the library linked against,
5725 which could be different from the headers version.
5726 */
5727 libver = SSLeay();
5728 r = PyLong_FromUnsignedLong(libver);
5729 if (r == NULL)
5730 return NULL;
5731 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5732 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005733 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005734 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5735 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5736 return NULL;
5737 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5738 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5739 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005740
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005741 libver = OPENSSL_VERSION_NUMBER;
5742 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5743 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5744 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5745 return NULL;
5746
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005747 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005748}