blob: a0f8c1cb3244342e6939651f88190586c1b2e1b2 [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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800340 PyObject *set_sni_cb;
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;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800347 int protocol;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000348} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000349
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350typedef struct {
351 PyObject_HEAD
352 PyObject *Socket; /* weakref to socket on which we're layered */
353 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100354 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200355 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200356 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200357 PyObject *owner; /* Python level "owner" passed to servername callback */
358 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700359 int ssl_errno; /* last seen error from SSL */
360 int c_errno; /* last seen error from libc */
361#ifdef MS_WINDOWS
362 int ws_errno; /* last seen error from winsock */
363#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000364} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000365
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200366typedef struct {
367 PyObject_HEAD
368 BIO *bio;
369 int eof_written;
370} PySSLMemoryBIO;
371
Christian Heimes99a65702016-09-10 23:44:53 +0200372typedef struct {
373 PyObject_HEAD
374 SSL_SESSION *session;
375 PySSLContext *ctx;
376} PySSLSession;
377
Antoine Pitrou152efa22010-05-16 18:19:27 +0000378static PyTypeObject PySSLContext_Type;
379static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200380static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200381static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000382
Steve Dowere6eb48c2017-09-08 15:16:15 -0700383#ifdef MS_WINDOWS
384#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
385 (sock)->ws_errno = WSAGetLastError(); \
386 _PySSL_FIX_ERRNO; \
387 (sock)->c_errno = errno; \
388 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
389 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
390#else
391#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
392 (sock)->c_errno = errno; \
393 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
394 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
395#endif
396#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
397
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300398/*[clinic input]
399module _ssl
400class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
401class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
402class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200403class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300404[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200405/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300406
407#include "clinic/_ssl.c.h"
408
Victor Stinner14690702015-04-06 22:46:13 +0200409static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000410
Antoine Pitrou152efa22010-05-16 18:19:27 +0000411#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200412#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200413#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000414
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000415typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000416 SOCKET_IS_NONBLOCKING,
417 SOCKET_IS_BLOCKING,
418 SOCKET_HAS_TIMED_OUT,
419 SOCKET_HAS_BEEN_CLOSED,
420 SOCKET_TOO_LARGE_FOR_SELECT,
421 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000422} timeout_state;
423
Thomas Woutersed03b412007-08-28 21:37:11 +0000424/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000425#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200426#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000427
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200428/* Get the socket from a PySSLSocket, if it has one */
429#define GET_SOCKET(obj) ((obj)->Socket ? \
430 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200431
Victor Stinner14690702015-04-06 22:46:13 +0200432/* If sock is NULL, use a timeout of 0 second */
433#define GET_SOCKET_TIMEOUT(sock) \
434 ((sock != NULL) ? (sock)->sock_timeout : 0)
435
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200436/*
437 * SSL errors.
438 */
439
440PyDoc_STRVAR(SSLError_doc,
441"An error occurred in the SSL implementation.");
442
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700443PyDoc_STRVAR(SSLCertVerificationError_doc,
444"A certificate could not be verified.");
445
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200446PyDoc_STRVAR(SSLZeroReturnError_doc,
447"SSL/TLS session closed cleanly.");
448
449PyDoc_STRVAR(SSLWantReadError_doc,
450"Non-blocking SSL socket needs to read more data\n"
451"before the requested operation can be completed.");
452
453PyDoc_STRVAR(SSLWantWriteError_doc,
454"Non-blocking SSL socket needs to write more data\n"
455"before the requested operation can be completed.");
456
457PyDoc_STRVAR(SSLSyscallError_doc,
458"System error when attempting SSL operation.");
459
460PyDoc_STRVAR(SSLEOFError_doc,
461"SSL/TLS connection terminated abruptly.");
462
463static PyObject *
464SSLError_str(PyOSErrorObject *self)
465{
466 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
467 Py_INCREF(self->strerror);
468 return self->strerror;
469 }
470 else
471 return PyObject_Str(self->args);
472}
473
474static PyType_Slot sslerror_type_slots[] = {
475 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
476 {Py_tp_doc, SSLError_doc},
477 {Py_tp_str, SSLError_str},
478 {0, 0},
479};
480
481static PyType_Spec sslerror_type_spec = {
482 "ssl.SSLError",
483 sizeof(PyOSErrorObject),
484 0,
485 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
486 sslerror_type_slots
487};
488
489static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700490fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
491 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200492{
493 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700494 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200495 PyObject *init_value, *msg, *key;
496 _Py_IDENTIFIER(reason);
497 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700498 _Py_IDENTIFIER(verify_message);
499 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200500
501 if (errcode != 0) {
502 int lib, reason;
503
504 lib = ERR_GET_LIB(errcode);
505 reason = ERR_GET_REASON(errcode);
506 key = Py_BuildValue("ii", lib, reason);
507 if (key == NULL)
508 goto fail;
509 reason_obj = PyDict_GetItem(err_codes_to_names, key);
510 Py_DECREF(key);
511 if (reason_obj == NULL) {
512 /* XXX if reason < 100, it might reflect a library number (!!) */
513 PyErr_Clear();
514 }
515 key = PyLong_FromLong(lib);
516 if (key == NULL)
517 goto fail;
518 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
519 Py_DECREF(key);
520 if (lib_obj == NULL) {
521 PyErr_Clear();
522 }
523 if (errstr == NULL)
524 errstr = ERR_reason_error_string(errcode);
525 }
526 if (errstr == NULL)
527 errstr = "unknown error";
528
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700529 /* verify code for cert validation error */
530 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
531 const char *verify_str = NULL;
532 long verify_code;
533
534 verify_code = SSL_get_verify_result(sslsock->ssl);
535 verify_code_obj = PyLong_FromLong(verify_code);
536 if (verify_code_obj == NULL) {
537 goto fail;
538 }
539
540 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700541#ifdef X509_V_ERR_HOSTNAME_MISMATCH
542 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700543 case X509_V_ERR_HOSTNAME_MISMATCH:
544 verify_obj = PyUnicode_FromFormat(
545 "Hostname mismatch, certificate is not valid for '%S'.",
546 sslsock->server_hostname
547 );
548 break;
Christian Heimes09153602017-09-08 14:47:58 -0700549#endif
550#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700551 case X509_V_ERR_IP_ADDRESS_MISMATCH:
552 verify_obj = PyUnicode_FromFormat(
553 "IP address mismatch, certificate is not valid for '%S'.",
554 sslsock->server_hostname
555 );
556 break;
Christian Heimes09153602017-09-08 14:47:58 -0700557#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700558 default:
559 verify_str = X509_verify_cert_error_string(verify_code);
560 if (verify_str != NULL) {
561 verify_obj = PyUnicode_FromString(verify_str);
562 } else {
563 verify_obj = Py_None;
564 Py_INCREF(verify_obj);
565 }
566 break;
567 }
568 if (verify_obj == NULL) {
569 goto fail;
570 }
571 }
572
573 if (verify_obj && reason_obj && lib_obj)
574 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
575 lib_obj, reason_obj, errstr, verify_obj,
576 lineno);
577 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200578 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
579 lib_obj, reason_obj, errstr, lineno);
580 else if (lib_obj)
581 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
582 lib_obj, errstr, lineno);
583 else
584 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200585 if (msg == NULL)
586 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100587
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200588 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100589 if (init_value == NULL)
590 goto fail;
591
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200592 err_value = PyObject_CallObject(type, init_value);
593 Py_DECREF(init_value);
594 if (err_value == NULL)
595 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100596
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 if (reason_obj == NULL)
598 reason_obj = Py_None;
599 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
600 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700601
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200602 if (lib_obj == NULL)
603 lib_obj = Py_None;
604 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
605 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700606
607 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
608 /* Only set verify code / message for SSLCertVerificationError */
609 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
610 verify_code_obj))
611 goto fail;
612 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
613 goto fail;
614 }
615
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200616 PyErr_SetObject(type, err_value);
617fail:
618 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700619 Py_XDECREF(verify_code_obj);
620 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200621}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000622
623static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700624PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000625{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200626 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200627 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 int err;
629 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200630 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200633 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000634
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700636 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000637
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 switch (err) {
639 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200640 errstr = "TLS/SSL connection has been closed (EOF)";
641 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000642 p = PY_SSL_ERROR_ZERO_RETURN;
643 break;
644 case SSL_ERROR_WANT_READ:
645 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200646 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000647 p = PY_SSL_ERROR_WANT_READ;
648 break;
649 case SSL_ERROR_WANT_WRITE:
650 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200651 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 errstr = "The operation did not complete (write)";
653 break;
654 case SSL_ERROR_WANT_X509_LOOKUP:
655 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000656 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000657 break;
658 case SSL_ERROR_WANT_CONNECT:
659 p = PY_SSL_ERROR_WANT_CONNECT;
660 errstr = "The operation did not complete (connect)";
661 break;
662 case SSL_ERROR_SYSCALL:
663 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700665 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000667 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200668 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000669 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200670 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000671 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000672 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700673#ifdef MS_WINDOWS
674 if (sslsock->ws_errno)
675 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
676#endif
677 if (sslsock->c_errno) {
678 errno = sslsock->c_errno;
679 return PyErr_SetFromErrno(PyExc_OSError);
680 }
681 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200682 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000683 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200684 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000685 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000686 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200687 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000688 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 }
690 } else {
691 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000692 }
693 break;
694 }
695 case SSL_ERROR_SSL:
696 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000697 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700698 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200699 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000700 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700701 }
702 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
703 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
704 type = PySSLCertVerificationErrorObject;
705 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 break;
707 }
708 default:
709 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
710 errstr = "Invalid error code";
711 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700713 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000714 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000716}
717
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000718static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200719_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200721 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200723 else
724 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700725 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000726 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000728}
729
Christian Heimes61d478c2018-01-27 15:51:38 +0100730/*
731 * SSL objects
732 */
733
734static int
735_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
736{
737 int retval = -1;
738 ASN1_OCTET_STRING *ip;
739 PyObject *hostname;
740 size_t len;
741
742 assert(server_hostname);
743
744 /* Disable OpenSSL's special mode with leading dot in hostname:
745 * When name starts with a dot (e.g ".example.com"), it will be
746 * matched by a certificate valid for any sub-domain of name.
747 */
748 len = strlen(server_hostname);
749 if (len == 0 || *server_hostname == '.') {
750 PyErr_SetString(
751 PyExc_ValueError,
752 "server_hostname cannot be an empty string or start with a "
753 "leading dot.");
754 return retval;
755 }
756
757 /* inet_pton is not available on all platforms. */
758 ip = a2i_IPADDRESS(server_hostname);
759 if (ip == NULL) {
760 ERR_clear_error();
761 }
762
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800763 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100764 if (hostname == NULL) {
765 goto error;
766 }
767 self->server_hostname = hostname;
768
769 /* Only send SNI extension for non-IP hostnames */
770 if (ip == NULL) {
771 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
772 _setSSLError(NULL, 0, __FILE__, __LINE__);
773 }
774 }
775 if (self->ctx->check_hostname) {
776 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
777 if (ip == NULL) {
778 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
779 _setSSLError(NULL, 0, __FILE__, __LINE__);
780 goto error;
781 }
782 } else {
783 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
784 ASN1_STRING_length(ip))) {
785 _setSSLError(NULL, 0, __FILE__, __LINE__);
786 goto error;
787 }
788 }
789 }
790 retval = 0;
791 error:
792 if (ip != NULL) {
793 ASN1_OCTET_STRING_free(ip);
794 }
795 return retval;
796}
797
Antoine Pitrou152efa22010-05-16 18:19:27 +0000798static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100799newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000800 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200801 char *server_hostname,
802 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000803{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000804 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100805 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200806 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000807
Antoine Pitrou152efa22010-05-16 18:19:27 +0000808 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000809 if (self == NULL)
810 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000813 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100814 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700815 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200816 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200817 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700818 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700819 self->ssl_errno = 0;
820 self->c_errno = 0;
821#ifdef MS_WINDOWS
822 self->ws_errno = 0;
823#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200824
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 /* Make sure the SSL error state is initialized */
826 (void) ERR_get_state();
827 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000828
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000830 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000831 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200832 SSL_set_app_data(self->ssl, self);
833 if (sock) {
834 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
835 } else {
836 /* BIOs are reference counted and SSL_set_bio borrows our reference.
837 * To prevent a double free in memory_bio_dealloc() we need to take an
838 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200839 BIO_up_ref(inbio->bio);
840 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200841 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
842 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200843 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000844#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200845 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000846#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200847 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000848
Christian Heimes61d478c2018-01-27 15:51:38 +0100849 if (server_hostname != NULL) {
850 if (_ssl_configure_hostname(self, server_hostname) < 0) {
851 Py_DECREF(self);
852 return NULL;
853 }
854 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 /* If the socket is in non-blocking mode or timeout mode, set the BIO
856 * to non-blocking mode (blocking is the default)
857 */
Victor Stinnere2452312015-03-28 03:00:46 +0100858 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000859 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
860 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
861 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000862
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 PySSL_BEGIN_ALLOW_THREADS
864 if (socket_type == PY_SSL_CLIENT)
865 SSL_set_connect_state(self->ssl);
866 else
867 SSL_set_accept_state(self->ssl);
868 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000869
Antoine Pitroud6494802011-07-21 01:11:30 +0200870 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200871 if (sock != NULL) {
872 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
873 if (self->Socket == NULL) {
874 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200875 return NULL;
876 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100877 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000879}
880
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000881/* SSL object methods */
882
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300883/*[clinic input]
884_ssl._SSLSocket.do_handshake
885[clinic start generated code]*/
886
887static PyObject *
888_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
889/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000890{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 int ret;
892 int err;
893 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200894 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200895 _PyTime_t timeout, deadline = 0;
896 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000897
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200898 if (sock) {
899 if (((PyObject*)sock) == Py_None) {
900 _setSSLError("Underlying socket connection gone",
901 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
902 return NULL;
903 }
904 Py_INCREF(sock);
905
906 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100907 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200908 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
909 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000911
Victor Stinner14690702015-04-06 22:46:13 +0200912 timeout = GET_SOCKET_TIMEOUT(sock);
913 has_timeout = (timeout > 0);
914 if (has_timeout)
915 deadline = _PyTime_GetMonotonicClock() + timeout;
916
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 /* Actually negotiate SSL connection */
918 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000920 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000921 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700922 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700924 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200925
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000926 if (PyErr_CheckSignals())
927 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200928
Victor Stinner14690702015-04-06 22:46:13 +0200929 if (has_timeout)
930 timeout = deadline - _PyTime_GetMonotonicClock();
931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200933 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200935 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 } else {
937 sockstate = SOCKET_OPERATION_OK;
938 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200939
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000940 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000941 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000942 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000943 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
945 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000946 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000947 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
949 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000950 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000951 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
953 break;
954 }
955 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200956 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 if (ret < 1)
958 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000959
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200960 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000961
962error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200963 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000964 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000965}
966
Thomas Woutersed03b412007-08-28 21:37:11 +0000967static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300968_asn1obj2py(const ASN1_OBJECT *name, int no_name)
969{
970 char buf[X509_NAME_MAXLEN];
971 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300973 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000974
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300975 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000976 if (buflen < 0) {
977 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300978 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300980 /* initial buffer is too small for oid + terminating null byte */
981 if (buflen > X509_NAME_MAXLEN - 1) {
982 /* make OBJ_obj2txt() calculate the required buflen */
983 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
984 /* allocate len + 1 for terminating NULL byte */
985 namebuf = PyMem_Malloc(buflen + 1);
986 if (namebuf == NULL) {
987 PyErr_NoMemory();
988 return NULL;
989 }
990 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
991 if (buflen < 0) {
992 _setSSLError(NULL, 0, __FILE__, __LINE__);
993 goto done;
994 }
995 }
996 if (!buflen && no_name) {
997 Py_INCREF(Py_None);
998 name_obj = Py_None;
999 }
1000 else {
1001 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1002 }
1003
1004 done:
1005 if (buf != namebuf) {
1006 PyMem_Free(namebuf);
1007 }
1008 return name_obj;
1009}
1010
1011static PyObject *
1012_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1013{
1014 Py_ssize_t buflen;
1015 unsigned char *valuebuf = NULL;
1016 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1019 if (buflen < 0) {
1020 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001021 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001023 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001024 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001026}
1027
1028static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001029_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001030{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001031 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1032 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1033 PyObject *rdnt;
1034 PyObject *attr = NULL; /* tuple to hold an attribute */
1035 int entry_count = X509_NAME_entry_count(xname);
1036 X509_NAME_ENTRY *entry;
1037 ASN1_OBJECT *name;
1038 ASN1_STRING *value;
1039 int index_counter;
1040 int rdn_level = -1;
1041 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 dn = PyList_New(0);
1044 if (dn == NULL)
1045 return NULL;
1046 /* now create another tuple to hold the top-level RDN */
1047 rdn = PyList_New(0);
1048 if (rdn == NULL)
1049 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001051 for (index_counter = 0;
1052 index_counter < entry_count;
1053 index_counter++)
1054 {
1055 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 /* check to see if we've gotten to a new RDN */
1058 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001059 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001060 /* yes, new RDN */
1061 /* add old RDN to DN */
1062 rdnt = PyList_AsTuple(rdn);
1063 Py_DECREF(rdn);
1064 if (rdnt == NULL)
1065 goto fail0;
1066 retcode = PyList_Append(dn, rdnt);
1067 Py_DECREF(rdnt);
1068 if (retcode < 0)
1069 goto fail0;
1070 /* create new RDN */
1071 rdn = PyList_New(0);
1072 if (rdn == NULL)
1073 goto fail0;
1074 }
1075 }
Christian Heimes598894f2016-09-05 23:19:05 +02001076 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001078 /* now add this attribute to the current RDN */
1079 name = X509_NAME_ENTRY_get_object(entry);
1080 value = X509_NAME_ENTRY_get_data(entry);
1081 attr = _create_tuple_for_attribute(name, value);
1082 /*
1083 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1084 entry->set,
1085 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1086 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1087 */
1088 if (attr == NULL)
1089 goto fail1;
1090 retcode = PyList_Append(rdn, attr);
1091 Py_DECREF(attr);
1092 if (retcode < 0)
1093 goto fail1;
1094 }
1095 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001096 if (rdn != NULL) {
1097 if (PyList_GET_SIZE(rdn) > 0) {
1098 rdnt = PyList_AsTuple(rdn);
1099 Py_DECREF(rdn);
1100 if (rdnt == NULL)
1101 goto fail0;
1102 retcode = PyList_Append(dn, rdnt);
1103 Py_DECREF(rdnt);
1104 if (retcode < 0)
1105 goto fail0;
1106 }
1107 else {
1108 Py_DECREF(rdn);
1109 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 /* convert list to tuple */
1113 rdnt = PyList_AsTuple(dn);
1114 Py_DECREF(dn);
1115 if (rdnt == NULL)
1116 return NULL;
1117 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001118
1119 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001120 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001121
1122 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001123 Py_XDECREF(dn);
1124 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001125}
1126
1127static PyObject *
1128_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001129
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001130 /* this code follows the procedure outlined in
1131 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1132 function to extract the STACK_OF(GENERAL_NAME),
1133 then iterates through the stack to add the
1134 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001136 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001138 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001139 GENERAL_NAMES *names = NULL;
1140 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 BIO *biobuf = NULL;
1142 char buf[2048];
1143 char *vptr;
1144 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001146 if (certificate == NULL)
1147 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001148
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001149 /* get a memory buffer */
1150 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001151
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001152 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1153 certificate, NID_subject_alt_name, NULL, NULL);
1154 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 if (peer_alt_names == Py_None) {
1156 peer_alt_names = PyList_New(0);
1157 if (peer_alt_names == NULL)
1158 goto fail;
1159 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001163 int gntype;
1164 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001166 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001167 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001168 switch (gntype) {
1169 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 /* we special-case DirName as a tuple of
1171 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001173 t = PyTuple_New(2);
1174 if (t == NULL) {
1175 goto fail;
1176 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 v = PyUnicode_FromString("DirName");
1179 if (v == NULL) {
1180 Py_DECREF(t);
1181 goto fail;
1182 }
1183 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001184
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 v = _create_tuple_for_X509_NAME (name->d.dirn);
1186 if (v == NULL) {
1187 Py_DECREF(t);
1188 goto fail;
1189 }
1190 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001191 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001192
Christian Heimes824f7f32013-08-17 00:54:47 +02001193 case GEN_EMAIL:
1194 case GEN_DNS:
1195 case GEN_URI:
1196 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1197 correctly, CVE-2013-4238 */
1198 t = PyTuple_New(2);
1199 if (t == NULL)
1200 goto fail;
1201 switch (gntype) {
1202 case GEN_EMAIL:
1203 v = PyUnicode_FromString("email");
1204 as = name->d.rfc822Name;
1205 break;
1206 case GEN_DNS:
1207 v = PyUnicode_FromString("DNS");
1208 as = name->d.dNSName;
1209 break;
1210 case GEN_URI:
1211 v = PyUnicode_FromString("URI");
1212 as = name->d.uniformResourceIdentifier;
1213 break;
1214 }
1215 if (v == NULL) {
1216 Py_DECREF(t);
1217 goto fail;
1218 }
1219 PyTuple_SET_ITEM(t, 0, v);
1220 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1221 ASN1_STRING_length(as));
1222 if (v == NULL) {
1223 Py_DECREF(t);
1224 goto fail;
1225 }
1226 PyTuple_SET_ITEM(t, 1, v);
1227 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001228
Christian Heimes1c03abd2016-09-06 23:25:35 +02001229 case GEN_RID:
1230 t = PyTuple_New(2);
1231 if (t == NULL)
1232 goto fail;
1233
1234 v = PyUnicode_FromString("Registered ID");
1235 if (v == NULL) {
1236 Py_DECREF(t);
1237 goto fail;
1238 }
1239 PyTuple_SET_ITEM(t, 0, v);
1240
1241 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1242 if (len < 0) {
1243 Py_DECREF(t);
1244 _setSSLError(NULL, 0, __FILE__, __LINE__);
1245 goto fail;
1246 } else if (len >= (int)sizeof(buf)) {
1247 v = PyUnicode_FromString("<INVALID>");
1248 } else {
1249 v = PyUnicode_FromStringAndSize(buf, len);
1250 }
1251 if (v == NULL) {
1252 Py_DECREF(t);
1253 goto fail;
1254 }
1255 PyTuple_SET_ITEM(t, 1, v);
1256 break;
1257
Christian Heimes824f7f32013-08-17 00:54:47 +02001258 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001259 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001260 switch (gntype) {
1261 /* check for new general name type */
1262 case GEN_OTHERNAME:
1263 case GEN_X400:
1264 case GEN_EDIPARTY:
1265 case GEN_IPADD:
1266 case GEN_RID:
1267 break;
1268 default:
1269 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1270 "Unknown general name type %d",
1271 gntype) == -1) {
1272 goto fail;
1273 }
1274 break;
1275 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 (void) BIO_reset(biobuf);
1277 GENERAL_NAME_print(biobuf, name);
1278 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1279 if (len < 0) {
1280 _setSSLError(NULL, 0, __FILE__, __LINE__);
1281 goto fail;
1282 }
1283 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001284 if (vptr == NULL) {
1285 PyErr_Format(PyExc_ValueError,
1286 "Invalid value %.200s",
1287 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001288 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001289 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 t = PyTuple_New(2);
1291 if (t == NULL)
1292 goto fail;
1293 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1294 if (v == NULL) {
1295 Py_DECREF(t);
1296 goto fail;
1297 }
1298 PyTuple_SET_ITEM(t, 0, v);
1299 v = PyUnicode_FromStringAndSize((vptr + 1),
1300 (len - (vptr - buf + 1)));
1301 if (v == NULL) {
1302 Py_DECREF(t);
1303 goto fail;
1304 }
1305 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001306 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001307 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001308
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 if (PyList_Append(peer_alt_names, t) < 0) {
1312 Py_DECREF(t);
1313 goto fail;
1314 }
1315 Py_DECREF(t);
1316 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001317 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001318 }
1319 BIO_free(biobuf);
1320 if (peer_alt_names != Py_None) {
1321 v = PyList_AsTuple(peer_alt_names);
1322 Py_DECREF(peer_alt_names);
1323 return v;
1324 } else {
1325 return peer_alt_names;
1326 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001327
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001328
1329 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001330 if (biobuf != NULL)
1331 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 if (peer_alt_names != Py_None) {
1334 Py_XDECREF(peer_alt_names);
1335 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001338}
1339
1340static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001341_get_aia_uri(X509 *certificate, int nid) {
1342 PyObject *lst = NULL, *ostr = NULL;
1343 int i, result;
1344 AUTHORITY_INFO_ACCESS *info;
1345
1346 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001347 if (info == NULL)
1348 return Py_None;
1349 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1350 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001351 return Py_None;
1352 }
1353
1354 if ((lst = PyList_New(0)) == NULL) {
1355 goto fail;
1356 }
1357
1358 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1359 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1360 ASN1_IA5STRING *uri;
1361
1362 if ((OBJ_obj2nid(ad->method) != nid) ||
1363 (ad->location->type != GEN_URI)) {
1364 continue;
1365 }
1366 uri = ad->location->d.uniformResourceIdentifier;
1367 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1368 uri->length);
1369 if (ostr == NULL) {
1370 goto fail;
1371 }
1372 result = PyList_Append(lst, ostr);
1373 Py_DECREF(ostr);
1374 if (result < 0) {
1375 goto fail;
1376 }
1377 }
1378 AUTHORITY_INFO_ACCESS_free(info);
1379
1380 /* convert to tuple or None */
1381 if (PyList_Size(lst) == 0) {
1382 Py_DECREF(lst);
1383 return Py_None;
1384 } else {
1385 PyObject *tup;
1386 tup = PyList_AsTuple(lst);
1387 Py_DECREF(lst);
1388 return tup;
1389 }
1390
1391 fail:
1392 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001393 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001394 return NULL;
1395}
1396
1397static PyObject *
1398_get_crl_dp(X509 *certificate) {
1399 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001400 int i, j;
1401 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001402
Christian Heimes598894f2016-09-05 23:19:05 +02001403 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001404
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001405 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001406 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001407
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001408 lst = PyList_New(0);
1409 if (lst == NULL)
1410 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001411
1412 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1413 DIST_POINT *dp;
1414 STACK_OF(GENERAL_NAME) *gns;
1415
1416 dp = sk_DIST_POINT_value(dps, i);
1417 gns = dp->distpoint->name.fullname;
1418
1419 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1420 GENERAL_NAME *gn;
1421 ASN1_IA5STRING *uri;
1422 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001423 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001424
1425 gn = sk_GENERAL_NAME_value(gns, j);
1426 if (gn->type != GEN_URI) {
1427 continue;
1428 }
1429 uri = gn->d.uniformResourceIdentifier;
1430 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1431 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001432 if (ouri == NULL)
1433 goto done;
1434
1435 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001436 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001437 if (err < 0)
1438 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001439 }
1440 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001441
1442 /* Convert to tuple. */
1443 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1444
1445 done:
1446 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001447 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001448 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001449}
1450
1451static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001452_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001454 PyObject *retval = NULL;
1455 BIO *biobuf = NULL;
1456 PyObject *peer;
1457 PyObject *peer_alt_names = NULL;
1458 PyObject *issuer;
1459 PyObject *version;
1460 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001461 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 ASN1_INTEGER *serialNumber;
1463 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001464 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001465 ASN1_TIME *notBefore, *notAfter;
1466 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001467
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001468 retval = PyDict_New();
1469 if (retval == NULL)
1470 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 peer = _create_tuple_for_X509_NAME(
1473 X509_get_subject_name(certificate));
1474 if (peer == NULL)
1475 goto fail0;
1476 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1477 Py_DECREF(peer);
1478 goto fail0;
1479 }
1480 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001481
Antoine Pitroufb046912010-11-09 20:21:19 +00001482 issuer = _create_tuple_for_X509_NAME(
1483 X509_get_issuer_name(certificate));
1484 if (issuer == NULL)
1485 goto fail0;
1486 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001488 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001489 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001490 Py_DECREF(issuer);
1491
1492 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001493 if (version == NULL)
1494 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001495 if (PyDict_SetItemString(retval, "version", version) < 0) {
1496 Py_DECREF(version);
1497 goto fail0;
1498 }
1499 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001500
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001501 /* get a memory buffer */
1502 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001503
Antoine Pitroufb046912010-11-09 20:21:19 +00001504 (void) BIO_reset(biobuf);
1505 serialNumber = X509_get_serialNumber(certificate);
1506 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1507 i2a_ASN1_INTEGER(biobuf, serialNumber);
1508 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1509 if (len < 0) {
1510 _setSSLError(NULL, 0, __FILE__, __LINE__);
1511 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001512 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001513 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1514 if (sn_obj == NULL)
1515 goto fail1;
1516 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1517 Py_DECREF(sn_obj);
1518 goto fail1;
1519 }
1520 Py_DECREF(sn_obj);
1521
1522 (void) BIO_reset(biobuf);
1523 notBefore = X509_get_notBefore(certificate);
1524 ASN1_TIME_print(biobuf, notBefore);
1525 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1526 if (len < 0) {
1527 _setSSLError(NULL, 0, __FILE__, __LINE__);
1528 goto fail1;
1529 }
1530 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1531 if (pnotBefore == NULL)
1532 goto fail1;
1533 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1534 Py_DECREF(pnotBefore);
1535 goto fail1;
1536 }
1537 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001538
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 (void) BIO_reset(biobuf);
1540 notAfter = X509_get_notAfter(certificate);
1541 ASN1_TIME_print(biobuf, notAfter);
1542 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1543 if (len < 0) {
1544 _setSSLError(NULL, 0, __FILE__, __LINE__);
1545 goto fail1;
1546 }
1547 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1548 if (pnotAfter == NULL)
1549 goto fail1;
1550 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1551 Py_DECREF(pnotAfter);
1552 goto fail1;
1553 }
1554 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001557
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001558 peer_alt_names = _get_peer_alt_names(certificate);
1559 if (peer_alt_names == NULL)
1560 goto fail1;
1561 else if (peer_alt_names != Py_None) {
1562 if (PyDict_SetItemString(retval, "subjectAltName",
1563 peer_alt_names) < 0) {
1564 Py_DECREF(peer_alt_names);
1565 goto fail1;
1566 }
1567 Py_DECREF(peer_alt_names);
1568 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001569
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001570 /* Authority Information Access: OCSP URIs */
1571 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1572 if (obj == NULL) {
1573 goto fail1;
1574 } else if (obj != Py_None) {
1575 result = PyDict_SetItemString(retval, "OCSP", obj);
1576 Py_DECREF(obj);
1577 if (result < 0) {
1578 goto fail1;
1579 }
1580 }
1581
1582 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1583 if (obj == NULL) {
1584 goto fail1;
1585 } else if (obj != Py_None) {
1586 result = PyDict_SetItemString(retval, "caIssuers", obj);
1587 Py_DECREF(obj);
1588 if (result < 0) {
1589 goto fail1;
1590 }
1591 }
1592
1593 /* CDP (CRL distribution points) */
1594 obj = _get_crl_dp(certificate);
1595 if (obj == NULL) {
1596 goto fail1;
1597 } else if (obj != Py_None) {
1598 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1599 Py_DECREF(obj);
1600 if (result < 0) {
1601 goto fail1;
1602 }
1603 }
1604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 BIO_free(biobuf);
1606 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001607
1608 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 if (biobuf != NULL)
1610 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001611 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 Py_XDECREF(retval);
1613 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001614}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001615
Christian Heimes9a5395a2013-06-17 15:44:12 +02001616static PyObject *
1617_certificate_to_der(X509 *certificate)
1618{
1619 unsigned char *bytes_buf = NULL;
1620 int len;
1621 PyObject *retval;
1622
1623 bytes_buf = NULL;
1624 len = i2d_X509(certificate, &bytes_buf);
1625 if (len < 0) {
1626 _setSSLError(NULL, 0, __FILE__, __LINE__);
1627 return NULL;
1628 }
1629 /* this is actually an immutable bytes sequence */
1630 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1631 OPENSSL_free(bytes_buf);
1632 return retval;
1633}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001634
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001635/*[clinic input]
1636_ssl._test_decode_cert
1637 path: object(converter="PyUnicode_FSConverter")
1638 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001639
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001640[clinic start generated code]*/
1641
1642static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001643_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1644/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001645{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001646 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001647 X509 *x=NULL;
1648 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001649
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1651 PyErr_SetString(PySSLErrorObject,
1652 "Can't malloc memory to read file");
1653 goto fail0;
1654 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001655
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001656 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001657 PyErr_SetString(PySSLErrorObject,
1658 "Can't open file");
1659 goto fail0;
1660 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001661
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001662 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1663 if (x == NULL) {
1664 PyErr_SetString(PySSLErrorObject,
1665 "Error decoding PEM-encoded file");
1666 goto fail0;
1667 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001668
Antoine Pitroufb046912010-11-09 20:21:19 +00001669 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001670 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001671
1672 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001673 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 if (cert != NULL) BIO_free(cert);
1675 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676}
1677
1678
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001679/*[clinic input]
1680_ssl._SSLSocket.peer_certificate
1681 der as binary_mode: bool = False
1682 /
1683
1684Returns the certificate for the peer.
1685
1686If no certificate was provided, returns None. If a certificate was
1687provided, but not validated, returns an empty dictionary. Otherwise
1688returns a dict containing information about the peer certificate.
1689
1690If the optional argument is True, returns a DER-encoded copy of the
1691peer certificate, or None if no certificate was provided. This will
1692return the certificate even if it wasn't validated.
1693[clinic start generated code]*/
1694
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001695static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001696_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1697/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001698{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001699 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001700 X509 *peer_cert;
1701 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001702
Christian Heimes66dc33b2017-05-23 16:02:02 -07001703 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001704 PyErr_SetString(PyExc_ValueError,
1705 "handshake not done yet");
1706 return NULL;
1707 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001708 peer_cert = SSL_get_peer_certificate(self->ssl);
1709 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001710 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001711
Antoine Pitrou721738f2012-08-15 23:20:39 +02001712 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001713 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001714 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001715 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001716 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001717 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001718 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001719 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001720 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001721 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001722 X509_free(peer_cert);
1723 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001724}
1725
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001726static PyObject *
1727cipher_to_tuple(const SSL_CIPHER *cipher)
1728{
1729 const char *cipher_name, *cipher_protocol;
1730 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001731 if (retval == NULL)
1732 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001733
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001734 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001735 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001736 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001737 PyTuple_SET_ITEM(retval, 0, Py_None);
1738 } else {
1739 v = PyUnicode_FromString(cipher_name);
1740 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001741 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001742 PyTuple_SET_ITEM(retval, 0, v);
1743 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001744
1745 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001746 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001747 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001748 PyTuple_SET_ITEM(retval, 1, Py_None);
1749 } else {
1750 v = PyUnicode_FromString(cipher_protocol);
1751 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001752 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001753 PyTuple_SET_ITEM(retval, 1, v);
1754 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001755
1756 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001758 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001759 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001760
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001761 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001762
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001763 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001764 Py_DECREF(retval);
1765 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001766}
1767
Christian Heimes25bfcd52016-09-06 00:04:45 +02001768#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1769static PyObject *
1770cipher_to_dict(const SSL_CIPHER *cipher)
1771{
1772 const char *cipher_name, *cipher_protocol;
1773
1774 unsigned long cipher_id;
1775 int alg_bits, strength_bits, len;
1776 char buf[512] = {0};
1777#if OPENSSL_VERSION_1_1
1778 int aead, nid;
1779 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1780#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001781
1782 /* can be NULL */
1783 cipher_name = SSL_CIPHER_get_name(cipher);
1784 cipher_protocol = SSL_CIPHER_get_version(cipher);
1785 cipher_id = SSL_CIPHER_get_id(cipher);
1786 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001787 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1788 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001789 if (len > 1 && buf[len-1] == '\n')
1790 buf[len-1] = '\0';
1791 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1792
1793#if OPENSSL_VERSION_1_1
1794 aead = SSL_CIPHER_is_aead(cipher);
1795 nid = SSL_CIPHER_get_cipher_nid(cipher);
1796 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1797 nid = SSL_CIPHER_get_digest_nid(cipher);
1798 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1799 nid = SSL_CIPHER_get_kx_nid(cipher);
1800 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1801 nid = SSL_CIPHER_get_auth_nid(cipher);
1802 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1803#endif
1804
Victor Stinner410b9882016-09-12 12:00:23 +02001805 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001806 "{sksssssssisi"
1807#if OPENSSL_VERSION_1_1
1808 "sOssssssss"
1809#endif
1810 "}",
1811 "id", cipher_id,
1812 "name", cipher_name,
1813 "protocol", cipher_protocol,
1814 "description", buf,
1815 "strength_bits", strength_bits,
1816 "alg_bits", alg_bits
1817#if OPENSSL_VERSION_1_1
1818 ,"aead", aead ? Py_True : Py_False,
1819 "symmetric", skcipher,
1820 "digest", digest,
1821 "kea", kx,
1822 "auth", auth
1823#endif
1824 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001825}
1826#endif
1827
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001828/*[clinic input]
1829_ssl._SSLSocket.shared_ciphers
1830[clinic start generated code]*/
1831
1832static PyObject *
1833_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1834/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001835{
1836 STACK_OF(SSL_CIPHER) *ciphers;
1837 int i;
1838 PyObject *res;
1839
Christian Heimes598894f2016-09-05 23:19:05 +02001840 ciphers = SSL_get_ciphers(self->ssl);
1841 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001842 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001843 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1844 if (!res)
1845 return NULL;
1846 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1847 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1848 if (!tup) {
1849 Py_DECREF(res);
1850 return NULL;
1851 }
1852 PyList_SET_ITEM(res, i, tup);
1853 }
1854 return res;
1855}
1856
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001857/*[clinic input]
1858_ssl._SSLSocket.cipher
1859[clinic start generated code]*/
1860
1861static PyObject *
1862_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1863/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001864{
1865 const SSL_CIPHER *current;
1866
1867 if (self->ssl == NULL)
1868 Py_RETURN_NONE;
1869 current = SSL_get_current_cipher(self->ssl);
1870 if (current == NULL)
1871 Py_RETURN_NONE;
1872 return cipher_to_tuple(current);
1873}
1874
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001875/*[clinic input]
1876_ssl._SSLSocket.version
1877[clinic start generated code]*/
1878
1879static PyObject *
1880_ssl__SSLSocket_version_impl(PySSLSocket *self)
1881/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001882{
1883 const char *version;
1884
1885 if (self->ssl == NULL)
1886 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001887 if (!SSL_is_init_finished(self->ssl)) {
1888 /* handshake not finished */
1889 Py_RETURN_NONE;
1890 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001891 version = SSL_get_version(self->ssl);
1892 if (!strcmp(version, "unknown"))
1893 Py_RETURN_NONE;
1894 return PyUnicode_FromString(version);
1895}
1896
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001897#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001898/*[clinic input]
1899_ssl._SSLSocket.selected_npn_protocol
1900[clinic start generated code]*/
1901
1902static PyObject *
1903_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1904/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1905{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001906 const unsigned char *out;
1907 unsigned int outlen;
1908
Victor Stinner4569cd52013-06-23 14:58:43 +02001909 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001910 &out, &outlen);
1911
1912 if (out == NULL)
1913 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001914 return PyUnicode_FromStringAndSize((char *)out, outlen);
1915}
1916#endif
1917
1918#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001919/*[clinic input]
1920_ssl._SSLSocket.selected_alpn_protocol
1921[clinic start generated code]*/
1922
1923static PyObject *
1924_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1925/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1926{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001927 const unsigned char *out;
1928 unsigned int outlen;
1929
1930 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1931
1932 if (out == NULL)
1933 Py_RETURN_NONE;
1934 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001935}
1936#endif
1937
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001938/*[clinic input]
1939_ssl._SSLSocket.compression
1940[clinic start generated code]*/
1941
1942static PyObject *
1943_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1944/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1945{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001946#ifdef OPENSSL_NO_COMP
1947 Py_RETURN_NONE;
1948#else
1949 const COMP_METHOD *comp_method;
1950 const char *short_name;
1951
1952 if (self->ssl == NULL)
1953 Py_RETURN_NONE;
1954 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001955 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001956 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001957 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001958 if (short_name == NULL)
1959 Py_RETURN_NONE;
1960 return PyUnicode_DecodeFSDefault(short_name);
1961#endif
1962}
1963
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001964static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1965 Py_INCREF(self->ctx);
1966 return self->ctx;
1967}
1968
1969static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1970 void *closure) {
1971
1972 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001973#if !HAVE_SNI
1974 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1975 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001976 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001977#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001978 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001979 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001980 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001981#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001982 } else {
1983 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1984 return -1;
1985 }
1986
1987 return 0;
1988}
1989
1990PyDoc_STRVAR(PySSL_set_context_doc,
1991"_setter_context(ctx)\n\
1992\
1993This changes the context associated with the SSLSocket. This is typically\n\
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08001994used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001995on the SSLContext to change the certificate information associated with the\n\
1996SSLSocket before the cryptographic exchange handshake messages\n");
1997
1998
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001999static PyObject *
2000PySSL_get_server_side(PySSLSocket *self, void *c)
2001{
2002 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2003}
2004
2005PyDoc_STRVAR(PySSL_get_server_side_doc,
2006"Whether this is a server-side socket.");
2007
2008static PyObject *
2009PySSL_get_server_hostname(PySSLSocket *self, void *c)
2010{
2011 if (self->server_hostname == NULL)
2012 Py_RETURN_NONE;
2013 Py_INCREF(self->server_hostname);
2014 return self->server_hostname;
2015}
2016
2017PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2018"The currently set server hostname (for SNI).");
2019
2020static PyObject *
2021PySSL_get_owner(PySSLSocket *self, void *c)
2022{
2023 PyObject *owner;
2024
2025 if (self->owner == NULL)
2026 Py_RETURN_NONE;
2027
2028 owner = PyWeakref_GetObject(self->owner);
2029 Py_INCREF(owner);
2030 return owner;
2031}
2032
2033static int
2034PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2035{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002036 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002037 if (self->owner == NULL)
2038 return -1;
2039 return 0;
2040}
2041
2042PyDoc_STRVAR(PySSL_get_owner_doc,
2043"The Python-level owner of this object.\
2044Passed as \"self\" in servername callback.");
2045
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002046
Antoine Pitrou152efa22010-05-16 18:19:27 +00002047static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002048{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 if (self->ssl)
2050 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002051 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002052 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002053 Py_XDECREF(self->server_hostname);
2054 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002055 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002056}
2057
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002058/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002059 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002060 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002061 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002062
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002063static int
Victor Stinner14690702015-04-06 22:46:13 +02002064PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002065{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002066 int rc;
2067#ifdef HAVE_POLL
2068 struct pollfd pollfd;
2069 _PyTime_t ms;
2070#else
2071 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002072 fd_set fds;
2073 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002074#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002077 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002079 else if (timeout < 0) {
2080 if (s->sock_timeout > 0)
2081 return SOCKET_HAS_TIMED_OUT;
2082 else
2083 return SOCKET_IS_BLOCKING;
2084 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002085
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002087 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002088 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002089
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002090 /* Prefer poll, if available, since you can poll() any fd
2091 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002092#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002093 pollfd.fd = s->sock_fd;
2094 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002095
Victor Stinner14690702015-04-06 22:46:13 +02002096 /* timeout is in seconds, poll() uses milliseconds */
2097 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002098 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002099
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002100 PySSL_BEGIN_ALLOW_THREADS
2101 rc = poll(&pollfd, 1, (int)ms);
2102 PySSL_END_ALLOW_THREADS
2103#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002104 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002105 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002107
Victor Stinner14690702015-04-06 22:46:13 +02002108 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002109
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002110 FD_ZERO(&fds);
2111 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002112
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002113 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002114 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002115 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002116 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002117 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002118 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002119 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002120 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002121#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002122
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002123 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2124 (when we are able to write or when there's something to read) */
2125 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002126}
2127
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002128/*[clinic input]
2129_ssl._SSLSocket.write
2130 b: Py_buffer
2131 /
2132
2133Writes the bytes-like object b into the SSL object.
2134
2135Returns the number of bytes written.
2136[clinic start generated code]*/
2137
2138static PyObject *
2139_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2140/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002141{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002142 int len;
2143 int sockstate;
2144 int err;
2145 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002146 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002147 _PyTime_t timeout, deadline = 0;
2148 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002149
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002150 if (sock != NULL) {
2151 if (((PyObject*)sock) == Py_None) {
2152 _setSSLError("Underlying socket connection gone",
2153 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2154 return NULL;
2155 }
2156 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 }
2158
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002159 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002160 PyErr_Format(PyExc_OverflowError,
2161 "string longer than %d bytes", INT_MAX);
2162 goto error;
2163 }
2164
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002165 if (sock != NULL) {
2166 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002167 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002168 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2169 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2170 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171
Victor Stinner14690702015-04-06 22:46:13 +02002172 timeout = GET_SOCKET_TIMEOUT(sock);
2173 has_timeout = (timeout > 0);
2174 if (has_timeout)
2175 deadline = _PyTime_GetMonotonicClock() + timeout;
2176
2177 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002179 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 "The write operation timed out");
2181 goto error;
2182 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2183 PyErr_SetString(PySSLErrorObject,
2184 "Underlying socket has been closed.");
2185 goto error;
2186 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2187 PyErr_SetString(PySSLErrorObject,
2188 "Underlying socket too large for select().");
2189 goto error;
2190 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002191
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002194 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002195 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002197 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002198
2199 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002200 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002201
Victor Stinner14690702015-04-06 22:46:13 +02002202 if (has_timeout)
2203 timeout = deadline - _PyTime_GetMonotonicClock();
2204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002205 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002206 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002208 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002209 } else {
2210 sockstate = SOCKET_OPERATION_OK;
2211 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002214 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002215 "The write operation timed out");
2216 goto error;
2217 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2218 PyErr_SetString(PySSLErrorObject,
2219 "Underlying socket has been closed.");
2220 goto error;
2221 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2222 break;
2223 }
2224 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002225
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002226 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 if (len > 0)
2228 return PyLong_FromLong(len);
2229 else
2230 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002231
2232error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002233 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002235}
2236
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002237/*[clinic input]
2238_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002239
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002240Returns the number of already decrypted bytes available for read, pending on the connection.
2241[clinic start generated code]*/
2242
2243static PyObject *
2244_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2245/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002246{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 PySSL_BEGIN_ALLOW_THREADS
2250 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002251 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002252 PySSL_END_ALLOW_THREADS
2253 if (count < 0)
2254 return PySSL_SetError(self, count, __FILE__, __LINE__);
2255 else
2256 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002257}
2258
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002259/*[clinic input]
2260_ssl._SSLSocket.read
2261 size as len: int
2262 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002263 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002264 ]
2265 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002266
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002267Read up to size bytes from the SSL socket.
2268[clinic start generated code]*/
2269
2270static PyObject *
2271_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2272 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002273/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002274{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002277 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 int sockstate;
2279 int err;
2280 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002281 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002282 _PyTime_t timeout, deadline = 0;
2283 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002284
Martin Panter5503d472016-03-27 05:35:19 +00002285 if (!group_right_1 && len < 0) {
2286 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2287 return NULL;
2288 }
2289
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002290 if (sock != NULL) {
2291 if (((PyObject*)sock) == Py_None) {
2292 _setSSLError("Underlying socket connection gone",
2293 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2294 return NULL;
2295 }
2296 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 }
2298
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002299 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002300 dest = PyBytes_FromStringAndSize(NULL, len);
2301 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002302 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002303 if (len == 0) {
2304 Py_XDECREF(sock);
2305 return dest;
2306 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002307 mem = PyBytes_AS_STRING(dest);
2308 }
2309 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002310 mem = buffer->buf;
2311 if (len <= 0 || len > buffer->len) {
2312 len = (int) buffer->len;
2313 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002314 PyErr_SetString(PyExc_OverflowError,
2315 "maximum length can't fit in a C 'int'");
2316 goto error;
2317 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002318 if (len == 0) {
2319 count = 0;
2320 goto done;
2321 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002322 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002323 }
2324
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002325 if (sock != NULL) {
2326 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002327 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002328 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2329 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2330 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331
Victor Stinner14690702015-04-06 22:46:13 +02002332 timeout = GET_SOCKET_TIMEOUT(sock);
2333 has_timeout = (timeout > 0);
2334 if (has_timeout)
2335 deadline = _PyTime_GetMonotonicClock() + timeout;
2336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 PySSL_BEGIN_ALLOW_THREADS
2339 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002340 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002341 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 if (PyErr_CheckSignals())
2344 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002345
Victor Stinner14690702015-04-06 22:46:13 +02002346 if (has_timeout)
2347 timeout = deadline - _PyTime_GetMonotonicClock();
2348
Steve Dowere6eb48c2017-09-08 15:16:15 -07002349 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002351 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002353 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002354 } else if (err == SSL_ERROR_ZERO_RETURN &&
2355 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 {
2357 count = 0;
2358 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002360 else
2361 sockstate = SOCKET_OPERATION_OK;
2362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002364 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 "The read operation timed out");
2366 goto error;
2367 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2368 break;
2369 }
2370 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002371
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002372 if (count <= 0) {
2373 PySSL_SetError(self, count, __FILE__, __LINE__);
2374 goto error;
2375 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002376
2377done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002378 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002379 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002380 _PyBytes_Resize(&dest, count);
2381 return dest;
2382 }
2383 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 return PyLong_FromLong(count);
2385 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002386
2387error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002388 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002389 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002390 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002391 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002392}
2393
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002394/*[clinic input]
2395_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002396
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002397Does the SSL shutdown handshake with the remote end.
2398
2399Returns the underlying socket object.
2400[clinic start generated code]*/
2401
2402static PyObject *
2403_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2404/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002405{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002406 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002407 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002408 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002409 _PyTime_t timeout, deadline = 0;
2410 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002411
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002412 if (sock != NULL) {
2413 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002414 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002415 _setSSLError("Underlying socket connection gone",
2416 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2417 return NULL;
2418 }
2419 Py_INCREF(sock);
2420
2421 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002422 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002423 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2424 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002425 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002426
Victor Stinner14690702015-04-06 22:46:13 +02002427 timeout = GET_SOCKET_TIMEOUT(sock);
2428 has_timeout = (timeout > 0);
2429 if (has_timeout)
2430 deadline = _PyTime_GetMonotonicClock() + timeout;
2431
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002432 while (1) {
2433 PySSL_BEGIN_ALLOW_THREADS
2434 /* Disable read-ahead so that unwrap can work correctly.
2435 * Otherwise OpenSSL might read in too much data,
2436 * eating clear text data that happens to be
2437 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002438 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439 * function is used and the shutdown_seen_zero != 0
2440 * condition is met.
2441 */
2442 if (self->shutdown_seen_zero)
2443 SSL_set_read_ahead(self->ssl, 0);
2444 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002445 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002446 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002447
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002448 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2449 if (err > 0)
2450 break;
2451 if (err == 0) {
2452 /* Don't loop endlessly; instead preserve legacy
2453 behaviour of trying SSL_shutdown() only twice.
2454 This looks necessary for OpenSSL < 0.9.8m */
2455 if (++zeros > 1)
2456 break;
2457 /* Shutdown was sent, now try receiving */
2458 self->shutdown_seen_zero = 1;
2459 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002460 }
2461
Victor Stinner14690702015-04-06 22:46:13 +02002462 if (has_timeout)
2463 timeout = deadline - _PyTime_GetMonotonicClock();
2464
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002465 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002466 _PySSL_UPDATE_ERRNO(self, err);
2467 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002468 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002469 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002470 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002471 else
2472 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002473
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002474 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002475 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002476 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002477 "The read operation timed out");
2478 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002479 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002480 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002481 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002482 }
2483 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2484 PyErr_SetString(PySSLErrorObject,
2485 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002486 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 }
2488 else if (sockstate != SOCKET_OPERATION_OK)
2489 /* Retain the SSL error code */
2490 break;
2491 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002492
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002493 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002494 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002495 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002496 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002497 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002498 /* It's already INCREF'ed */
2499 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002500 else
2501 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002502
2503error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002504 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002505 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002506}
2507
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002508/*[clinic input]
2509_ssl._SSLSocket.tls_unique_cb
2510
2511Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2512
2513If the TLS handshake is not yet complete, None is returned.
2514[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002515
Antoine Pitroud6494802011-07-21 01:11:30 +02002516static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002517_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2518/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002519{
2520 PyObject *retval = NULL;
2521 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002522 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002523
2524 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2525 /* if session is resumed XOR we are the client */
2526 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2527 }
2528 else {
2529 /* if a new session XOR we are the server */
2530 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2531 }
2532
2533 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002534 if (len == 0)
2535 Py_RETURN_NONE;
2536
2537 retval = PyBytes_FromStringAndSize(buf, len);
2538
2539 return retval;
2540}
2541
Christian Heimes99a65702016-09-10 23:44:53 +02002542#ifdef OPENSSL_VERSION_1_1
2543
2544static SSL_SESSION*
2545_ssl_session_dup(SSL_SESSION *session) {
2546 SSL_SESSION *newsession = NULL;
2547 int slen;
2548 unsigned char *senc = NULL, *p;
2549 const unsigned char *const_p;
2550
2551 if (session == NULL) {
2552 PyErr_SetString(PyExc_ValueError, "Invalid session");
2553 goto error;
2554 }
2555
2556 /* get length */
2557 slen = i2d_SSL_SESSION(session, NULL);
2558 if (slen == 0 || slen > 0xFF00) {
2559 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2560 goto error;
2561 }
2562 if ((senc = PyMem_Malloc(slen)) == NULL) {
2563 PyErr_NoMemory();
2564 goto error;
2565 }
2566 p = senc;
2567 if (!i2d_SSL_SESSION(session, &p)) {
2568 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2569 goto error;
2570 }
2571 const_p = senc;
2572 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2573 if (session == NULL) {
2574 goto error;
2575 }
2576 PyMem_Free(senc);
2577 return newsession;
2578 error:
2579 if (senc != NULL) {
2580 PyMem_Free(senc);
2581 }
2582 return NULL;
2583}
2584#endif
2585
2586static PyObject *
2587PySSL_get_session(PySSLSocket *self, void *closure) {
2588 /* get_session can return sessions from a server-side connection,
2589 * it does not check for handshake done or client socket. */
2590 PySSLSession *pysess;
2591 SSL_SESSION *session;
2592
2593#ifdef OPENSSL_VERSION_1_1
2594 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2595 * https://github.com/openssl/openssl/issues/1550 */
2596 session = SSL_get0_session(self->ssl); /* borrowed reference */
2597 if (session == NULL) {
2598 Py_RETURN_NONE;
2599 }
2600 if ((session = _ssl_session_dup(session)) == NULL) {
2601 return NULL;
2602 }
2603#else
2604 session = SSL_get1_session(self->ssl);
2605 if (session == NULL) {
2606 Py_RETURN_NONE;
2607 }
2608#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002609 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002610 if (pysess == NULL) {
2611 SSL_SESSION_free(session);
2612 return NULL;
2613 }
2614
2615 assert(self->ctx);
2616 pysess->ctx = self->ctx;
2617 Py_INCREF(pysess->ctx);
2618 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002619 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002620 return (PyObject *)pysess;
2621}
2622
2623static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2624 void *closure)
2625 {
2626 PySSLSession *pysess;
2627#ifdef OPENSSL_VERSION_1_1
2628 SSL_SESSION *session;
2629#endif
2630 int result;
2631
2632 if (!PySSLSession_Check(value)) {
2633 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2634 return -1;
2635 }
2636 pysess = (PySSLSession *)value;
2637
2638 if (self->ctx->ctx != pysess->ctx->ctx) {
2639 PyErr_SetString(PyExc_ValueError,
2640 "Session refers to a different SSLContext.");
2641 return -1;
2642 }
2643 if (self->socket_type != PY_SSL_CLIENT) {
2644 PyErr_SetString(PyExc_ValueError,
2645 "Cannot set session for server-side SSLSocket.");
2646 return -1;
2647 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002648 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002649 PyErr_SetString(PyExc_ValueError,
2650 "Cannot set session after handshake.");
2651 return -1;
2652 }
2653#ifdef OPENSSL_VERSION_1_1
2654 /* duplicate session */
2655 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2656 return -1;
2657 }
2658 result = SSL_set_session(self->ssl, session);
2659 /* free duplicate, SSL_set_session() bumps ref count */
2660 SSL_SESSION_free(session);
2661#else
2662 result = SSL_set_session(self->ssl, pysess->session);
2663#endif
2664 if (result == 0) {
2665 _setSSLError(NULL, 0, __FILE__, __LINE__);
2666 return -1;
2667 }
2668 return 0;
2669}
2670
2671PyDoc_STRVAR(PySSL_set_session_doc,
2672"_setter_session(session)\n\
2673\
2674Get / set SSLSession.");
2675
2676static PyObject *
2677PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2678 if (SSL_session_reused(self->ssl)) {
2679 Py_RETURN_TRUE;
2680 } else {
2681 Py_RETURN_FALSE;
2682 }
2683}
2684
2685PyDoc_STRVAR(PySSL_get_session_reused_doc,
2686"Was the client session reused during handshake?");
2687
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002688static PyGetSetDef ssl_getsetlist[] = {
2689 {"context", (getter) PySSL_get_context,
2690 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002691 {"server_side", (getter) PySSL_get_server_side, NULL,
2692 PySSL_get_server_side_doc},
2693 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2694 PySSL_get_server_hostname_doc},
2695 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2696 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002697 {"session", (getter) PySSL_get_session,
2698 (setter) PySSL_set_session, PySSL_set_session_doc},
2699 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2700 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002701 {NULL}, /* sentinel */
2702};
2703
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002704static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002705 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2706 _SSL__SSLSOCKET_WRITE_METHODDEF
2707 _SSL__SSLSOCKET_READ_METHODDEF
2708 _SSL__SSLSOCKET_PENDING_METHODDEF
2709 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2710 _SSL__SSLSOCKET_CIPHER_METHODDEF
2711 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2712 _SSL__SSLSOCKET_VERSION_METHODDEF
2713 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2714 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2715 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2716 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2717 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002718 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002719};
2720
Antoine Pitrou152efa22010-05-16 18:19:27 +00002721static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002722 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002723 "_ssl._SSLSocket", /*tp_name*/
2724 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002725 0, /*tp_itemsize*/
2726 /* methods */
2727 (destructor)PySSL_dealloc, /*tp_dealloc*/
2728 0, /*tp_print*/
2729 0, /*tp_getattr*/
2730 0, /*tp_setattr*/
2731 0, /*tp_reserved*/
2732 0, /*tp_repr*/
2733 0, /*tp_as_number*/
2734 0, /*tp_as_sequence*/
2735 0, /*tp_as_mapping*/
2736 0, /*tp_hash*/
2737 0, /*tp_call*/
2738 0, /*tp_str*/
2739 0, /*tp_getattro*/
2740 0, /*tp_setattro*/
2741 0, /*tp_as_buffer*/
2742 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2743 0, /*tp_doc*/
2744 0, /*tp_traverse*/
2745 0, /*tp_clear*/
2746 0, /*tp_richcompare*/
2747 0, /*tp_weaklistoffset*/
2748 0, /*tp_iter*/
2749 0, /*tp_iternext*/
2750 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002751 0, /*tp_members*/
2752 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002753};
2754
Antoine Pitrou152efa22010-05-16 18:19:27 +00002755
2756/*
2757 * _SSLContext objects
2758 */
2759
Christian Heimes5fe668c2016-09-12 00:01:11 +02002760static int
2761_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2762{
2763 int mode;
2764 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2765
2766 switch(n) {
2767 case PY_SSL_CERT_NONE:
2768 mode = SSL_VERIFY_NONE;
2769 break;
2770 case PY_SSL_CERT_OPTIONAL:
2771 mode = SSL_VERIFY_PEER;
2772 break;
2773 case PY_SSL_CERT_REQUIRED:
2774 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2775 break;
2776 default:
2777 PyErr_SetString(PyExc_ValueError,
2778 "invalid value for verify_mode");
2779 return -1;
2780 }
2781 /* keep current verify cb */
2782 verify_cb = SSL_CTX_get_verify_callback(ctx);
2783 SSL_CTX_set_verify(ctx, mode, verify_cb);
2784 return 0;
2785}
2786
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002787/*[clinic input]
2788@classmethod
2789_ssl._SSLContext.__new__
2790 protocol as proto_version: int
2791 /
2792[clinic start generated code]*/
2793
Antoine Pitrou152efa22010-05-16 18:19:27 +00002794static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002795_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2796/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002797{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002798 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002799 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002800 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002801 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002802 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002803#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002804 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002805#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002806
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807 PySSL_BEGIN_ALLOW_THREADS
2808 if (proto_version == PY_SSL_VERSION_TLS1)
2809 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002810#if HAVE_TLSv1_2
2811 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2812 ctx = SSL_CTX_new(TLSv1_1_method());
2813 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2814 ctx = SSL_CTX_new(TLSv1_2_method());
2815#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002816#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002817 else if (proto_version == PY_SSL_VERSION_SSL3)
2818 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002819#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002820#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002821 else if (proto_version == PY_SSL_VERSION_SSL2)
2822 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002823#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002824 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002825 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002826 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2827 ctx = SSL_CTX_new(TLS_client_method());
2828 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2829 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002830 else
2831 proto_version = -1;
2832 PySSL_END_ALLOW_THREADS
2833
2834 if (proto_version == -1) {
2835 PyErr_SetString(PyExc_ValueError,
2836 "invalid protocol version");
2837 return NULL;
2838 }
2839 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002840 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002841 return NULL;
2842 }
2843
2844 assert(type != NULL && type->tp_alloc != NULL);
2845 self = (PySSLContext *) type->tp_alloc(type, 0);
2846 if (self == NULL) {
2847 SSL_CTX_free(ctx);
2848 return NULL;
2849 }
2850 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002851 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002852 self->protocol = proto_version;
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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002860 self->set_sni_cb = 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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002971 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002972#endif
2973 return 0;
2974}
2975
2976static int
2977context_clear(PySSLContext *self)
2978{
2979#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002980 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002981#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
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003357static PyObject *
3358get_protocol(PySSLContext *self, void *c) {
3359 return PyLong_FromLong(self->protocol);
3360}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003361
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003362typedef struct {
3363 PyThreadState *thread_state;
3364 PyObject *callable;
3365 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003366 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003367 int error;
3368} _PySSLPasswordInfo;
3369
3370static int
3371_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3372 const char *bad_type_error)
3373{
3374 /* Set the password and size fields of a _PySSLPasswordInfo struct
3375 from a unicode, bytes, or byte array object.
3376 The password field will be dynamically allocated and must be freed
3377 by the caller */
3378 PyObject *password_bytes = NULL;
3379 const char *data = NULL;
3380 Py_ssize_t size;
3381
3382 if (PyUnicode_Check(password)) {
3383 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3384 if (!password_bytes) {
3385 goto error;
3386 }
3387 data = PyBytes_AS_STRING(password_bytes);
3388 size = PyBytes_GET_SIZE(password_bytes);
3389 } else if (PyBytes_Check(password)) {
3390 data = PyBytes_AS_STRING(password);
3391 size = PyBytes_GET_SIZE(password);
3392 } else if (PyByteArray_Check(password)) {
3393 data = PyByteArray_AS_STRING(password);
3394 size = PyByteArray_GET_SIZE(password);
3395 } else {
3396 PyErr_SetString(PyExc_TypeError, bad_type_error);
3397 goto error;
3398 }
3399
Victor Stinner9ee02032013-06-23 15:08:23 +02003400 if (size > (Py_ssize_t)INT_MAX) {
3401 PyErr_Format(PyExc_ValueError,
3402 "password cannot be longer than %d bytes", INT_MAX);
3403 goto error;
3404 }
3405
Victor Stinner11ebff22013-07-07 17:07:52 +02003406 PyMem_Free(pw_info->password);
3407 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003408 if (!pw_info->password) {
3409 PyErr_SetString(PyExc_MemoryError,
3410 "unable to allocate password buffer");
3411 goto error;
3412 }
3413 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003414 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003415
3416 Py_XDECREF(password_bytes);
3417 return 1;
3418
3419error:
3420 Py_XDECREF(password_bytes);
3421 return 0;
3422}
3423
3424static int
3425_password_callback(char *buf, int size, int rwflag, void *userdata)
3426{
3427 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3428 PyObject *fn_ret = NULL;
3429
3430 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3431
3432 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003433 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003434 if (!fn_ret) {
3435 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3436 core python API, so we could use it to add a frame here */
3437 goto error;
3438 }
3439
3440 if (!_pwinfo_set(pw_info, fn_ret,
3441 "password callback must return a string")) {
3442 goto error;
3443 }
3444 Py_CLEAR(fn_ret);
3445 }
3446
3447 if (pw_info->size > size) {
3448 PyErr_Format(PyExc_ValueError,
3449 "password cannot be longer than %d bytes", size);
3450 goto error;
3451 }
3452
3453 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3454 memcpy(buf, pw_info->password, pw_info->size);
3455 return pw_info->size;
3456
3457error:
3458 Py_XDECREF(fn_ret);
3459 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3460 pw_info->error = 1;
3461 return -1;
3462}
3463
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003464/*[clinic input]
3465_ssl._SSLContext.load_cert_chain
3466 certfile: object
3467 keyfile: object = NULL
3468 password: object = NULL
3469
3470[clinic start generated code]*/
3471
Antoine Pitroub5218772010-05-21 09:56:06 +00003472static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003473_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3474 PyObject *keyfile, PyObject *password)
3475/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003476{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003477 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003478 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3479 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003480 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003481 int r;
3482
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003483 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003484 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003485 if (keyfile == Py_None)
3486 keyfile = NULL;
3487 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3488 PyErr_SetString(PyExc_TypeError,
3489 "certfile should be a valid filesystem path");
3490 return NULL;
3491 }
3492 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3493 PyErr_SetString(PyExc_TypeError,
3494 "keyfile should be a valid filesystem path");
3495 goto error;
3496 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003497 if (password && password != Py_None) {
3498 if (PyCallable_Check(password)) {
3499 pw_info.callable = password;
3500 } else if (!_pwinfo_set(&pw_info, password,
3501 "password should be a string or callable")) {
3502 goto error;
3503 }
3504 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3505 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3506 }
3507 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003508 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3509 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003510 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003511 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003512 if (pw_info.error) {
3513 ERR_clear_error();
3514 /* the password callback has already set the error information */
3515 }
3516 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003517 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003518 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003519 }
3520 else {
3521 _setSSLError(NULL, 0, __FILE__, __LINE__);
3522 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003523 goto error;
3524 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003525 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003526 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003527 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3528 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003529 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3530 Py_CLEAR(keyfile_bytes);
3531 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003532 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003533 if (pw_info.error) {
3534 ERR_clear_error();
3535 /* the password callback has already set the error information */
3536 }
3537 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003538 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003539 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003540 }
3541 else {
3542 _setSSLError(NULL, 0, __FILE__, __LINE__);
3543 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003544 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003546 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003547 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003548 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003549 if (r != 1) {
3550 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003551 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003552 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003553 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3554 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003555 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003556 Py_RETURN_NONE;
3557
3558error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003559 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3560 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003561 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003562 Py_XDECREF(keyfile_bytes);
3563 Py_XDECREF(certfile_bytes);
3564 return NULL;
3565}
3566
Christian Heimesefff7062013-11-21 03:35:02 +01003567/* internal helper function, returns -1 on error
3568 */
3569static int
3570_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3571 int filetype)
3572{
3573 BIO *biobuf = NULL;
3574 X509_STORE *store;
3575 int retval = 0, err, loaded = 0;
3576
3577 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3578
3579 if (len <= 0) {
3580 PyErr_SetString(PyExc_ValueError,
3581 "Empty certificate data");
3582 return -1;
3583 } else if (len > INT_MAX) {
3584 PyErr_SetString(PyExc_OverflowError,
3585 "Certificate data is too long.");
3586 return -1;
3587 }
3588
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003589 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003590 if (biobuf == NULL) {
3591 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3592 return -1;
3593 }
3594
3595 store = SSL_CTX_get_cert_store(self->ctx);
3596 assert(store != NULL);
3597
3598 while (1) {
3599 X509 *cert = NULL;
3600 int r;
3601
3602 if (filetype == SSL_FILETYPE_ASN1) {
3603 cert = d2i_X509_bio(biobuf, NULL);
3604 } else {
3605 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003606 SSL_CTX_get_default_passwd_cb(self->ctx),
3607 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3608 );
Christian Heimesefff7062013-11-21 03:35:02 +01003609 }
3610 if (cert == NULL) {
3611 break;
3612 }
3613 r = X509_STORE_add_cert(store, cert);
3614 X509_free(cert);
3615 if (!r) {
3616 err = ERR_peek_last_error();
3617 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3618 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3619 /* cert already in hash table, not an error */
3620 ERR_clear_error();
3621 } else {
3622 break;
3623 }
3624 }
3625 loaded++;
3626 }
3627
3628 err = ERR_peek_last_error();
3629 if ((filetype == SSL_FILETYPE_ASN1) &&
3630 (loaded > 0) &&
3631 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3632 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3633 /* EOF ASN1 file, not an error */
3634 ERR_clear_error();
3635 retval = 0;
3636 } else if ((filetype == SSL_FILETYPE_PEM) &&
3637 (loaded > 0) &&
3638 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3639 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3640 /* EOF PEM file, not an error */
3641 ERR_clear_error();
3642 retval = 0;
3643 } else {
3644 _setSSLError(NULL, 0, __FILE__, __LINE__);
3645 retval = -1;
3646 }
3647
3648 BIO_free(biobuf);
3649 return retval;
3650}
3651
3652
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003653/*[clinic input]
3654_ssl._SSLContext.load_verify_locations
3655 cafile: object = NULL
3656 capath: object = NULL
3657 cadata: object = NULL
3658
3659[clinic start generated code]*/
3660
Antoine Pitrou152efa22010-05-16 18:19:27 +00003661static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003662_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3663 PyObject *cafile,
3664 PyObject *capath,
3665 PyObject *cadata)
3666/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003667{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003668 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3669 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003670 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003671
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003672 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003673 if (cafile == Py_None)
3674 cafile = NULL;
3675 if (capath == Py_None)
3676 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003677 if (cadata == Py_None)
3678 cadata = NULL;
3679
3680 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003681 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003682 "cafile, capath and cadata cannot be all omitted");
3683 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003684 }
3685 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3686 PyErr_SetString(PyExc_TypeError,
3687 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003688 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003689 }
3690 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003691 PyErr_SetString(PyExc_TypeError,
3692 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003693 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003694 }
Christian Heimesefff7062013-11-21 03:35:02 +01003695
3696 /* validata cadata type and load cadata */
3697 if (cadata) {
3698 Py_buffer buf;
3699 PyObject *cadata_ascii = NULL;
3700
3701 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3702 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3703 PyBuffer_Release(&buf);
3704 PyErr_SetString(PyExc_TypeError,
3705 "cadata should be a contiguous buffer with "
3706 "a single dimension");
3707 goto error;
3708 }
3709 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3710 PyBuffer_Release(&buf);
3711 if (r == -1) {
3712 goto error;
3713 }
3714 } else {
3715 PyErr_Clear();
3716 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3717 if (cadata_ascii == NULL) {
3718 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003719 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003720 "bytes-like object");
3721 goto error;
3722 }
3723 r = _add_ca_certs(self,
3724 PyBytes_AS_STRING(cadata_ascii),
3725 PyBytes_GET_SIZE(cadata_ascii),
3726 SSL_FILETYPE_PEM);
3727 Py_DECREF(cadata_ascii);
3728 if (r == -1) {
3729 goto error;
3730 }
3731 }
3732 }
3733
3734 /* load cafile or capath */
3735 if (cafile || capath) {
3736 if (cafile)
3737 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3738 if (capath)
3739 capath_buf = PyBytes_AS_STRING(capath_bytes);
3740 PySSL_BEGIN_ALLOW_THREADS
3741 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3742 PySSL_END_ALLOW_THREADS
3743 if (r != 1) {
3744 ok = 0;
3745 if (errno != 0) {
3746 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003747 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003748 }
3749 else {
3750 _setSSLError(NULL, 0, __FILE__, __LINE__);
3751 }
3752 goto error;
3753 }
3754 }
3755 goto end;
3756
3757 error:
3758 ok = 0;
3759 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003760 Py_XDECREF(cafile_bytes);
3761 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003762 if (ok) {
3763 Py_RETURN_NONE;
3764 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003765 return NULL;
3766 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003767}
3768
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003769/*[clinic input]
3770_ssl._SSLContext.load_dh_params
3771 path as filepath: object
3772 /
3773
3774[clinic start generated code]*/
3775
Antoine Pitrou152efa22010-05-16 18:19:27 +00003776static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003777_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3778/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003779{
3780 FILE *f;
3781 DH *dh;
3782
Victor Stinnerdaf45552013-08-28 00:53:59 +02003783 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003784 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003785 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003786
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003787 errno = 0;
3788 PySSL_BEGIN_ALLOW_THREADS
3789 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003790 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003791 PySSL_END_ALLOW_THREADS
3792 if (dh == NULL) {
3793 if (errno != 0) {
3794 ERR_clear_error();
3795 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3796 }
3797 else {
3798 _setSSLError(NULL, 0, __FILE__, __LINE__);
3799 }
3800 return NULL;
3801 }
3802 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3803 _setSSLError(NULL, 0, __FILE__, __LINE__);
3804 DH_free(dh);
3805 Py_RETURN_NONE;
3806}
3807
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003808/*[clinic input]
3809_ssl._SSLContext._wrap_socket
3810 sock: object(subclass_of="PySocketModule.Sock_Type")
3811 server_side: int
3812 server_hostname as hostname_obj: object = None
3813
3814[clinic start generated code]*/
3815
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003816static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003817_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3818 int server_side, PyObject *hostname_obj)
3819/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003820{
Antoine Pitroud5323212010-10-22 18:19:07 +00003821 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003822 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003823
Antoine Pitroud5323212010-10-22 18:19:07 +00003824 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003825 as IDN A-label (ASCII str). */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003826 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003827 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003828 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003829 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003830
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003831 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3832 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003833 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003834 if (hostname != NULL)
3835 PyMem_Free(hostname);
3836 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003837}
3838
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003839/*[clinic input]
3840_ssl._SSLContext._wrap_bio
3841 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3842 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3843 server_side: int
3844 server_hostname as hostname_obj: object = None
3845
3846[clinic start generated code]*/
3847
Antoine Pitroub0182c82010-10-12 20:09:02 +00003848static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003849_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3850 PySSLMemoryBIO *outgoing, int server_side,
3851 PyObject *hostname_obj)
3852/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003853{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003854 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003855 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003856
3857 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003858 as IDN A-label (ASCII str). */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003859 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003860 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003861 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003862 }
3863
3864 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3865 incoming, outgoing);
3866
3867 PyMem_Free(hostname);
3868 return res;
3869}
3870
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003871/*[clinic input]
3872_ssl._SSLContext.session_stats
3873[clinic start generated code]*/
3874
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003875static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003876_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3877/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003878{
3879 int r;
3880 PyObject *value, *stats = PyDict_New();
3881 if (!stats)
3882 return NULL;
3883
3884#define ADD_STATS(SSL_NAME, KEY_NAME) \
3885 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3886 if (value == NULL) \
3887 goto error; \
3888 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3889 Py_DECREF(value); \
3890 if (r < 0) \
3891 goto error;
3892
3893 ADD_STATS(number, "number");
3894 ADD_STATS(connect, "connect");
3895 ADD_STATS(connect_good, "connect_good");
3896 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3897 ADD_STATS(accept, "accept");
3898 ADD_STATS(accept_good, "accept_good");
3899 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3900 ADD_STATS(accept, "accept");
3901 ADD_STATS(hits, "hits");
3902 ADD_STATS(misses, "misses");
3903 ADD_STATS(timeouts, "timeouts");
3904 ADD_STATS(cache_full, "cache_full");
3905
3906#undef ADD_STATS
3907
3908 return stats;
3909
3910error:
3911 Py_DECREF(stats);
3912 return NULL;
3913}
3914
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003915/*[clinic input]
3916_ssl._SSLContext.set_default_verify_paths
3917[clinic start generated code]*/
3918
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003919static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003920_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3921/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003922{
3923 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3924 _setSSLError(NULL, 0, __FILE__, __LINE__);
3925 return NULL;
3926 }
3927 Py_RETURN_NONE;
3928}
3929
Antoine Pitrou501da612011-12-21 09:27:41 +01003930#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003931/*[clinic input]
3932_ssl._SSLContext.set_ecdh_curve
3933 name: object
3934 /
3935
3936[clinic start generated code]*/
3937
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003938static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003939_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3940/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003941{
3942 PyObject *name_bytes;
3943 int nid;
3944 EC_KEY *key;
3945
3946 if (!PyUnicode_FSConverter(name, &name_bytes))
3947 return NULL;
3948 assert(PyBytes_Check(name_bytes));
3949 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3950 Py_DECREF(name_bytes);
3951 if (nid == 0) {
3952 PyErr_Format(PyExc_ValueError,
3953 "unknown elliptic curve name %R", name);
3954 return NULL;
3955 }
3956 key = EC_KEY_new_by_curve_name(nid);
3957 if (key == NULL) {
3958 _setSSLError(NULL, 0, __FILE__, __LINE__);
3959 return NULL;
3960 }
3961 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3962 EC_KEY_free(key);
3963 Py_RETURN_NONE;
3964}
Antoine Pitrou501da612011-12-21 09:27:41 +01003965#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003966
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003967#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003968static int
3969_servername_callback(SSL *s, int *al, void *args)
3970{
3971 int ret;
3972 PySSLContext *ssl_ctx = (PySSLContext *) args;
3973 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003974 PyObject *result;
3975 /* The high-level ssl.SSLSocket object */
3976 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003977 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003978 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003979
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003980 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003981 /* remove race condition in this the call back while if removing the
3982 * callback is in progress */
3983 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003984 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003985 }
3986
3987 ssl = SSL_get_app_data(s);
3988 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003989
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003990 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003991 * SSL connection and that has a .context attribute that can be changed to
3992 * identify the requested hostname. Since the official API is the Python
3993 * level API we want to pass the callback a Python level object rather than
3994 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3995 * SSLObject) that will be passed. Otherwise if there's a socket then that
3996 * will be passed. If both do not exist only then the C-level object is
3997 * passed. */
3998 if (ssl->owner)
3999 ssl_socket = PyWeakref_GetObject(ssl->owner);
4000 else if (ssl->Socket)
4001 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4002 else
4003 ssl_socket = (PyObject *) ssl;
4004
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004005 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004006 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004007 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004008
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004009 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004010 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004011 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004012 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004013 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004014 PyObject *servername_bytes;
4015 PyObject *servername_str;
4016
4017 servername_bytes = PyBytes_FromString(servername);
4018 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004019 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4020 goto error;
4021 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004022 /* server_hostname was encoded to an A-label by our caller; put it
4023 * back into a str object, but still as an A-label (bpo-28414)
4024 */
4025 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4026 Py_DECREF(servername_bytes);
4027 if (servername_str == NULL) {
4028 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004029 goto error;
4030 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004031 result = PyObject_CallFunctionObjArgs(
4032 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4033 ssl_ctx, NULL);
4034 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004035 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004036 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004037
4038 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004039 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004040 *al = SSL_AD_HANDSHAKE_FAILURE;
4041 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4042 }
4043 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004044 /* Result may be None, a SSLContext or an integer
4045 * None and SSLContext are OK, integer or other values are an error.
4046 */
4047 if (result == Py_None) {
4048 ret = SSL_TLSEXT_ERR_OK;
4049 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004050 *al = (int) PyLong_AsLong(result);
4051 if (PyErr_Occurred()) {
4052 PyErr_WriteUnraisable(result);
4053 *al = SSL_AD_INTERNAL_ERROR;
4054 }
4055 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4056 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004057 Py_DECREF(result);
4058 }
4059
4060 PyGILState_Release(gstate);
4061 return ret;
4062
4063error:
4064 Py_DECREF(ssl_socket);
4065 *al = SSL_AD_INTERNAL_ERROR;
4066 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4067 PyGILState_Release(gstate);
4068 return ret;
4069}
Antoine Pitroua5963382013-03-30 16:39:00 +01004070#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004071
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004072static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004073get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004074{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004075 PyObject *cb = self->set_sni_cb;
4076 if (cb == NULL) {
4077 Py_RETURN_NONE;
4078 }
4079 Py_INCREF(cb);
4080 return cb;
4081}
4082
4083static int
4084set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4085{
4086 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4087 PyErr_SetString(PyExc_ValueError,
4088 "sni_callback cannot be set on TLS_CLIENT context");
4089 return -1;
4090 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004091#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004092 Py_CLEAR(self->set_sni_cb);
4093 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004094 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4095 }
4096 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004097 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004098 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4099 PyErr_SetString(PyExc_TypeError,
4100 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004101 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004102 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004103 Py_INCREF(arg);
4104 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004105 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4106 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4107 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004108 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004109#else
4110 PyErr_SetString(PyExc_NotImplementedError,
4111 "The TLS extension servername callback, "
4112 "SSL_CTX_set_tlsext_servername_callback, "
4113 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004114 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004115#endif
4116}
4117
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004118PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4119"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4120\n\
4121If the argument is None then the callback is disabled. The method is called\n\
4122with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4123See RFC 6066 for details of the SNI extension.");
4124
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004125/*[clinic input]
4126_ssl._SSLContext.cert_store_stats
4127
4128Returns quantities of loaded X.509 certificates.
4129
4130X.509 certificates with a CA extension and certificate revocation lists
4131inside the context's cert store.
4132
4133NOTE: Certificates in a capath directory aren't loaded unless they have
4134been used at least once.
4135[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004136
4137static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4139/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004140{
4141 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004142 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004143 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004144 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004145
4146 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004147 objs = X509_STORE_get0_objects(store);
4148 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4149 obj = sk_X509_OBJECT_value(objs, i);
4150 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004151 case X509_LU_X509:
4152 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004153 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004154 ca++;
4155 }
4156 break;
4157 case X509_LU_CRL:
4158 crl++;
4159 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004160 default:
4161 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4162 * As far as I can tell they are internal states and never
4163 * stored in a cert store */
4164 break;
4165 }
4166 }
4167 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4168 "x509_ca", ca);
4169}
4170
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004171/*[clinic input]
4172_ssl._SSLContext.get_ca_certs
4173 binary_form: bool = False
4174
4175Returns a list of dicts with information of loaded CA certs.
4176
4177If the optional argument is True, returns a DER-encoded copy of the CA
4178certificate.
4179
4180NOTE: Certificates in a capath directory aren't loaded unless they have
4181been used at least once.
4182[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004183
4184static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4186/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004187{
4188 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004189 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004190 PyObject *ci = NULL, *rlist = NULL;
4191 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004192
4193 if ((rlist = PyList_New(0)) == NULL) {
4194 return NULL;
4195 }
4196
4197 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004198 objs = X509_STORE_get0_objects(store);
4199 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004200 X509_OBJECT *obj;
4201 X509 *cert;
4202
Christian Heimes598894f2016-09-05 23:19:05 +02004203 obj = sk_X509_OBJECT_value(objs, i);
4204 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004205 /* not a x509 cert */
4206 continue;
4207 }
4208 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004209 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004210 if (!X509_check_ca(cert)) {
4211 continue;
4212 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004213 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004214 ci = _certificate_to_der(cert);
4215 } else {
4216 ci = _decode_certificate(cert);
4217 }
4218 if (ci == NULL) {
4219 goto error;
4220 }
4221 if (PyList_Append(rlist, ci) == -1) {
4222 goto error;
4223 }
4224 Py_CLEAR(ci);
4225 }
4226 return rlist;
4227
4228 error:
4229 Py_XDECREF(ci);
4230 Py_XDECREF(rlist);
4231 return NULL;
4232}
4233
4234
Antoine Pitrou152efa22010-05-16 18:19:27 +00004235static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004236 {"check_hostname", (getter) get_check_hostname,
4237 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004238 {"_host_flags", (getter) get_host_flags,
4239 (setter) set_host_flags, NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004240 {"sni_callback", (getter) get_sni_callback,
4241 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004242 {"options", (getter) get_options,
4243 (setter) set_options, NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004244 {"protocol", (getter) get_protocol,
4245 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004246 {"verify_flags", (getter) get_verify_flags,
4247 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004248 {"verify_mode", (getter) get_verify_mode,
4249 (setter) set_verify_mode, NULL},
4250 {NULL}, /* sentinel */
4251};
4252
4253static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004254 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4255 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4256 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4257 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4258 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4259 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4260 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4261 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4262 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4263 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4264 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004265 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4266 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004267 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004268 {NULL, NULL} /* sentinel */
4269};
4270
4271static PyTypeObject PySSLContext_Type = {
4272 PyVarObject_HEAD_INIT(NULL, 0)
4273 "_ssl._SSLContext", /*tp_name*/
4274 sizeof(PySSLContext), /*tp_basicsize*/
4275 0, /*tp_itemsize*/
4276 (destructor)context_dealloc, /*tp_dealloc*/
4277 0, /*tp_print*/
4278 0, /*tp_getattr*/
4279 0, /*tp_setattr*/
4280 0, /*tp_reserved*/
4281 0, /*tp_repr*/
4282 0, /*tp_as_number*/
4283 0, /*tp_as_sequence*/
4284 0, /*tp_as_mapping*/
4285 0, /*tp_hash*/
4286 0, /*tp_call*/
4287 0, /*tp_str*/
4288 0, /*tp_getattro*/
4289 0, /*tp_setattro*/
4290 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004291 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004292 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004293 (traverseproc) context_traverse, /*tp_traverse*/
4294 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004295 0, /*tp_richcompare*/
4296 0, /*tp_weaklistoffset*/
4297 0, /*tp_iter*/
4298 0, /*tp_iternext*/
4299 context_methods, /*tp_methods*/
4300 0, /*tp_members*/
4301 context_getsetlist, /*tp_getset*/
4302 0, /*tp_base*/
4303 0, /*tp_dict*/
4304 0, /*tp_descr_get*/
4305 0, /*tp_descr_set*/
4306 0, /*tp_dictoffset*/
4307 0, /*tp_init*/
4308 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004309 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004310};
4311
4312
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004313/*
4314 * MemoryBIO objects
4315 */
4316
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004317/*[clinic input]
4318@classmethod
4319_ssl.MemoryBIO.__new__
4320
4321[clinic start generated code]*/
4322
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004323static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004324_ssl_MemoryBIO_impl(PyTypeObject *type)
4325/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004326{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004327 BIO *bio;
4328 PySSLMemoryBIO *self;
4329
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004330 bio = BIO_new(BIO_s_mem());
4331 if (bio == NULL) {
4332 PyErr_SetString(PySSLErrorObject,
4333 "failed to allocate BIO");
4334 return NULL;
4335 }
4336 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4337 * just that no data is currently available. The SSL routines should retry
4338 * the read, which we can achieve by calling BIO_set_retry_read(). */
4339 BIO_set_retry_read(bio);
4340 BIO_set_mem_eof_return(bio, -1);
4341
4342 assert(type != NULL && type->tp_alloc != NULL);
4343 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4344 if (self == NULL) {
4345 BIO_free(bio);
4346 return NULL;
4347 }
4348 self->bio = bio;
4349 self->eof_written = 0;
4350
4351 return (PyObject *) self;
4352}
4353
4354static void
4355memory_bio_dealloc(PySSLMemoryBIO *self)
4356{
4357 BIO_free(self->bio);
4358 Py_TYPE(self)->tp_free(self);
4359}
4360
4361static PyObject *
4362memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4363{
Segev Finer5cff6372017-07-27 01:19:17 +03004364 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004365}
4366
4367PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4368"The number of bytes pending in the memory BIO.");
4369
4370static PyObject *
4371memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4372{
4373 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4374 && self->eof_written);
4375}
4376
4377PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4378"Whether the memory BIO is at EOF.");
4379
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004380/*[clinic input]
4381_ssl.MemoryBIO.read
4382 size as len: int = -1
4383 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004384
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004385Read up to size bytes from the memory BIO.
4386
4387If size is not specified, read the entire buffer.
4388If the return value is an empty bytes instance, this means either
4389EOF or that no data is available. Use the "eof" property to
4390distinguish between the two.
4391[clinic start generated code]*/
4392
4393static PyObject *
4394_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4395/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4396{
4397 int avail, nbytes;
4398 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004399
Segev Finer5cff6372017-07-27 01:19:17 +03004400 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004401 if ((len < 0) || (len > avail))
4402 len = avail;
4403
4404 result = PyBytes_FromStringAndSize(NULL, len);
4405 if ((result == NULL) || (len == 0))
4406 return result;
4407
4408 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4409 /* There should never be any short reads but check anyway. */
4410 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4411 Py_DECREF(result);
4412 return NULL;
4413 }
4414
4415 return result;
4416}
4417
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004418/*[clinic input]
4419_ssl.MemoryBIO.write
4420 b: Py_buffer
4421 /
4422
4423Writes the bytes b into the memory BIO.
4424
4425Returns the number of bytes written.
4426[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004427
4428static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004429_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4430/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004431{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004432 int nbytes;
4433
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004434 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004435 PyErr_Format(PyExc_OverflowError,
4436 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004437 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004438 }
4439
4440 if (self->eof_written) {
4441 PyErr_SetString(PySSLErrorObject,
4442 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004443 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004444 }
4445
Segev Finer5cff6372017-07-27 01:19:17 +03004446 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004447 if (nbytes < 0) {
4448 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004449 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004450 }
4451
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004452 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004453}
4454
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004455/*[clinic input]
4456_ssl.MemoryBIO.write_eof
4457
4458Write an EOF marker to the memory BIO.
4459
4460When all data has been read, the "eof" property will be True.
4461[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004462
4463static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004464_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4465/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004466{
4467 self->eof_written = 1;
4468 /* After an EOF is written, a zero return from read() should be a real EOF
4469 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4470 BIO_clear_retry_flags(self->bio);
4471 BIO_set_mem_eof_return(self->bio, 0);
4472
4473 Py_RETURN_NONE;
4474}
4475
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004476static PyGetSetDef memory_bio_getsetlist[] = {
4477 {"pending", (getter) memory_bio_get_pending, NULL,
4478 PySSL_memory_bio_pending_doc},
4479 {"eof", (getter) memory_bio_get_eof, NULL,
4480 PySSL_memory_bio_eof_doc},
4481 {NULL}, /* sentinel */
4482};
4483
4484static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004485 _SSL_MEMORYBIO_READ_METHODDEF
4486 _SSL_MEMORYBIO_WRITE_METHODDEF
4487 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004488 {NULL, NULL} /* sentinel */
4489};
4490
4491static PyTypeObject PySSLMemoryBIO_Type = {
4492 PyVarObject_HEAD_INIT(NULL, 0)
4493 "_ssl.MemoryBIO", /*tp_name*/
4494 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4495 0, /*tp_itemsize*/
4496 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4497 0, /*tp_print*/
4498 0, /*tp_getattr*/
4499 0, /*tp_setattr*/
4500 0, /*tp_reserved*/
4501 0, /*tp_repr*/
4502 0, /*tp_as_number*/
4503 0, /*tp_as_sequence*/
4504 0, /*tp_as_mapping*/
4505 0, /*tp_hash*/
4506 0, /*tp_call*/
4507 0, /*tp_str*/
4508 0, /*tp_getattro*/
4509 0, /*tp_setattro*/
4510 0, /*tp_as_buffer*/
4511 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4512 0, /*tp_doc*/
4513 0, /*tp_traverse*/
4514 0, /*tp_clear*/
4515 0, /*tp_richcompare*/
4516 0, /*tp_weaklistoffset*/
4517 0, /*tp_iter*/
4518 0, /*tp_iternext*/
4519 memory_bio_methods, /*tp_methods*/
4520 0, /*tp_members*/
4521 memory_bio_getsetlist, /*tp_getset*/
4522 0, /*tp_base*/
4523 0, /*tp_dict*/
4524 0, /*tp_descr_get*/
4525 0, /*tp_descr_set*/
4526 0, /*tp_dictoffset*/
4527 0, /*tp_init*/
4528 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004529 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004530};
4531
Antoine Pitrou152efa22010-05-16 18:19:27 +00004532
Christian Heimes99a65702016-09-10 23:44:53 +02004533/*
4534 * SSL Session object
4535 */
4536
4537static void
4538PySSLSession_dealloc(PySSLSession *self)
4539{
INADA Naokia6296d32017-08-24 14:55:17 +09004540 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004541 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004542 Py_XDECREF(self->ctx);
4543 if (self->session != NULL) {
4544 SSL_SESSION_free(self->session);
4545 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004546 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004547}
4548
4549static PyObject *
4550PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4551{
4552 int result;
4553
4554 if (left == NULL || right == NULL) {
4555 PyErr_BadInternalCall();
4556 return NULL;
4557 }
4558
4559 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4560 Py_RETURN_NOTIMPLEMENTED;
4561 }
4562
4563 if (left == right) {
4564 result = 0;
4565 } else {
4566 const unsigned char *left_id, *right_id;
4567 unsigned int left_len, right_len;
4568 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4569 &left_len);
4570 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4571 &right_len);
4572 if (left_len == right_len) {
4573 result = memcmp(left_id, right_id, left_len);
4574 } else {
4575 result = 1;
4576 }
4577 }
4578
4579 switch (op) {
4580 case Py_EQ:
4581 if (result == 0) {
4582 Py_RETURN_TRUE;
4583 } else {
4584 Py_RETURN_FALSE;
4585 }
4586 break;
4587 case Py_NE:
4588 if (result != 0) {
4589 Py_RETURN_TRUE;
4590 } else {
4591 Py_RETURN_FALSE;
4592 }
4593 break;
4594 case Py_LT:
4595 case Py_LE:
4596 case Py_GT:
4597 case Py_GE:
4598 Py_RETURN_NOTIMPLEMENTED;
4599 break;
4600 default:
4601 PyErr_BadArgument();
4602 return NULL;
4603 }
4604}
4605
4606static int
4607PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4608{
4609 Py_VISIT(self->ctx);
4610 return 0;
4611}
4612
4613static int
4614PySSLSession_clear(PySSLSession *self)
4615{
4616 Py_CLEAR(self->ctx);
4617 return 0;
4618}
4619
4620
4621static PyObject *
4622PySSLSession_get_time(PySSLSession *self, void *closure) {
4623 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4624}
4625
4626PyDoc_STRVAR(PySSLSession_get_time_doc,
4627"Session creation time (seconds since epoch).");
4628
4629
4630static PyObject *
4631PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4632 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4633}
4634
4635PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4636"Session timeout (delta in seconds).");
4637
4638
4639static PyObject *
4640PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4641 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4642 return PyLong_FromUnsignedLong(hint);
4643}
4644
4645PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4646"Ticket life time hint.");
4647
4648
4649static PyObject *
4650PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4651 const unsigned char *id;
4652 unsigned int len;
4653 id = SSL_SESSION_get_id(self->session, &len);
4654 return PyBytes_FromStringAndSize((const char *)id, len);
4655}
4656
4657PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4658"Session id");
4659
4660
4661static PyObject *
4662PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4663 if (SSL_SESSION_has_ticket(self->session)) {
4664 Py_RETURN_TRUE;
4665 } else {
4666 Py_RETURN_FALSE;
4667 }
4668}
4669
4670PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4671"Does the session contain a ticket?");
4672
4673
4674static PyGetSetDef PySSLSession_getsetlist[] = {
4675 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4676 PySSLSession_get_has_ticket_doc},
4677 {"id", (getter) PySSLSession_get_session_id, NULL,
4678 PySSLSession_get_session_id_doc},
4679 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4680 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4681 {"time", (getter) PySSLSession_get_time, NULL,
4682 PySSLSession_get_time_doc},
4683 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4684 PySSLSession_get_timeout_doc},
4685 {NULL}, /* sentinel */
4686};
4687
4688static PyTypeObject PySSLSession_Type = {
4689 PyVarObject_HEAD_INIT(NULL, 0)
4690 "_ssl.Session", /*tp_name*/
4691 sizeof(PySSLSession), /*tp_basicsize*/
4692 0, /*tp_itemsize*/
4693 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4694 0, /*tp_print*/
4695 0, /*tp_getattr*/
4696 0, /*tp_setattr*/
4697 0, /*tp_reserved*/
4698 0, /*tp_repr*/
4699 0, /*tp_as_number*/
4700 0, /*tp_as_sequence*/
4701 0, /*tp_as_mapping*/
4702 0, /*tp_hash*/
4703 0, /*tp_call*/
4704 0, /*tp_str*/
4705 0, /*tp_getattro*/
4706 0, /*tp_setattro*/
4707 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004708 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004709 0, /*tp_doc*/
4710 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4711 (inquiry)PySSLSession_clear, /*tp_clear*/
4712 PySSLSession_richcompare, /*tp_richcompare*/
4713 0, /*tp_weaklistoffset*/
4714 0, /*tp_iter*/
4715 0, /*tp_iternext*/
4716 0, /*tp_methods*/
4717 0, /*tp_members*/
4718 PySSLSession_getsetlist, /*tp_getset*/
4719};
4720
4721
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004722/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004723/*[clinic input]
4724_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004725 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004726 entropy: double
4727 /
4728
4729Mix string into the OpenSSL PRNG state.
4730
4731entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304732string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004733[clinic start generated code]*/
4734
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004735static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004736_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004737/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004738{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004739 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004740 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004742 buf = (const char *)view->buf;
4743 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004744 do {
4745 written = Py_MIN(len, INT_MAX);
4746 RAND_add(buf, (int)written, entropy);
4747 buf += written;
4748 len -= written;
4749 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004750 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004751}
4752
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004753static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004754PySSL_RAND(int len, int pseudo)
4755{
4756 int ok;
4757 PyObject *bytes;
4758 unsigned long err;
4759 const char *errstr;
4760 PyObject *v;
4761
Victor Stinner1e81a392013-12-19 16:47:04 +01004762 if (len < 0) {
4763 PyErr_SetString(PyExc_ValueError, "num must be positive");
4764 return NULL;
4765 }
4766
Victor Stinner99c8b162011-05-24 12:05:19 +02004767 bytes = PyBytes_FromStringAndSize(NULL, len);
4768 if (bytes == NULL)
4769 return NULL;
4770 if (pseudo) {
4771 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4772 if (ok == 0 || ok == 1)
4773 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4774 }
4775 else {
4776 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4777 if (ok == 1)
4778 return bytes;
4779 }
4780 Py_DECREF(bytes);
4781
4782 err = ERR_get_error();
4783 errstr = ERR_reason_error_string(err);
4784 v = Py_BuildValue("(ks)", err, errstr);
4785 if (v != NULL) {
4786 PyErr_SetObject(PySSLErrorObject, v);
4787 Py_DECREF(v);
4788 }
4789 return NULL;
4790}
4791
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004792/*[clinic input]
4793_ssl.RAND_bytes
4794 n: int
4795 /
4796
4797Generate n cryptographically strong pseudo-random bytes.
4798[clinic start generated code]*/
4799
Victor Stinner99c8b162011-05-24 12:05:19 +02004800static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004801_ssl_RAND_bytes_impl(PyObject *module, int n)
4802/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004803{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004804 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004805}
4806
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004807/*[clinic input]
4808_ssl.RAND_pseudo_bytes
4809 n: int
4810 /
4811
4812Generate n pseudo-random bytes.
4813
4814Return a pair (bytes, is_cryptographic). is_cryptographic is True
4815if the bytes generated are cryptographically strong.
4816[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004817
4818static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004819_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4820/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004821{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004822 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004823}
4824
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004825/*[clinic input]
4826_ssl.RAND_status
4827
4828Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4829
4830It is necessary to seed the PRNG with RAND_add() on some platforms before
4831using the ssl() function.
4832[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004833
4834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004835_ssl_RAND_status_impl(PyObject *module)
4836/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004837{
Christian Heimes217cfd12007-12-02 14:31:20 +00004838 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004839}
4840
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004841#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004842/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004843/*[clinic input]
4844_ssl.RAND_egd
4845 path: object(converter="PyUnicode_FSConverter")
4846 /
4847
4848Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4849
4850Returns number of bytes read. Raises SSLError if connection to EGD
4851fails or if it does not provide enough data to seed PRNG.
4852[clinic start generated code]*/
4853
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004855_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4856/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004857{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004858 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004859 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004860 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004861 PyErr_SetString(PySSLErrorObject,
4862 "EGD connection failed or EGD did not return "
4863 "enough data to seed the PRNG");
4864 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004865 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004866 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004867}
Christian Heimesa5d07652016-09-24 10:48:05 +02004868/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004869#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004870
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004872
4873/*[clinic input]
4874_ssl.get_default_verify_paths
4875
4876Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4877
4878The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4879[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004880
4881static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004882_ssl_get_default_verify_paths_impl(PyObject *module)
4883/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004884{
4885 PyObject *ofile_env = NULL;
4886 PyObject *ofile = NULL;
4887 PyObject *odir_env = NULL;
4888 PyObject *odir = NULL;
4889
Benjamin Petersond113c962015-07-18 10:59:13 -07004890#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004891 const char *tmp = (info); \
4892 target = NULL; \
4893 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4894 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4895 target = PyBytes_FromString(tmp); } \
4896 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004897 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004898
Benjamin Petersond113c962015-07-18 10:59:13 -07004899 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4900 CONVERT(X509_get_default_cert_file(), ofile);
4901 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4902 CONVERT(X509_get_default_cert_dir(), odir);
4903#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004904
Christian Heimes200bb1b2013-06-14 15:14:29 +02004905 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004906
4907 error:
4908 Py_XDECREF(ofile_env);
4909 Py_XDECREF(ofile);
4910 Py_XDECREF(odir_env);
4911 Py_XDECREF(odir);
4912 return NULL;
4913}
4914
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004915static PyObject*
4916asn1obj2py(ASN1_OBJECT *obj)
4917{
4918 int nid;
4919 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004920
4921 nid = OBJ_obj2nid(obj);
4922 if (nid == NID_undef) {
4923 PyErr_Format(PyExc_ValueError, "Unknown object");
4924 return NULL;
4925 }
4926 sn = OBJ_nid2sn(nid);
4927 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004928 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004929}
4930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004931/*[clinic input]
4932_ssl.txt2obj
4933 txt: str
4934 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004936Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4937
4938By default objects are looked up by OID. With name=True short and
4939long name are also matched.
4940[clinic start generated code]*/
4941
4942static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004943_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4944/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004945{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004946 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004947 ASN1_OBJECT *obj;
4948
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004949 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4950 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004951 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004952 return NULL;
4953 }
4954 result = asn1obj2py(obj);
4955 ASN1_OBJECT_free(obj);
4956 return result;
4957}
4958
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004959/*[clinic input]
4960_ssl.nid2obj
4961 nid: int
4962 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004963
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004964Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4965[clinic start generated code]*/
4966
4967static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004968_ssl_nid2obj_impl(PyObject *module, int nid)
4969/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004970{
4971 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004972 ASN1_OBJECT *obj;
4973
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004974 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004975 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004976 return NULL;
4977 }
4978 obj = OBJ_nid2obj(nid);
4979 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004980 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004981 return NULL;
4982 }
4983 result = asn1obj2py(obj);
4984 ASN1_OBJECT_free(obj);
4985 return result;
4986}
4987
Christian Heimes46bebee2013-06-09 19:03:31 +02004988#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004989
4990static PyObject*
4991certEncodingType(DWORD encodingType)
4992{
4993 static PyObject *x509_asn = NULL;
4994 static PyObject *pkcs_7_asn = NULL;
4995
4996 if (x509_asn == NULL) {
4997 x509_asn = PyUnicode_InternFromString("x509_asn");
4998 if (x509_asn == NULL)
4999 return NULL;
5000 }
5001 if (pkcs_7_asn == NULL) {
5002 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5003 if (pkcs_7_asn == NULL)
5004 return NULL;
5005 }
5006 switch(encodingType) {
5007 case X509_ASN_ENCODING:
5008 Py_INCREF(x509_asn);
5009 return x509_asn;
5010 case PKCS_7_ASN_ENCODING:
5011 Py_INCREF(pkcs_7_asn);
5012 return pkcs_7_asn;
5013 default:
5014 return PyLong_FromLong(encodingType);
5015 }
5016}
5017
5018static PyObject*
5019parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5020{
5021 CERT_ENHKEY_USAGE *usage;
5022 DWORD size, error, i;
5023 PyObject *retval;
5024
5025 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5026 error = GetLastError();
5027 if (error == CRYPT_E_NOT_FOUND) {
5028 Py_RETURN_TRUE;
5029 }
5030 return PyErr_SetFromWindowsErr(error);
5031 }
5032
5033 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5034 if (usage == NULL) {
5035 return PyErr_NoMemory();
5036 }
5037
5038 /* Now get the actual enhanced usage property */
5039 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5040 PyMem_Free(usage);
5041 error = GetLastError();
5042 if (error == CRYPT_E_NOT_FOUND) {
5043 Py_RETURN_TRUE;
5044 }
5045 return PyErr_SetFromWindowsErr(error);
5046 }
5047 retval = PySet_New(NULL);
5048 if (retval == NULL) {
5049 goto error;
5050 }
5051 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5052 if (usage->rgpszUsageIdentifier[i]) {
5053 PyObject *oid;
5054 int err;
5055 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5056 if (oid == NULL) {
5057 Py_CLEAR(retval);
5058 goto error;
5059 }
5060 err = PySet_Add(retval, oid);
5061 Py_DECREF(oid);
5062 if (err == -1) {
5063 Py_CLEAR(retval);
5064 goto error;
5065 }
5066 }
5067 }
5068 error:
5069 PyMem_Free(usage);
5070 return retval;
5071}
5072
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005073/*[clinic input]
5074_ssl.enum_certificates
5075 store_name: str
5076
5077Retrieve certificates from Windows' cert store.
5078
5079store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5080more cert storages, too. The function returns a list of (bytes,
5081encoding_type, trust) tuples. The encoding_type flag can be interpreted
5082with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5083a set of OIDs or the boolean True.
5084[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005085
Christian Heimes46bebee2013-06-09 19:03:31 +02005086static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005087_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5088/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005089{
Christian Heimes46bebee2013-06-09 19:03:31 +02005090 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005091 PCCERT_CONTEXT pCertCtx = NULL;
5092 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005093 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005094
Christian Heimes44109d72013-11-22 01:51:30 +01005095 result = PyList_New(0);
5096 if (result == NULL) {
5097 return NULL;
5098 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005099 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5100 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5101 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005102 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005103 Py_DECREF(result);
5104 return PyErr_SetFromWindowsErr(GetLastError());
5105 }
5106
Christian Heimes44109d72013-11-22 01:51:30 +01005107 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5108 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5109 pCertCtx->cbCertEncoded);
5110 if (!cert) {
5111 Py_CLEAR(result);
5112 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005113 }
Christian Heimes44109d72013-11-22 01:51:30 +01005114 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5115 Py_CLEAR(result);
5116 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005117 }
Christian Heimes44109d72013-11-22 01:51:30 +01005118 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5119 if (keyusage == Py_True) {
5120 Py_DECREF(keyusage);
5121 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005122 }
Christian Heimes44109d72013-11-22 01:51:30 +01005123 if (keyusage == NULL) {
5124 Py_CLEAR(result);
5125 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005126 }
Christian Heimes44109d72013-11-22 01:51:30 +01005127 if ((tup = PyTuple_New(3)) == NULL) {
5128 Py_CLEAR(result);
5129 break;
5130 }
5131 PyTuple_SET_ITEM(tup, 0, cert);
5132 cert = NULL;
5133 PyTuple_SET_ITEM(tup, 1, enc);
5134 enc = NULL;
5135 PyTuple_SET_ITEM(tup, 2, keyusage);
5136 keyusage = NULL;
5137 if (PyList_Append(result, tup) < 0) {
5138 Py_CLEAR(result);
5139 break;
5140 }
5141 Py_CLEAR(tup);
5142 }
5143 if (pCertCtx) {
5144 /* loop ended with an error, need to clean up context manually */
5145 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005146 }
5147
5148 /* In error cases cert, enc and tup may not be NULL */
5149 Py_XDECREF(cert);
5150 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005151 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005152 Py_XDECREF(tup);
5153
5154 if (!CertCloseStore(hStore, 0)) {
5155 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005156 Py_XDECREF(result);
5157 return PyErr_SetFromWindowsErr(GetLastError());
5158 }
5159 return result;
5160}
5161
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005162/*[clinic input]
5163_ssl.enum_crls
5164 store_name: str
5165
5166Retrieve CRLs from Windows' cert store.
5167
5168store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5169more cert storages, too. The function returns a list of (bytes,
5170encoding_type) tuples. The encoding_type flag can be interpreted with
5171X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5172[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005173
5174static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005175_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5176/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005177{
Christian Heimes44109d72013-11-22 01:51:30 +01005178 HCERTSTORE hStore = NULL;
5179 PCCRL_CONTEXT pCrlCtx = NULL;
5180 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5181 PyObject *result = NULL;
5182
Christian Heimes44109d72013-11-22 01:51:30 +01005183 result = PyList_New(0);
5184 if (result == NULL) {
5185 return NULL;
5186 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005187 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5188 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5189 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005190 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005191 Py_DECREF(result);
5192 return PyErr_SetFromWindowsErr(GetLastError());
5193 }
Christian Heimes44109d72013-11-22 01:51:30 +01005194
5195 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5196 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5197 pCrlCtx->cbCrlEncoded);
5198 if (!crl) {
5199 Py_CLEAR(result);
5200 break;
5201 }
5202 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5203 Py_CLEAR(result);
5204 break;
5205 }
5206 if ((tup = PyTuple_New(2)) == NULL) {
5207 Py_CLEAR(result);
5208 break;
5209 }
5210 PyTuple_SET_ITEM(tup, 0, crl);
5211 crl = NULL;
5212 PyTuple_SET_ITEM(tup, 1, enc);
5213 enc = NULL;
5214
5215 if (PyList_Append(result, tup) < 0) {
5216 Py_CLEAR(result);
5217 break;
5218 }
5219 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005220 }
Christian Heimes44109d72013-11-22 01:51:30 +01005221 if (pCrlCtx) {
5222 /* loop ended with an error, need to clean up context manually */
5223 CertFreeCRLContext(pCrlCtx);
5224 }
5225
5226 /* In error cases cert, enc and tup may not be NULL */
5227 Py_XDECREF(crl);
5228 Py_XDECREF(enc);
5229 Py_XDECREF(tup);
5230
5231 if (!CertCloseStore(hStore, 0)) {
5232 /* This error case might shadow another exception.*/
5233 Py_XDECREF(result);
5234 return PyErr_SetFromWindowsErr(GetLastError());
5235 }
5236 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005237}
Christian Heimes44109d72013-11-22 01:51:30 +01005238
5239#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005240
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005241/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005242static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005243 _SSL__TEST_DECODE_CERT_METHODDEF
5244 _SSL_RAND_ADD_METHODDEF
5245 _SSL_RAND_BYTES_METHODDEF
5246 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5247 _SSL_RAND_EGD_METHODDEF
5248 _SSL_RAND_STATUS_METHODDEF
5249 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5250 _SSL_ENUM_CERTIFICATES_METHODDEF
5251 _SSL_ENUM_CRLS_METHODDEF
5252 _SSL_TXT2OBJ_METHODDEF
5253 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005254 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005255};
5256
5257
Christian Heimes598894f2016-09-05 23:19:05 +02005258#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005259
5260/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005261 * of the Python C thread library
5262 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5263 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005264
5265static PyThread_type_lock *_ssl_locks = NULL;
5266
Christian Heimes4d98ca92013-08-19 17:36:29 +02005267#if OPENSSL_VERSION_NUMBER >= 0x10000000
5268/* use new CRYPTO_THREADID API. */
5269static void
5270_ssl_threadid_callback(CRYPTO_THREADID *id)
5271{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005272 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005273}
5274#else
5275/* deprecated CRYPTO_set_id_callback() API. */
5276static unsigned long
5277_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005278 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005279}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005280#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005281
Bill Janssen6e027db2007-11-15 22:23:56 +00005282static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005283 (int mode, int n, const char *file, int line) {
5284 /* this function is needed to perform locking on shared data
5285 structures. (Note that OpenSSL uses a number of global data
5286 structures that will be implicitly shared whenever multiple
5287 threads use OpenSSL.) Multi-threaded applications will
5288 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005290 locking_function() must be able to handle up to
5291 CRYPTO_num_locks() different mutex locks. It sets the n-th
5292 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005294 file and line are the file number of the function setting the
5295 lock. They can be useful for debugging.
5296 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005297
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005298 if ((_ssl_locks == NULL) ||
5299 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5300 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005301
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005302 if (mode & CRYPTO_LOCK) {
5303 PyThread_acquire_lock(_ssl_locks[n], 1);
5304 } else {
5305 PyThread_release_lock(_ssl_locks[n]);
5306 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005307}
5308
5309static int _setup_ssl_threads(void) {
5310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005311 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005312
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005313 if (_ssl_locks == NULL) {
5314 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005315 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5316 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005317 if (_ssl_locks == NULL) {
5318 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005319 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005320 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005321 for (i = 0; i < _ssl_locks_count; i++) {
5322 _ssl_locks[i] = PyThread_allocate_lock();
5323 if (_ssl_locks[i] == NULL) {
5324 unsigned int j;
5325 for (j = 0; j < i; j++) {
5326 PyThread_free_lock(_ssl_locks[j]);
5327 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005328 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005329 return 0;
5330 }
5331 }
5332 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005333#if OPENSSL_VERSION_NUMBER >= 0x10000000
5334 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5335#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005336 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005337#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005338 }
5339 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005340}
5341
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005342#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005343
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005344PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005345"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005346for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005347
Martin v. Löwis1a214512008-06-11 05:26:20 +00005348
5349static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005350 PyModuleDef_HEAD_INIT,
5351 "_ssl",
5352 module_doc,
5353 -1,
5354 PySSL_methods,
5355 NULL,
5356 NULL,
5357 NULL,
5358 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005359};
5360
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005361
5362static void
5363parse_openssl_version(unsigned long libver,
5364 unsigned int *major, unsigned int *minor,
5365 unsigned int *fix, unsigned int *patch,
5366 unsigned int *status)
5367{
5368 *status = libver & 0xF;
5369 libver >>= 4;
5370 *patch = libver & 0xFF;
5371 libver >>= 8;
5372 *fix = libver & 0xFF;
5373 libver >>= 8;
5374 *minor = libver & 0xFF;
5375 libver >>= 8;
5376 *major = libver & 0xFF;
5377}
5378
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005379PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005380PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005381{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005382 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005383 unsigned long libver;
5384 unsigned int major, minor, fix, patch, status;
5385 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005386 struct py_ssl_error_code *errcode;
5387 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005388
Antoine Pitrou152efa22010-05-16 18:19:27 +00005389 if (PyType_Ready(&PySSLContext_Type) < 0)
5390 return NULL;
5391 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005392 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005393 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5394 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005395 if (PyType_Ready(&PySSLSession_Type) < 0)
5396 return NULL;
5397
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005398
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005399 m = PyModule_Create(&_sslmodule);
5400 if (m == NULL)
5401 return NULL;
5402 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005403
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005404 /* Load _socket module and its C API */
5405 socket_api = PySocketModule_ImportModuleAndAPI();
5406 if (!socket_api)
5407 return NULL;
5408 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005409
Christian Heimesc941e622017-09-05 15:47:11 +02005410#ifndef OPENSSL_VERSION_1_1
5411 /* Load all algorithms and initialize cpuid */
5412 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005413 /* Init OpenSSL */
5414 SSL_load_error_strings();
5415 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005416#endif
5417
Christian Heimes598894f2016-09-05 23:19:05 +02005418#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005419 /* note that this will start threading if not already started */
5420 if (!_setup_ssl_threads()) {
5421 return NULL;
5422 }
Christian Heimes598894f2016-09-05 23:19:05 +02005423#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5424 /* OpenSSL 1.1.0 builtin thread support is enabled */
5425 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005426#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005428 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005429 sslerror_type_slots[0].pfunc = PyExc_OSError;
5430 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005431 if (PySSLErrorObject == NULL)
5432 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005433
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005434 /* ssl.CertificateError used to be a subclass of ValueError */
5435 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5436 if (bases == NULL)
5437 return NULL;
5438 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5439 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5440 bases, NULL);
5441 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005442 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5443 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5444 PySSLErrorObject, NULL);
5445 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5446 "ssl.SSLWantReadError", SSLWantReadError_doc,
5447 PySSLErrorObject, NULL);
5448 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5449 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5450 PySSLErrorObject, NULL);
5451 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5452 "ssl.SSLSyscallError", SSLSyscallError_doc,
5453 PySSLErrorObject, NULL);
5454 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5455 "ssl.SSLEOFError", SSLEOFError_doc,
5456 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005457 if (PySSLCertVerificationErrorObject == NULL
5458 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005459 || PySSLWantReadErrorObject == NULL
5460 || PySSLWantWriteErrorObject == NULL
5461 || PySSLSyscallErrorObject == NULL
5462 || PySSLEOFErrorObject == NULL)
5463 return NULL;
5464 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005465 || PyDict_SetItemString(d, "SSLCertVerificationError",
5466 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005467 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5468 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5469 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5470 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5471 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005472 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005473 if (PyDict_SetItemString(d, "_SSLContext",
5474 (PyObject *)&PySSLContext_Type) != 0)
5475 return NULL;
5476 if (PyDict_SetItemString(d, "_SSLSocket",
5477 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005478 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005479 if (PyDict_SetItemString(d, "MemoryBIO",
5480 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5481 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005482 if (PyDict_SetItemString(d, "SSLSession",
5483 (PyObject *)&PySSLSession_Type) != 0)
5484 return NULL;
5485
Christian Heimes892d66e2018-01-29 14:10:18 +01005486 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5487 PY_SSL_DEFAULT_CIPHER_STRING);
5488
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005489 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5490 PY_SSL_ERROR_ZERO_RETURN);
5491 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5492 PY_SSL_ERROR_WANT_READ);
5493 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5494 PY_SSL_ERROR_WANT_WRITE);
5495 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5496 PY_SSL_ERROR_WANT_X509_LOOKUP);
5497 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5498 PY_SSL_ERROR_SYSCALL);
5499 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5500 PY_SSL_ERROR_SSL);
5501 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5502 PY_SSL_ERROR_WANT_CONNECT);
5503 /* non ssl.h errorcodes */
5504 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5505 PY_SSL_ERROR_EOF);
5506 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5507 PY_SSL_ERROR_INVALID_ERROR_CODE);
5508 /* cert requirements */
5509 PyModule_AddIntConstant(m, "CERT_NONE",
5510 PY_SSL_CERT_NONE);
5511 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5512 PY_SSL_CERT_OPTIONAL);
5513 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5514 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005515 /* CRL verification for verification_flags */
5516 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5517 0);
5518 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5519 X509_V_FLAG_CRL_CHECK);
5520 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5521 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5522 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5523 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005524#ifdef X509_V_FLAG_TRUSTED_FIRST
5525 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5526 X509_V_FLAG_TRUSTED_FIRST);
5527#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005528
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005529 /* Alert Descriptions from ssl.h */
5530 /* note RESERVED constants no longer intended for use have been removed */
5531 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5532
5533#define ADD_AD_CONSTANT(s) \
5534 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5535 SSL_AD_##s)
5536
5537 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5538 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5539 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5540 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5541 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5542 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5543 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5544 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5545 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5546 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5547 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5548 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5549 ADD_AD_CONSTANT(UNKNOWN_CA);
5550 ADD_AD_CONSTANT(ACCESS_DENIED);
5551 ADD_AD_CONSTANT(DECODE_ERROR);
5552 ADD_AD_CONSTANT(DECRYPT_ERROR);
5553 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5554 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5555 ADD_AD_CONSTANT(INTERNAL_ERROR);
5556 ADD_AD_CONSTANT(USER_CANCELLED);
5557 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005558 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005559#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5560 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5561#endif
5562#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5563 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5564#endif
5565#ifdef SSL_AD_UNRECOGNIZED_NAME
5566 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5567#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005568#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5569 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5570#endif
5571#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5572 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5573#endif
5574#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5575 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5576#endif
5577
5578#undef ADD_AD_CONSTANT
5579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005580 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005581#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005582 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5583 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005584#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005585#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005586 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5587 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005588#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005589 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005590 PY_SSL_VERSION_TLS);
5591 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5592 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005593 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5594 PY_SSL_VERSION_TLS_CLIENT);
5595 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5596 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005597 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5598 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005599#if HAVE_TLSv1_2
5600 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5601 PY_SSL_VERSION_TLS1_1);
5602 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5603 PY_SSL_VERSION_TLS1_2);
5604#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005605
Antoine Pitroub5218772010-05-21 09:56:06 +00005606 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005607 PyModule_AddIntConstant(m, "OP_ALL",
5608 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005609 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5610 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5611 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005612#if HAVE_TLSv1_2
5613 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5614 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5615#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005616#ifdef SSL_OP_NO_TLSv1_3
5617 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5618#else
5619 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5620#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005621 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5622 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005623 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005624 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005625#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005626 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005627#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005628#ifdef SSL_OP_NO_COMPRESSION
5629 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5630 SSL_OP_NO_COMPRESSION);
5631#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005632
Christian Heimes61d478c2018-01-27 15:51:38 +01005633#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5634 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5635 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5636#endif
5637#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5638 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5639 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5640#endif
5641#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5642 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5643 X509_CHECK_FLAG_NO_WILDCARDS);
5644#endif
5645#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5646 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5647 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5648#endif
5649#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5650 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5651 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5652#endif
5653#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5654 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5655 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5656#endif
5657
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005658#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005659 r = Py_True;
5660#else
5661 r = Py_False;
5662#endif
5663 Py_INCREF(r);
5664 PyModule_AddObject(m, "HAS_SNI", r);
5665
Antoine Pitroud6494802011-07-21 01:11:30 +02005666 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005667 Py_INCREF(r);
5668 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5669
Antoine Pitrou501da612011-12-21 09:27:41 +01005670#ifdef OPENSSL_NO_ECDH
5671 r = Py_False;
5672#else
5673 r = Py_True;
5674#endif
5675 Py_INCREF(r);
5676 PyModule_AddObject(m, "HAS_ECDH", r);
5677
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005678#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005679 r = Py_True;
5680#else
5681 r = Py_False;
5682#endif
5683 Py_INCREF(r);
5684 PyModule_AddObject(m, "HAS_NPN", r);
5685
Benjamin Petersoncca27322015-01-23 16:35:37 -05005686#ifdef HAVE_ALPN
5687 r = Py_True;
5688#else
5689 r = Py_False;
5690#endif
5691 Py_INCREF(r);
5692 PyModule_AddObject(m, "HAS_ALPN", r);
5693
Christian Heimescb5b68a2017-09-07 18:07:00 -07005694#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5695 r = Py_True;
5696#else
5697 r = Py_False;
5698#endif
5699 Py_INCREF(r);
5700 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5701
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005702 /* Mappings for error codes */
5703 err_codes_to_names = PyDict_New();
5704 err_names_to_codes = PyDict_New();
5705 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5706 return NULL;
5707 errcode = error_codes;
5708 while (errcode->mnemonic != NULL) {
5709 PyObject *mnemo, *key;
5710 mnemo = PyUnicode_FromString(errcode->mnemonic);
5711 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5712 if (mnemo == NULL || key == NULL)
5713 return NULL;
5714 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5715 return NULL;
5716 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5717 return NULL;
5718 Py_DECREF(key);
5719 Py_DECREF(mnemo);
5720 errcode++;
5721 }
5722 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5723 return NULL;
5724 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5725 return NULL;
5726
5727 lib_codes_to_names = PyDict_New();
5728 if (lib_codes_to_names == NULL)
5729 return NULL;
5730 libcode = library_codes;
5731 while (libcode->library != NULL) {
5732 PyObject *mnemo, *key;
5733 key = PyLong_FromLong(libcode->code);
5734 mnemo = PyUnicode_FromString(libcode->library);
5735 if (key == NULL || mnemo == NULL)
5736 return NULL;
5737 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5738 return NULL;
5739 Py_DECREF(key);
5740 Py_DECREF(mnemo);
5741 libcode++;
5742 }
5743 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5744 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005745
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005746 /* OpenSSL version */
5747 /* SSLeay() gives us the version of the library linked against,
5748 which could be different from the headers version.
5749 */
5750 libver = SSLeay();
5751 r = PyLong_FromUnsignedLong(libver);
5752 if (r == NULL)
5753 return NULL;
5754 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5755 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005756 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005757 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5758 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5759 return NULL;
5760 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5761 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5762 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005763
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005764 libver = OPENSSL_VERSION_NUMBER;
5765 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5766 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5767 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5768 return NULL;
5769
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005770 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005771}