blob: 2136cbdeae47e7b9c0ebae2dbe33129b34885f28 [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
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800411static int PySSL_set_owner(PySSLSocket *, PyObject *, void *);
412static int PySSL_set_session(PySSLSocket *, PyObject *, void *);
Antoine Pitrou152efa22010-05-16 18:19:27 +0000413#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200414#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200415#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000416
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000417typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000418 SOCKET_IS_NONBLOCKING,
419 SOCKET_IS_BLOCKING,
420 SOCKET_HAS_TIMED_OUT,
421 SOCKET_HAS_BEEN_CLOSED,
422 SOCKET_TOO_LARGE_FOR_SELECT,
423 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000424} timeout_state;
425
Thomas Woutersed03b412007-08-28 21:37:11 +0000426/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000427#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200428#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000429
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200430/* Get the socket from a PySSLSocket, if it has one */
431#define GET_SOCKET(obj) ((obj)->Socket ? \
432 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200433
Victor Stinner14690702015-04-06 22:46:13 +0200434/* If sock is NULL, use a timeout of 0 second */
435#define GET_SOCKET_TIMEOUT(sock) \
436 ((sock != NULL) ? (sock)->sock_timeout : 0)
437
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200438/*
439 * SSL errors.
440 */
441
442PyDoc_STRVAR(SSLError_doc,
443"An error occurred in the SSL implementation.");
444
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700445PyDoc_STRVAR(SSLCertVerificationError_doc,
446"A certificate could not be verified.");
447
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200448PyDoc_STRVAR(SSLZeroReturnError_doc,
449"SSL/TLS session closed cleanly.");
450
451PyDoc_STRVAR(SSLWantReadError_doc,
452"Non-blocking SSL socket needs to read more data\n"
453"before the requested operation can be completed.");
454
455PyDoc_STRVAR(SSLWantWriteError_doc,
456"Non-blocking SSL socket needs to write more data\n"
457"before the requested operation can be completed.");
458
459PyDoc_STRVAR(SSLSyscallError_doc,
460"System error when attempting SSL operation.");
461
462PyDoc_STRVAR(SSLEOFError_doc,
463"SSL/TLS connection terminated abruptly.");
464
465static PyObject *
466SSLError_str(PyOSErrorObject *self)
467{
468 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
469 Py_INCREF(self->strerror);
470 return self->strerror;
471 }
472 else
473 return PyObject_Str(self->args);
474}
475
476static PyType_Slot sslerror_type_slots[] = {
477 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
478 {Py_tp_doc, SSLError_doc},
479 {Py_tp_str, SSLError_str},
480 {0, 0},
481};
482
483static PyType_Spec sslerror_type_spec = {
484 "ssl.SSLError",
485 sizeof(PyOSErrorObject),
486 0,
487 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
488 sslerror_type_slots
489};
490
491static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700492fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
493 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200494{
495 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700496 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200497 PyObject *init_value, *msg, *key;
498 _Py_IDENTIFIER(reason);
499 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700500 _Py_IDENTIFIER(verify_message);
501 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200502
503 if (errcode != 0) {
504 int lib, reason;
505
506 lib = ERR_GET_LIB(errcode);
507 reason = ERR_GET_REASON(errcode);
508 key = Py_BuildValue("ii", lib, reason);
509 if (key == NULL)
510 goto fail;
511 reason_obj = PyDict_GetItem(err_codes_to_names, key);
512 Py_DECREF(key);
513 if (reason_obj == NULL) {
514 /* XXX if reason < 100, it might reflect a library number (!!) */
515 PyErr_Clear();
516 }
517 key = PyLong_FromLong(lib);
518 if (key == NULL)
519 goto fail;
520 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
521 Py_DECREF(key);
522 if (lib_obj == NULL) {
523 PyErr_Clear();
524 }
525 if (errstr == NULL)
526 errstr = ERR_reason_error_string(errcode);
527 }
528 if (errstr == NULL)
529 errstr = "unknown error";
530
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700531 /* verify code for cert validation error */
532 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
533 const char *verify_str = NULL;
534 long verify_code;
535
536 verify_code = SSL_get_verify_result(sslsock->ssl);
537 verify_code_obj = PyLong_FromLong(verify_code);
538 if (verify_code_obj == NULL) {
539 goto fail;
540 }
541
542 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700543#ifdef X509_V_ERR_HOSTNAME_MISMATCH
544 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700545 case X509_V_ERR_HOSTNAME_MISMATCH:
546 verify_obj = PyUnicode_FromFormat(
547 "Hostname mismatch, certificate is not valid for '%S'.",
548 sslsock->server_hostname
549 );
550 break;
Christian Heimes09153602017-09-08 14:47:58 -0700551#endif
552#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700553 case X509_V_ERR_IP_ADDRESS_MISMATCH:
554 verify_obj = PyUnicode_FromFormat(
555 "IP address mismatch, certificate is not valid for '%S'.",
556 sslsock->server_hostname
557 );
558 break;
Christian Heimes09153602017-09-08 14:47:58 -0700559#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700560 default:
561 verify_str = X509_verify_cert_error_string(verify_code);
562 if (verify_str != NULL) {
563 verify_obj = PyUnicode_FromString(verify_str);
564 } else {
565 verify_obj = Py_None;
566 Py_INCREF(verify_obj);
567 }
568 break;
569 }
570 if (verify_obj == NULL) {
571 goto fail;
572 }
573 }
574
575 if (verify_obj && reason_obj && lib_obj)
576 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
577 lib_obj, reason_obj, errstr, verify_obj,
578 lineno);
579 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200580 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
581 lib_obj, reason_obj, errstr, lineno);
582 else if (lib_obj)
583 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
584 lib_obj, errstr, lineno);
585 else
586 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200587 if (msg == NULL)
588 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100589
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200590 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100591 if (init_value == NULL)
592 goto fail;
593
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594 err_value = PyObject_CallObject(type, init_value);
595 Py_DECREF(init_value);
596 if (err_value == NULL)
597 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100598
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200599 if (reason_obj == NULL)
600 reason_obj = Py_None;
601 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
602 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700603
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200604 if (lib_obj == NULL)
605 lib_obj = Py_None;
606 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
607 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700608
609 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
610 /* Only set verify code / message for SSLCertVerificationError */
611 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
612 verify_code_obj))
613 goto fail;
614 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
615 goto fail;
616 }
617
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200618 PyErr_SetObject(type, err_value);
619fail:
620 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700621 Py_XDECREF(verify_code_obj);
622 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200623}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000624
625static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700626PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000627{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200628 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200629 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000630 int err;
631 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200632 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000633
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000634 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200635 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000636
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700637 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700638 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000639
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 switch (err) {
641 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200642 errstr = "TLS/SSL connection has been closed (EOF)";
643 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000644 p = PY_SSL_ERROR_ZERO_RETURN;
645 break;
646 case SSL_ERROR_WANT_READ:
647 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200648 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 p = PY_SSL_ERROR_WANT_READ;
650 break;
651 case SSL_ERROR_WANT_WRITE:
652 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200653 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 errstr = "The operation did not complete (write)";
655 break;
656 case SSL_ERROR_WANT_X509_LOOKUP:
657 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000658 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 break;
660 case SSL_ERROR_WANT_CONNECT:
661 p = PY_SSL_ERROR_WANT_CONNECT;
662 errstr = "The operation did not complete (connect)";
663 break;
664 case SSL_ERROR_SYSCALL:
665 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700667 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000669 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200670 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000671 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200672 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000673 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000674 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700675#ifdef MS_WINDOWS
676 if (sslsock->ws_errno)
677 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
678#endif
679 if (sslsock->c_errno) {
680 errno = sslsock->c_errno;
681 return PyErr_SetFromErrno(PyExc_OSError);
682 }
683 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200684 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000685 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200686 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000687 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000688 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200689 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000690 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000691 }
692 } else {
693 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 }
695 break;
696 }
697 case SSL_ERROR_SSL:
698 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700700 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200701 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000702 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700703 }
704 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
705 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
706 type = PySSLCertVerificationErrorObject;
707 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000708 break;
709 }
710 default:
711 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
712 errstr = "Invalid error code";
713 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700715 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000716 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000717 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000718}
719
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000720static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200721_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000722
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200723 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200725 else
726 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700727 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000728 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000729 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000730}
731
Christian Heimes61d478c2018-01-27 15:51:38 +0100732/*
733 * SSL objects
734 */
735
736static int
737_ssl_configure_hostname(PySSLSocket *self, const char* server_hostname)
738{
739 int retval = -1;
740 ASN1_OCTET_STRING *ip;
741 PyObject *hostname;
742 size_t len;
743
744 assert(server_hostname);
745
746 /* Disable OpenSSL's special mode with leading dot in hostname:
747 * When name starts with a dot (e.g ".example.com"), it will be
748 * matched by a certificate valid for any sub-domain of name.
749 */
750 len = strlen(server_hostname);
751 if (len == 0 || *server_hostname == '.') {
752 PyErr_SetString(
753 PyExc_ValueError,
754 "server_hostname cannot be an empty string or start with a "
755 "leading dot.");
756 return retval;
757 }
758
759 /* inet_pton is not available on all platforms. */
760 ip = a2i_IPADDRESS(server_hostname);
761 if (ip == NULL) {
762 ERR_clear_error();
763 }
764
Miss Islington (bot)1c37e272018-02-23 19:18:28 -0800765 hostname = PyUnicode_Decode(server_hostname, len, "ascii", "strict");
Christian Heimes61d478c2018-01-27 15:51:38 +0100766 if (hostname == NULL) {
767 goto error;
768 }
769 self->server_hostname = hostname;
770
771 /* Only send SNI extension for non-IP hostnames */
772 if (ip == NULL) {
773 if (!SSL_set_tlsext_host_name(self->ssl, server_hostname)) {
774 _setSSLError(NULL, 0, __FILE__, __LINE__);
775 }
776 }
777 if (self->ctx->check_hostname) {
778 X509_VERIFY_PARAM *param = SSL_get0_param(self->ssl);
779 if (ip == NULL) {
780 if (!X509_VERIFY_PARAM_set1_host(param, server_hostname, 0)) {
781 _setSSLError(NULL, 0, __FILE__, __LINE__);
782 goto error;
783 }
784 } else {
785 if (!X509_VERIFY_PARAM_set1_ip(param, ASN1_STRING_data(ip),
786 ASN1_STRING_length(ip))) {
787 _setSSLError(NULL, 0, __FILE__, __LINE__);
788 goto error;
789 }
790 }
791 }
792 retval = 0;
793 error:
794 if (ip != NULL) {
795 ASN1_OCTET_STRING_free(ip);
796 }
797 return retval;
798}
799
Antoine Pitrou152efa22010-05-16 18:19:27 +0000800static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100801newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000802 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200803 char *server_hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800804 PyObject *owner, PyObject *session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200805 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000806{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000807 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100808 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200809 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000810
Antoine Pitrou152efa22010-05-16 18:19:27 +0000811 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 if (self == NULL)
813 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000814
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100817 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700818 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200819 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200820 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700821 self->server_hostname = NULL;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700822 self->ssl_errno = 0;
823 self->c_errno = 0;
824#ifdef MS_WINDOWS
825 self->ws_errno = 0;
826#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200827
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 /* Make sure the SSL error state is initialized */
829 (void) ERR_get_state();
830 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000833 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200835 SSL_set_app_data(self->ssl, self);
836 if (sock) {
837 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
838 } else {
839 /* BIOs are reference counted and SSL_set_bio borrows our reference.
840 * To prevent a double free in memory_bio_dealloc() we need to take an
841 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200842 BIO_up_ref(inbio->bio);
843 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200844 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
845 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200846 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000847#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200848 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000849#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200850 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000851
Christian Heimes61d478c2018-01-27 15:51:38 +0100852 if (server_hostname != NULL) {
853 if (_ssl_configure_hostname(self, server_hostname) < 0) {
854 Py_DECREF(self);
855 return NULL;
856 }
857 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 /* If the socket is in non-blocking mode or timeout mode, set the BIO
859 * to non-blocking mode (blocking is the default)
860 */
Victor Stinnere2452312015-03-28 03:00:46 +0100861 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000862 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
863 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
864 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000865
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000866 PySSL_BEGIN_ALLOW_THREADS
867 if (socket_type == PY_SSL_CLIENT)
868 SSL_set_connect_state(self->ssl);
869 else
870 SSL_set_accept_state(self->ssl);
871 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000872
Antoine Pitroud6494802011-07-21 01:11:30 +0200873 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200874 if (sock != NULL) {
875 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
876 if (self->Socket == NULL) {
877 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200878 return NULL;
879 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100880 }
Miss Islington (bot)8fa84782018-02-24 12:51:56 -0800881 if (owner && owner != Py_None) {
882 if (PySSL_set_owner(self, owner, NULL) == -1) {
883 Py_DECREF(self);
884 return NULL;
885 }
886 }
887 if (session && session != Py_None) {
888 if (PySSL_set_session(self, session, NULL) == -1) {
889 Py_DECREF(self);
890 return NULL;
891 }
892 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000893 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000894}
895
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000896/* SSL object methods */
897
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300898/*[clinic input]
899_ssl._SSLSocket.do_handshake
900[clinic start generated code]*/
901
902static PyObject *
903_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
904/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000905{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000906 int ret;
907 int err;
908 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200909 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200910 _PyTime_t timeout, deadline = 0;
911 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000912
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200913 if (sock) {
914 if (((PyObject*)sock) == Py_None) {
915 _setSSLError("Underlying socket connection gone",
916 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
917 return NULL;
918 }
919 Py_INCREF(sock);
920
921 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100922 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200923 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
924 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000925 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000926
Victor Stinner14690702015-04-06 22:46:13 +0200927 timeout = GET_SOCKET_TIMEOUT(sock);
928 has_timeout = (timeout > 0);
929 if (has_timeout)
930 deadline = _PyTime_GetMonotonicClock() + timeout;
931
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 /* Actually negotiate SSL connection */
933 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000935 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000936 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700937 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700939 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200940
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000941 if (PyErr_CheckSignals())
942 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200943
Victor Stinner14690702015-04-06 22:46:13 +0200944 if (has_timeout)
945 timeout = deadline - _PyTime_GetMonotonicClock();
946
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000947 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200948 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200950 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000951 } else {
952 sockstate = SOCKET_OPERATION_OK;
953 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200954
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000955 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000956 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000957 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000958 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
960 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000961 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000962 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
964 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000965 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000966 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000967 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
968 break;
969 }
970 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200971 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000972 if (ret < 1)
973 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000974
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200975 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000976
977error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200978 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000979 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000980}
981
Thomas Woutersed03b412007-08-28 21:37:11 +0000982static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300983_asn1obj2py(const ASN1_OBJECT *name, int no_name)
984{
985 char buf[X509_NAME_MAXLEN];
986 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300988 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000989
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300990 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 if (buflen < 0) {
992 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300993 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000994 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300995 /* initial buffer is too small for oid + terminating null byte */
996 if (buflen > X509_NAME_MAXLEN - 1) {
997 /* make OBJ_obj2txt() calculate the required buflen */
998 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
999 /* allocate len + 1 for terminating NULL byte */
1000 namebuf = PyMem_Malloc(buflen + 1);
1001 if (namebuf == NULL) {
1002 PyErr_NoMemory();
1003 return NULL;
1004 }
1005 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
1006 if (buflen < 0) {
1007 _setSSLError(NULL, 0, __FILE__, __LINE__);
1008 goto done;
1009 }
1010 }
1011 if (!buflen && no_name) {
1012 Py_INCREF(Py_None);
1013 name_obj = Py_None;
1014 }
1015 else {
1016 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
1017 }
1018
1019 done:
1020 if (buf != namebuf) {
1021 PyMem_Free(namebuf);
1022 }
1023 return name_obj;
1024}
1025
1026static PyObject *
1027_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
1028{
1029 Py_ssize_t buflen;
1030 unsigned char *valuebuf = NULL;
1031 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
1034 if (buflen < 0) {
1035 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001036 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +03001038 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001039 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +00001041}
1042
1043static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +00001045{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001046 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
1047 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
1048 PyObject *rdnt;
1049 PyObject *attr = NULL; /* tuple to hold an attribute */
1050 int entry_count = X509_NAME_entry_count(xname);
1051 X509_NAME_ENTRY *entry;
1052 ASN1_OBJECT *name;
1053 ASN1_STRING *value;
1054 int index_counter;
1055 int rdn_level = -1;
1056 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001058 dn = PyList_New(0);
1059 if (dn == NULL)
1060 return NULL;
1061 /* now create another tuple to hold the top-level RDN */
1062 rdn = PyList_New(0);
1063 if (rdn == NULL)
1064 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 for (index_counter = 0;
1067 index_counter < entry_count;
1068 index_counter++)
1069 {
1070 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001071
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 /* check to see if we've gotten to a new RDN */
1073 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +02001074 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 /* yes, new RDN */
1076 /* add old RDN to DN */
1077 rdnt = PyList_AsTuple(rdn);
1078 Py_DECREF(rdn);
1079 if (rdnt == NULL)
1080 goto fail0;
1081 retcode = PyList_Append(dn, rdnt);
1082 Py_DECREF(rdnt);
1083 if (retcode < 0)
1084 goto fail0;
1085 /* create new RDN */
1086 rdn = PyList_New(0);
1087 if (rdn == NULL)
1088 goto fail0;
1089 }
1090 }
Christian Heimes598894f2016-09-05 23:19:05 +02001091 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001092
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001093 /* now add this attribute to the current RDN */
1094 name = X509_NAME_ENTRY_get_object(entry);
1095 value = X509_NAME_ENTRY_get_data(entry);
1096 attr = _create_tuple_for_attribute(name, value);
1097 /*
1098 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
1099 entry->set,
1100 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
1101 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1102 */
1103 if (attr == NULL)
1104 goto fail1;
1105 retcode = PyList_Append(rdn, attr);
1106 Py_DECREF(attr);
1107 if (retcode < 0)
1108 goto fail1;
1109 }
1110 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001111 if (rdn != NULL) {
1112 if (PyList_GET_SIZE(rdn) > 0) {
1113 rdnt = PyList_AsTuple(rdn);
1114 Py_DECREF(rdn);
1115 if (rdnt == NULL)
1116 goto fail0;
1117 retcode = PyList_Append(dn, rdnt);
1118 Py_DECREF(rdnt);
1119 if (retcode < 0)
1120 goto fail0;
1121 }
1122 else {
1123 Py_DECREF(rdn);
1124 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001127 /* convert list to tuple */
1128 rdnt = PyList_AsTuple(dn);
1129 Py_DECREF(dn);
1130 if (rdnt == NULL)
1131 return NULL;
1132 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001133
1134 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001135 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
1137 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001138 Py_XDECREF(dn);
1139 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140}
1141
1142static PyObject *
1143_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001145 /* this code follows the procedure outlined in
1146 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1147 function to extract the STACK_OF(GENERAL_NAME),
1148 then iterates through the stack to add the
1149 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001151 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001153 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001154 GENERAL_NAMES *names = NULL;
1155 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001156 BIO *biobuf = NULL;
1157 char buf[2048];
1158 char *vptr;
1159 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001161 if (certificate == NULL)
1162 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001164 /* get a memory buffer */
1165 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001166
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001167 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1168 certificate, NID_subject_alt_name, NULL, NULL);
1169 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001170 if (peer_alt_names == Py_None) {
1171 peer_alt_names = PyList_New(0);
1172 if (peer_alt_names == NULL)
1173 goto fail;
1174 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001177 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001178 int gntype;
1179 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001182 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001183 switch (gntype) {
1184 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 /* we special-case DirName as a tuple of
1186 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001187
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001188 t = PyTuple_New(2);
1189 if (t == NULL) {
1190 goto fail;
1191 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001192
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001193 v = PyUnicode_FromString("DirName");
1194 if (v == NULL) {
1195 Py_DECREF(t);
1196 goto fail;
1197 }
1198 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 v = _create_tuple_for_X509_NAME (name->d.dirn);
1201 if (v == NULL) {
1202 Py_DECREF(t);
1203 goto fail;
1204 }
1205 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001206 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001207
Christian Heimes824f7f32013-08-17 00:54:47 +02001208 case GEN_EMAIL:
1209 case GEN_DNS:
1210 case GEN_URI:
1211 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1212 correctly, CVE-2013-4238 */
1213 t = PyTuple_New(2);
1214 if (t == NULL)
1215 goto fail;
1216 switch (gntype) {
1217 case GEN_EMAIL:
1218 v = PyUnicode_FromString("email");
1219 as = name->d.rfc822Name;
1220 break;
1221 case GEN_DNS:
1222 v = PyUnicode_FromString("DNS");
1223 as = name->d.dNSName;
1224 break;
1225 case GEN_URI:
1226 v = PyUnicode_FromString("URI");
1227 as = name->d.uniformResourceIdentifier;
1228 break;
1229 }
1230 if (v == NULL) {
1231 Py_DECREF(t);
1232 goto fail;
1233 }
1234 PyTuple_SET_ITEM(t, 0, v);
1235 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1236 ASN1_STRING_length(as));
1237 if (v == NULL) {
1238 Py_DECREF(t);
1239 goto fail;
1240 }
1241 PyTuple_SET_ITEM(t, 1, v);
1242 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001243
Christian Heimes1c03abd2016-09-06 23:25:35 +02001244 case GEN_RID:
1245 t = PyTuple_New(2);
1246 if (t == NULL)
1247 goto fail;
1248
1249 v = PyUnicode_FromString("Registered ID");
1250 if (v == NULL) {
1251 Py_DECREF(t);
1252 goto fail;
1253 }
1254 PyTuple_SET_ITEM(t, 0, v);
1255
1256 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1257 if (len < 0) {
1258 Py_DECREF(t);
1259 _setSSLError(NULL, 0, __FILE__, __LINE__);
1260 goto fail;
1261 } else if (len >= (int)sizeof(buf)) {
1262 v = PyUnicode_FromString("<INVALID>");
1263 } else {
1264 v = PyUnicode_FromStringAndSize(buf, len);
1265 }
1266 if (v == NULL) {
1267 Py_DECREF(t);
1268 goto fail;
1269 }
1270 PyTuple_SET_ITEM(t, 1, v);
1271 break;
1272
Christian Heimes824f7f32013-08-17 00:54:47 +02001273 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001274 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001275 switch (gntype) {
1276 /* check for new general name type */
1277 case GEN_OTHERNAME:
1278 case GEN_X400:
1279 case GEN_EDIPARTY:
1280 case GEN_IPADD:
1281 case GEN_RID:
1282 break;
1283 default:
1284 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1285 "Unknown general name type %d",
1286 gntype) == -1) {
1287 goto fail;
1288 }
1289 break;
1290 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 (void) BIO_reset(biobuf);
1292 GENERAL_NAME_print(biobuf, name);
1293 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1294 if (len < 0) {
1295 _setSSLError(NULL, 0, __FILE__, __LINE__);
1296 goto fail;
1297 }
1298 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001299 if (vptr == NULL) {
1300 PyErr_Format(PyExc_ValueError,
1301 "Invalid value %.200s",
1302 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001303 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001304 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 t = PyTuple_New(2);
1306 if (t == NULL)
1307 goto fail;
1308 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1309 if (v == NULL) {
1310 Py_DECREF(t);
1311 goto fail;
1312 }
1313 PyTuple_SET_ITEM(t, 0, v);
1314 v = PyUnicode_FromStringAndSize((vptr + 1),
1315 (len - (vptr - buf + 1)));
1316 if (v == NULL) {
1317 Py_DECREF(t);
1318 goto fail;
1319 }
1320 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001321 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001322 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001324 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 if (PyList_Append(peer_alt_names, t) < 0) {
1327 Py_DECREF(t);
1328 goto fail;
1329 }
1330 Py_DECREF(t);
1331 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001332 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001333 }
1334 BIO_free(biobuf);
1335 if (peer_alt_names != Py_None) {
1336 v = PyList_AsTuple(peer_alt_names);
1337 Py_DECREF(peer_alt_names);
1338 return v;
1339 } else {
1340 return peer_alt_names;
1341 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001342
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001343
1344 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001345 if (biobuf != NULL)
1346 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001347
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001348 if (peer_alt_names != Py_None) {
1349 Py_XDECREF(peer_alt_names);
1350 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001352 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001353}
1354
1355static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001356_get_aia_uri(X509 *certificate, int nid) {
1357 PyObject *lst = NULL, *ostr = NULL;
1358 int i, result;
1359 AUTHORITY_INFO_ACCESS *info;
1360
1361 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001362 if (info == NULL)
1363 return Py_None;
1364 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1365 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001366 return Py_None;
1367 }
1368
1369 if ((lst = PyList_New(0)) == NULL) {
1370 goto fail;
1371 }
1372
1373 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1374 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1375 ASN1_IA5STRING *uri;
1376
1377 if ((OBJ_obj2nid(ad->method) != nid) ||
1378 (ad->location->type != GEN_URI)) {
1379 continue;
1380 }
1381 uri = ad->location->d.uniformResourceIdentifier;
1382 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1383 uri->length);
1384 if (ostr == NULL) {
1385 goto fail;
1386 }
1387 result = PyList_Append(lst, ostr);
1388 Py_DECREF(ostr);
1389 if (result < 0) {
1390 goto fail;
1391 }
1392 }
1393 AUTHORITY_INFO_ACCESS_free(info);
1394
1395 /* convert to tuple or None */
1396 if (PyList_Size(lst) == 0) {
1397 Py_DECREF(lst);
1398 return Py_None;
1399 } else {
1400 PyObject *tup;
1401 tup = PyList_AsTuple(lst);
1402 Py_DECREF(lst);
1403 return tup;
1404 }
1405
1406 fail:
1407 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001408 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001409 return NULL;
1410}
1411
1412static PyObject *
1413_get_crl_dp(X509 *certificate) {
1414 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001415 int i, j;
1416 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001417
Christian Heimes598894f2016-09-05 23:19:05 +02001418 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001419
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001420 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001421 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001422
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001423 lst = PyList_New(0);
1424 if (lst == NULL)
1425 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001426
1427 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1428 DIST_POINT *dp;
1429 STACK_OF(GENERAL_NAME) *gns;
1430
1431 dp = sk_DIST_POINT_value(dps, i);
1432 gns = dp->distpoint->name.fullname;
1433
1434 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1435 GENERAL_NAME *gn;
1436 ASN1_IA5STRING *uri;
1437 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001438 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001439
1440 gn = sk_GENERAL_NAME_value(gns, j);
1441 if (gn->type != GEN_URI) {
1442 continue;
1443 }
1444 uri = gn->d.uniformResourceIdentifier;
1445 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1446 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001447 if (ouri == NULL)
1448 goto done;
1449
1450 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001451 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001452 if (err < 0)
1453 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001454 }
1455 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001456
1457 /* Convert to tuple. */
1458 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1459
1460 done:
1461 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001462 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001463 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001464}
1465
1466static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001467_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 PyObject *retval = NULL;
1470 BIO *biobuf = NULL;
1471 PyObject *peer;
1472 PyObject *peer_alt_names = NULL;
1473 PyObject *issuer;
1474 PyObject *version;
1475 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001476 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 ASN1_INTEGER *serialNumber;
1478 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001479 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001480 ASN1_TIME *notBefore, *notAfter;
1481 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001482
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001483 retval = PyDict_New();
1484 if (retval == NULL)
1485 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001487 peer = _create_tuple_for_X509_NAME(
1488 X509_get_subject_name(certificate));
1489 if (peer == NULL)
1490 goto fail0;
1491 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1492 Py_DECREF(peer);
1493 goto fail0;
1494 }
1495 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001496
Antoine Pitroufb046912010-11-09 20:21:19 +00001497 issuer = _create_tuple_for_X509_NAME(
1498 X509_get_issuer_name(certificate));
1499 if (issuer == NULL)
1500 goto fail0;
1501 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001502 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001503 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001504 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001505 Py_DECREF(issuer);
1506
1507 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001508 if (version == NULL)
1509 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001510 if (PyDict_SetItemString(retval, "version", version) < 0) {
1511 Py_DECREF(version);
1512 goto fail0;
1513 }
1514 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001515
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001516 /* get a memory buffer */
1517 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001518
Antoine Pitroufb046912010-11-09 20:21:19 +00001519 (void) BIO_reset(biobuf);
1520 serialNumber = X509_get_serialNumber(certificate);
1521 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1522 i2a_ASN1_INTEGER(biobuf, serialNumber);
1523 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1524 if (len < 0) {
1525 _setSSLError(NULL, 0, __FILE__, __LINE__);
1526 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001527 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001528 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1529 if (sn_obj == NULL)
1530 goto fail1;
1531 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1532 Py_DECREF(sn_obj);
1533 goto fail1;
1534 }
1535 Py_DECREF(sn_obj);
1536
1537 (void) BIO_reset(biobuf);
1538 notBefore = X509_get_notBefore(certificate);
1539 ASN1_TIME_print(biobuf, notBefore);
1540 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1541 if (len < 0) {
1542 _setSSLError(NULL, 0, __FILE__, __LINE__);
1543 goto fail1;
1544 }
1545 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1546 if (pnotBefore == NULL)
1547 goto fail1;
1548 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1549 Py_DECREF(pnotBefore);
1550 goto fail1;
1551 }
1552 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001553
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001554 (void) BIO_reset(biobuf);
1555 notAfter = X509_get_notAfter(certificate);
1556 ASN1_TIME_print(biobuf, notAfter);
1557 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1558 if (len < 0) {
1559 _setSSLError(NULL, 0, __FILE__, __LINE__);
1560 goto fail1;
1561 }
1562 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1563 if (pnotAfter == NULL)
1564 goto fail1;
1565 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1566 Py_DECREF(pnotAfter);
1567 goto fail1;
1568 }
1569 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001572
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001573 peer_alt_names = _get_peer_alt_names(certificate);
1574 if (peer_alt_names == NULL)
1575 goto fail1;
1576 else if (peer_alt_names != Py_None) {
1577 if (PyDict_SetItemString(retval, "subjectAltName",
1578 peer_alt_names) < 0) {
1579 Py_DECREF(peer_alt_names);
1580 goto fail1;
1581 }
1582 Py_DECREF(peer_alt_names);
1583 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001584
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001585 /* Authority Information Access: OCSP URIs */
1586 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1587 if (obj == NULL) {
1588 goto fail1;
1589 } else if (obj != Py_None) {
1590 result = PyDict_SetItemString(retval, "OCSP", obj);
1591 Py_DECREF(obj);
1592 if (result < 0) {
1593 goto fail1;
1594 }
1595 }
1596
1597 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1598 if (obj == NULL) {
1599 goto fail1;
1600 } else if (obj != Py_None) {
1601 result = PyDict_SetItemString(retval, "caIssuers", obj);
1602 Py_DECREF(obj);
1603 if (result < 0) {
1604 goto fail1;
1605 }
1606 }
1607
1608 /* CDP (CRL distribution points) */
1609 obj = _get_crl_dp(certificate);
1610 if (obj == NULL) {
1611 goto fail1;
1612 } else if (obj != Py_None) {
1613 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1614 Py_DECREF(obj);
1615 if (result < 0) {
1616 goto fail1;
1617 }
1618 }
1619
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 BIO_free(biobuf);
1621 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001622
1623 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 if (biobuf != NULL)
1625 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001626 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 Py_XDECREF(retval);
1628 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001629}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001630
Christian Heimes9a5395a2013-06-17 15:44:12 +02001631static PyObject *
1632_certificate_to_der(X509 *certificate)
1633{
1634 unsigned char *bytes_buf = NULL;
1635 int len;
1636 PyObject *retval;
1637
1638 bytes_buf = NULL;
1639 len = i2d_X509(certificate, &bytes_buf);
1640 if (len < 0) {
1641 _setSSLError(NULL, 0, __FILE__, __LINE__);
1642 return NULL;
1643 }
1644 /* this is actually an immutable bytes sequence */
1645 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1646 OPENSSL_free(bytes_buf);
1647 return retval;
1648}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001649
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001650/*[clinic input]
1651_ssl._test_decode_cert
1652 path: object(converter="PyUnicode_FSConverter")
1653 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001654
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001655[clinic start generated code]*/
1656
1657static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001658_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1659/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001660{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001661 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001662 X509 *x=NULL;
1663 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001664
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001665 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1666 PyErr_SetString(PySSLErrorObject,
1667 "Can't malloc memory to read file");
1668 goto fail0;
1669 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001670
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001671 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 PyErr_SetString(PySSLErrorObject,
1673 "Can't open file");
1674 goto fail0;
1675 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001676
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1678 if (x == NULL) {
1679 PyErr_SetString(PySSLErrorObject,
1680 "Error decoding PEM-encoded file");
1681 goto fail0;
1682 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001683
Antoine Pitroufb046912010-11-09 20:21:19 +00001684 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001685 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001686
1687 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001688 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001689 if (cert != NULL) BIO_free(cert);
1690 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001691}
1692
1693
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001694/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001695_ssl._SSLSocket.getpeercert
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001696 der as binary_mode: bool = False
1697 /
1698
1699Returns the certificate for the peer.
1700
1701If no certificate was provided, returns None. If a certificate was
1702provided, but not validated, returns an empty dictionary. Otherwise
1703returns a dict containing information about the peer certificate.
1704
1705If the optional argument is True, returns a DER-encoded copy of the
1706peer certificate, or None if no certificate was provided. This will
1707return the certificate even if it wasn't validated.
1708[clinic start generated code]*/
1709
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001710static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08001711_ssl__SSLSocket_getpeercert_impl(PySSLSocket *self, int binary_mode)
1712/*[clinic end generated code: output=1f0ab66dfb693c88 input=c0fbe802e57629b7]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001713{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001714 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001715 X509 *peer_cert;
1716 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001717
Christian Heimes66dc33b2017-05-23 16:02:02 -07001718 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001719 PyErr_SetString(PyExc_ValueError,
1720 "handshake not done yet");
1721 return NULL;
1722 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001723 peer_cert = SSL_get_peer_certificate(self->ssl);
1724 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001725 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001726
Antoine Pitrou721738f2012-08-15 23:20:39 +02001727 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001728 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001729 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001730 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001731 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001732 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001733 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001734 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001735 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001736 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001737 X509_free(peer_cert);
1738 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001739}
1740
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001741static PyObject *
1742cipher_to_tuple(const SSL_CIPHER *cipher)
1743{
1744 const char *cipher_name, *cipher_protocol;
1745 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001746 if (retval == NULL)
1747 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001748
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001749 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001750 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001751 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001752 PyTuple_SET_ITEM(retval, 0, Py_None);
1753 } else {
1754 v = PyUnicode_FromString(cipher_name);
1755 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001756 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001757 PyTuple_SET_ITEM(retval, 0, v);
1758 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001759
1760 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001761 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001762 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001763 PyTuple_SET_ITEM(retval, 1, Py_None);
1764 } else {
1765 v = PyUnicode_FromString(cipher_protocol);
1766 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001767 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001768 PyTuple_SET_ITEM(retval, 1, v);
1769 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001770
1771 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001772 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001773 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001774 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001776 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001777
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001778 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001779 Py_DECREF(retval);
1780 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001781}
1782
Christian Heimes25bfcd52016-09-06 00:04:45 +02001783#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1784static PyObject *
1785cipher_to_dict(const SSL_CIPHER *cipher)
1786{
1787 const char *cipher_name, *cipher_protocol;
1788
1789 unsigned long cipher_id;
1790 int alg_bits, strength_bits, len;
1791 char buf[512] = {0};
1792#if OPENSSL_VERSION_1_1
1793 int aead, nid;
1794 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1795#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001796
1797 /* can be NULL */
1798 cipher_name = SSL_CIPHER_get_name(cipher);
1799 cipher_protocol = SSL_CIPHER_get_version(cipher);
1800 cipher_id = SSL_CIPHER_get_id(cipher);
1801 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001802 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1803 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001804 if (len > 1 && buf[len-1] == '\n')
1805 buf[len-1] = '\0';
1806 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1807
1808#if OPENSSL_VERSION_1_1
1809 aead = SSL_CIPHER_is_aead(cipher);
1810 nid = SSL_CIPHER_get_cipher_nid(cipher);
1811 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1812 nid = SSL_CIPHER_get_digest_nid(cipher);
1813 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1814 nid = SSL_CIPHER_get_kx_nid(cipher);
1815 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1816 nid = SSL_CIPHER_get_auth_nid(cipher);
1817 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1818#endif
1819
Victor Stinner410b9882016-09-12 12:00:23 +02001820 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001821 "{sksssssssisi"
1822#if OPENSSL_VERSION_1_1
1823 "sOssssssss"
1824#endif
1825 "}",
1826 "id", cipher_id,
1827 "name", cipher_name,
1828 "protocol", cipher_protocol,
1829 "description", buf,
1830 "strength_bits", strength_bits,
1831 "alg_bits", alg_bits
1832#if OPENSSL_VERSION_1_1
1833 ,"aead", aead ? Py_True : Py_False,
1834 "symmetric", skcipher,
1835 "digest", digest,
1836 "kea", kx,
1837 "auth", auth
1838#endif
1839 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001840}
1841#endif
1842
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001843/*[clinic input]
1844_ssl._SSLSocket.shared_ciphers
1845[clinic start generated code]*/
1846
1847static PyObject *
1848_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1849/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001850{
1851 STACK_OF(SSL_CIPHER) *ciphers;
1852 int i;
1853 PyObject *res;
1854
Christian Heimes598894f2016-09-05 23:19:05 +02001855 ciphers = SSL_get_ciphers(self->ssl);
1856 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001857 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001858 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1859 if (!res)
1860 return NULL;
1861 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1862 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1863 if (!tup) {
1864 Py_DECREF(res);
1865 return NULL;
1866 }
1867 PyList_SET_ITEM(res, i, tup);
1868 }
1869 return res;
1870}
1871
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001872/*[clinic input]
1873_ssl._SSLSocket.cipher
1874[clinic start generated code]*/
1875
1876static PyObject *
1877_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1878/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001879{
1880 const SSL_CIPHER *current;
1881
1882 if (self->ssl == NULL)
1883 Py_RETURN_NONE;
1884 current = SSL_get_current_cipher(self->ssl);
1885 if (current == NULL)
1886 Py_RETURN_NONE;
1887 return cipher_to_tuple(current);
1888}
1889
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001890/*[clinic input]
1891_ssl._SSLSocket.version
1892[clinic start generated code]*/
1893
1894static PyObject *
1895_ssl__SSLSocket_version_impl(PySSLSocket *self)
1896/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001897{
1898 const char *version;
1899
1900 if (self->ssl == NULL)
1901 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001902 if (!SSL_is_init_finished(self->ssl)) {
1903 /* handshake not finished */
1904 Py_RETURN_NONE;
1905 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001906 version = SSL_get_version(self->ssl);
1907 if (!strcmp(version, "unknown"))
1908 Py_RETURN_NONE;
1909 return PyUnicode_FromString(version);
1910}
1911
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001912#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001913/*[clinic input]
1914_ssl._SSLSocket.selected_npn_protocol
1915[clinic start generated code]*/
1916
1917static PyObject *
1918_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1919/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1920{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001921 const unsigned char *out;
1922 unsigned int outlen;
1923
Victor Stinner4569cd52013-06-23 14:58:43 +02001924 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001925 &out, &outlen);
1926
1927 if (out == NULL)
1928 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001929 return PyUnicode_FromStringAndSize((char *)out, outlen);
1930}
1931#endif
1932
1933#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001934/*[clinic input]
1935_ssl._SSLSocket.selected_alpn_protocol
1936[clinic start generated code]*/
1937
1938static PyObject *
1939_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1940/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1941{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001942 const unsigned char *out;
1943 unsigned int outlen;
1944
1945 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1946
1947 if (out == NULL)
1948 Py_RETURN_NONE;
1949 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001950}
1951#endif
1952
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001953/*[clinic input]
1954_ssl._SSLSocket.compression
1955[clinic start generated code]*/
1956
1957static PyObject *
1958_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1959/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1960{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001961#ifdef OPENSSL_NO_COMP
1962 Py_RETURN_NONE;
1963#else
1964 const COMP_METHOD *comp_method;
1965 const char *short_name;
1966
1967 if (self->ssl == NULL)
1968 Py_RETURN_NONE;
1969 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001970 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001971 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001972 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001973 if (short_name == NULL)
1974 Py_RETURN_NONE;
1975 return PyUnicode_DecodeFSDefault(short_name);
1976#endif
1977}
1978
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001979static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1980 Py_INCREF(self->ctx);
1981 return self->ctx;
1982}
1983
1984static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1985 void *closure) {
1986
1987 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001988#if !HAVE_SNI
1989 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1990 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001991 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001992#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001993 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001994 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001995 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001996#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001997 } else {
1998 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1999 return -1;
2000 }
2001
2002 return 0;
2003}
2004
2005PyDoc_STRVAR(PySSL_set_context_doc,
2006"_setter_context(ctx)\n\
2007\
2008This changes the context associated with the SSLSocket. This is typically\n\
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002009used from within a callback function set by the sni_callback\n\
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002010on the SSLContext to change the certificate information associated with the\n\
2011SSLSocket before the cryptographic exchange handshake messages\n");
2012
2013
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002014static PyObject *
2015PySSL_get_server_side(PySSLSocket *self, void *c)
2016{
2017 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
2018}
2019
2020PyDoc_STRVAR(PySSL_get_server_side_doc,
2021"Whether this is a server-side socket.");
2022
2023static PyObject *
2024PySSL_get_server_hostname(PySSLSocket *self, void *c)
2025{
2026 if (self->server_hostname == NULL)
2027 Py_RETURN_NONE;
2028 Py_INCREF(self->server_hostname);
2029 return self->server_hostname;
2030}
2031
2032PyDoc_STRVAR(PySSL_get_server_hostname_doc,
2033"The currently set server hostname (for SNI).");
2034
2035static PyObject *
2036PySSL_get_owner(PySSLSocket *self, void *c)
2037{
2038 PyObject *owner;
2039
2040 if (self->owner == NULL)
2041 Py_RETURN_NONE;
2042
2043 owner = PyWeakref_GetObject(self->owner);
2044 Py_INCREF(owner);
2045 return owner;
2046}
2047
2048static int
2049PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
2050{
Serhiy Storchaka48842712016-04-06 09:45:48 +03002051 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002052 if (self->owner == NULL)
2053 return -1;
2054 return 0;
2055}
2056
2057PyDoc_STRVAR(PySSL_get_owner_doc,
2058"The Python-level owner of this object.\
2059Passed as \"self\" in servername callback.");
2060
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002061
Antoine Pitrou152efa22010-05-16 18:19:27 +00002062static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002063{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 if (self->ssl)
2065 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002067 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002068 Py_XDECREF(self->server_hostname);
2069 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002070 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002071}
2072
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002073/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002074 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002075 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002076 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00002077
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002078static int
Victor Stinner14690702015-04-06 22:46:13 +02002079PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002080{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002081 int rc;
2082#ifdef HAVE_POLL
2083 struct pollfd pollfd;
2084 _PyTime_t ms;
2085#else
2086 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002087 fd_set fds;
2088 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002089#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002090
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02002092 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02002094 else if (timeout < 0) {
2095 if (s->sock_timeout > 0)
2096 return SOCKET_HAS_TIMED_OUT;
2097 else
2098 return SOCKET_IS_BLOCKING;
2099 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002100
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002101 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002102 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002103 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002104
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002105 /* Prefer poll, if available, since you can poll() any fd
2106 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002107#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002108 pollfd.fd = s->sock_fd;
2109 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002110
Victor Stinner14690702015-04-06 22:46:13 +02002111 /* timeout is in seconds, poll() uses milliseconds */
2112 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002113 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002114
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002115 PySSL_BEGIN_ALLOW_THREADS
2116 rc = poll(&pollfd, 1, (int)ms);
2117 PySSL_END_ALLOW_THREADS
2118#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002120 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002121 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002122
Victor Stinner14690702015-04-06 22:46:13 +02002123 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002125 FD_ZERO(&fds);
2126 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002127
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002128 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002129 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002130 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002131 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002132 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002134 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002135 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002136#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2139 (when we are able to write or when there's something to read) */
2140 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002141}
2142
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002143/*[clinic input]
2144_ssl._SSLSocket.write
2145 b: Py_buffer
2146 /
2147
2148Writes the bytes-like object b into the SSL object.
2149
2150Returns the number of bytes written.
2151[clinic start generated code]*/
2152
2153static PyObject *
2154_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2155/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002156{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 int len;
2158 int sockstate;
2159 int err;
2160 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002161 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002162 _PyTime_t timeout, deadline = 0;
2163 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002164
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002165 if (sock != NULL) {
2166 if (((PyObject*)sock) == Py_None) {
2167 _setSSLError("Underlying socket connection gone",
2168 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2169 return NULL;
2170 }
2171 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172 }
2173
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002174 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002175 PyErr_Format(PyExc_OverflowError,
2176 "string longer than %d bytes", INT_MAX);
2177 goto error;
2178 }
2179
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002180 if (sock != NULL) {
2181 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002182 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002183 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2184 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2185 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002186
Victor Stinner14690702015-04-06 22:46:13 +02002187 timeout = GET_SOCKET_TIMEOUT(sock);
2188 has_timeout = (timeout > 0);
2189 if (has_timeout)
2190 deadline = _PyTime_GetMonotonicClock() + timeout;
2191
2192 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002194 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002195 "The write operation timed out");
2196 goto error;
2197 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2198 PyErr_SetString(PySSLErrorObject,
2199 "Underlying socket has been closed.");
2200 goto error;
2201 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2202 PyErr_SetString(PySSLErrorObject,
2203 "Underlying socket too large for select().");
2204 goto error;
2205 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002209 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002210 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002211 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002212 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002213
2214 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002215 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002216
Victor Stinner14690702015-04-06 22:46:13 +02002217 if (has_timeout)
2218 timeout = deadline - _PyTime_GetMonotonicClock();
2219
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002221 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002222 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002223 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002224 } else {
2225 sockstate = SOCKET_OPERATION_OK;
2226 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002227
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002229 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002230 "The write operation timed out");
2231 goto error;
2232 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2233 PyErr_SetString(PySSLErrorObject,
2234 "Underlying socket has been closed.");
2235 goto error;
2236 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2237 break;
2238 }
2239 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002240
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002241 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002242 if (len > 0)
2243 return PyLong_FromLong(len);
2244 else
2245 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002246
2247error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002248 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002250}
2251
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002252/*[clinic input]
2253_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002254
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002255Returns the number of already decrypted bytes available for read, pending on the connection.
2256[clinic start generated code]*/
2257
2258static PyObject *
2259_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2260/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002261{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002264 PySSL_BEGIN_ALLOW_THREADS
2265 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002266 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002267 PySSL_END_ALLOW_THREADS
2268 if (count < 0)
2269 return PySSL_SetError(self, count, __FILE__, __LINE__);
2270 else
2271 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002272}
2273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002274/*[clinic input]
2275_ssl._SSLSocket.read
2276 size as len: int
2277 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002278 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002279 ]
2280 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002282Read up to size bytes from the SSL socket.
2283[clinic start generated code]*/
2284
2285static PyObject *
2286_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2287 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002288/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002289{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002292 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002293 int sockstate;
2294 int err;
2295 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002296 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002297 _PyTime_t timeout, deadline = 0;
2298 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002299
Martin Panter5503d472016-03-27 05:35:19 +00002300 if (!group_right_1 && len < 0) {
2301 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2302 return NULL;
2303 }
2304
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002305 if (sock != NULL) {
2306 if (((PyObject*)sock) == Py_None) {
2307 _setSSLError("Underlying socket connection gone",
2308 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2309 return NULL;
2310 }
2311 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002312 }
2313
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002314 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002315 dest = PyBytes_FromStringAndSize(NULL, len);
2316 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002317 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002318 if (len == 0) {
2319 Py_XDECREF(sock);
2320 return dest;
2321 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002322 mem = PyBytes_AS_STRING(dest);
2323 }
2324 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002325 mem = buffer->buf;
2326 if (len <= 0 || len > buffer->len) {
2327 len = (int) buffer->len;
2328 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002329 PyErr_SetString(PyExc_OverflowError,
2330 "maximum length can't fit in a C 'int'");
2331 goto error;
2332 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002333 if (len == 0) {
2334 count = 0;
2335 goto done;
2336 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002337 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 }
2339
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002340 if (sock != NULL) {
2341 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002342 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002343 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2344 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2345 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002346
Victor Stinner14690702015-04-06 22:46:13 +02002347 timeout = GET_SOCKET_TIMEOUT(sock);
2348 has_timeout = (timeout > 0);
2349 if (has_timeout)
2350 deadline = _PyTime_GetMonotonicClock() + timeout;
2351
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002353 PySSL_BEGIN_ALLOW_THREADS
2354 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002355 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002356 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002357
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 if (PyErr_CheckSignals())
2359 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002360
Victor Stinner14690702015-04-06 22:46:13 +02002361 if (has_timeout)
2362 timeout = deadline - _PyTime_GetMonotonicClock();
2363
Steve Dowere6eb48c2017-09-08 15:16:15 -07002364 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002365 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002366 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002367 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002368 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002369 } else if (err == SSL_ERROR_ZERO_RETURN &&
2370 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 {
2372 count = 0;
2373 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002374 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002375 else
2376 sockstate = SOCKET_OPERATION_OK;
2377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002379 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002380 "The read operation timed out");
2381 goto error;
2382 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2383 break;
2384 }
2385 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 if (count <= 0) {
2388 PySSL_SetError(self, count, __FILE__, __LINE__);
2389 goto error;
2390 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002391
2392done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002393 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002394 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002395 _PyBytes_Resize(&dest, count);
2396 return dest;
2397 }
2398 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002399 return PyLong_FromLong(count);
2400 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002401
2402error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002403 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002404 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002405 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002406 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002407}
2408
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002409/*[clinic input]
2410_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002411
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002412Does the SSL shutdown handshake with the remote end.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002413[clinic start generated code]*/
2414
2415static PyObject *
2416_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002417/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=11d39e69b0a2bf4a]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002418{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002419 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002420 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002421 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002422 _PyTime_t timeout, deadline = 0;
2423 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002424
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002425 if (sock != NULL) {
2426 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002427 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002428 _setSSLError("Underlying socket connection gone",
2429 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2430 return NULL;
2431 }
2432 Py_INCREF(sock);
2433
2434 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002435 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002436 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2437 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002438 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002439
Victor Stinner14690702015-04-06 22:46:13 +02002440 timeout = GET_SOCKET_TIMEOUT(sock);
2441 has_timeout = (timeout > 0);
2442 if (has_timeout)
2443 deadline = _PyTime_GetMonotonicClock() + timeout;
2444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002445 while (1) {
2446 PySSL_BEGIN_ALLOW_THREADS
2447 /* Disable read-ahead so that unwrap can work correctly.
2448 * Otherwise OpenSSL might read in too much data,
2449 * eating clear text data that happens to be
2450 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002451 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002452 * function is used and the shutdown_seen_zero != 0
2453 * condition is met.
2454 */
2455 if (self->shutdown_seen_zero)
2456 SSL_set_read_ahead(self->ssl, 0);
2457 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002458 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002459 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002460
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002461 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2462 if (err > 0)
2463 break;
2464 if (err == 0) {
2465 /* Don't loop endlessly; instead preserve legacy
2466 behaviour of trying SSL_shutdown() only twice.
2467 This looks necessary for OpenSSL < 0.9.8m */
2468 if (++zeros > 1)
2469 break;
2470 /* Shutdown was sent, now try receiving */
2471 self->shutdown_seen_zero = 1;
2472 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002473 }
2474
Victor Stinner14690702015-04-06 22:46:13 +02002475 if (has_timeout)
2476 timeout = deadline - _PyTime_GetMonotonicClock();
2477
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002478 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002479 _PySSL_UPDATE_ERRNO(self, err);
2480 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002481 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002482 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002483 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002484 else
2485 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002486
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002487 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002488 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002489 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002490 "The read operation timed out");
2491 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002492 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002493 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002494 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002495 }
2496 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2497 PyErr_SetString(PySSLErrorObject,
2498 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002499 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002500 }
2501 else if (sockstate != SOCKET_OPERATION_OK)
2502 /* Retain the SSL error code */
2503 break;
2504 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002505
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002506 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002507 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002508 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002509 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002510 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002511 /* It's already INCREF'ed */
2512 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002513 else
2514 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002515
2516error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002517 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002518 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002519}
2520
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002521/*[clinic input]
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002522_ssl._SSLSocket.get_channel_binding
2523 cb_type: str = "tls-unique"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002524
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002525Get channel binding data for current connection.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002526
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002527Raise ValueError if the requested `cb_type` is not supported. Return bytes
2528of the data or None if the data is not available (e.g. before the handshake).
2529Only 'tls-unique' channel binding data from RFC 5929 is supported.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002530[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002531
Antoine Pitroud6494802011-07-21 01:11:30 +02002532static PyObject *
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002533_ssl__SSLSocket_get_channel_binding_impl(PySSLSocket *self,
2534 const char *cb_type)
2535/*[clinic end generated code: output=34bac9acb6a61d31 input=08b7e43b99c17d41]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002536{
Antoine Pitroud6494802011-07-21 01:11:30 +02002537 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002538 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002539
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002540 if (strcmp(cb_type, "tls-unique") == 0) {
2541 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2542 /* if session is resumed XOR we are the client */
2543 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2544 }
2545 else {
2546 /* if a new session XOR we are the server */
2547 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2548 }
Antoine Pitroud6494802011-07-21 01:11:30 +02002549 }
2550 else {
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002551 PyErr_Format(
2552 PyExc_ValueError,
2553 "'%s' channel binding type not implemented",
2554 cb_type
2555 );
2556 return NULL;
Antoine Pitroud6494802011-07-21 01:11:30 +02002557 }
2558
2559 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002560 if (len == 0)
2561 Py_RETURN_NONE;
2562
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002563 return PyBytes_FromStringAndSize(buf, len);
Antoine Pitroud6494802011-07-21 01:11:30 +02002564}
2565
Christian Heimes99a65702016-09-10 23:44:53 +02002566#ifdef OPENSSL_VERSION_1_1
2567
2568static SSL_SESSION*
2569_ssl_session_dup(SSL_SESSION *session) {
2570 SSL_SESSION *newsession = NULL;
2571 int slen;
2572 unsigned char *senc = NULL, *p;
2573 const unsigned char *const_p;
2574
2575 if (session == NULL) {
2576 PyErr_SetString(PyExc_ValueError, "Invalid session");
2577 goto error;
2578 }
2579
2580 /* get length */
2581 slen = i2d_SSL_SESSION(session, NULL);
2582 if (slen == 0 || slen > 0xFF00) {
2583 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2584 goto error;
2585 }
2586 if ((senc = PyMem_Malloc(slen)) == NULL) {
2587 PyErr_NoMemory();
2588 goto error;
2589 }
2590 p = senc;
2591 if (!i2d_SSL_SESSION(session, &p)) {
2592 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2593 goto error;
2594 }
2595 const_p = senc;
2596 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2597 if (session == NULL) {
2598 goto error;
2599 }
2600 PyMem_Free(senc);
2601 return newsession;
2602 error:
2603 if (senc != NULL) {
2604 PyMem_Free(senc);
2605 }
2606 return NULL;
2607}
2608#endif
2609
2610static PyObject *
2611PySSL_get_session(PySSLSocket *self, void *closure) {
2612 /* get_session can return sessions from a server-side connection,
2613 * it does not check for handshake done or client socket. */
2614 PySSLSession *pysess;
2615 SSL_SESSION *session;
2616
2617#ifdef OPENSSL_VERSION_1_1
2618 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2619 * https://github.com/openssl/openssl/issues/1550 */
2620 session = SSL_get0_session(self->ssl); /* borrowed reference */
2621 if (session == NULL) {
2622 Py_RETURN_NONE;
2623 }
2624 if ((session = _ssl_session_dup(session)) == NULL) {
2625 return NULL;
2626 }
2627#else
2628 session = SSL_get1_session(self->ssl);
2629 if (session == NULL) {
2630 Py_RETURN_NONE;
2631 }
2632#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002633 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002634 if (pysess == NULL) {
2635 SSL_SESSION_free(session);
2636 return NULL;
2637 }
2638
2639 assert(self->ctx);
2640 pysess->ctx = self->ctx;
2641 Py_INCREF(pysess->ctx);
2642 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002643 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002644 return (PyObject *)pysess;
2645}
2646
2647static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2648 void *closure)
2649 {
2650 PySSLSession *pysess;
2651#ifdef OPENSSL_VERSION_1_1
2652 SSL_SESSION *session;
2653#endif
2654 int result;
2655
2656 if (!PySSLSession_Check(value)) {
2657 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2658 return -1;
2659 }
2660 pysess = (PySSLSession *)value;
2661
2662 if (self->ctx->ctx != pysess->ctx->ctx) {
2663 PyErr_SetString(PyExc_ValueError,
2664 "Session refers to a different SSLContext.");
2665 return -1;
2666 }
2667 if (self->socket_type != PY_SSL_CLIENT) {
2668 PyErr_SetString(PyExc_ValueError,
2669 "Cannot set session for server-side SSLSocket.");
2670 return -1;
2671 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002672 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002673 PyErr_SetString(PyExc_ValueError,
2674 "Cannot set session after handshake.");
2675 return -1;
2676 }
2677#ifdef OPENSSL_VERSION_1_1
2678 /* duplicate session */
2679 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2680 return -1;
2681 }
2682 result = SSL_set_session(self->ssl, session);
2683 /* free duplicate, SSL_set_session() bumps ref count */
2684 SSL_SESSION_free(session);
2685#else
2686 result = SSL_set_session(self->ssl, pysess->session);
2687#endif
2688 if (result == 0) {
2689 _setSSLError(NULL, 0, __FILE__, __LINE__);
2690 return -1;
2691 }
2692 return 0;
2693}
2694
2695PyDoc_STRVAR(PySSL_set_session_doc,
2696"_setter_session(session)\n\
2697\
2698Get / set SSLSession.");
2699
2700static PyObject *
2701PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2702 if (SSL_session_reused(self->ssl)) {
2703 Py_RETURN_TRUE;
2704 } else {
2705 Py_RETURN_FALSE;
2706 }
2707}
2708
2709PyDoc_STRVAR(PySSL_get_session_reused_doc,
2710"Was the client session reused during handshake?");
2711
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002712static PyGetSetDef ssl_getsetlist[] = {
2713 {"context", (getter) PySSL_get_context,
2714 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002715 {"server_side", (getter) PySSL_get_server_side, NULL,
2716 PySSL_get_server_side_doc},
2717 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2718 PySSL_get_server_hostname_doc},
2719 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2720 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002721 {"session", (getter) PySSL_get_session,
2722 (setter) PySSL_set_session, PySSL_set_session_doc},
2723 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2724 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002725 {NULL}, /* sentinel */
2726};
2727
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002728static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002729 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2730 _SSL__SSLSOCKET_WRITE_METHODDEF
2731 _SSL__SSLSOCKET_READ_METHODDEF
2732 _SSL__SSLSOCKET_PENDING_METHODDEF
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08002733 _SSL__SSLSOCKET_GETPEERCERT_METHODDEF
2734 _SSL__SSLSOCKET_GET_CHANNEL_BINDING_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002735 _SSL__SSLSOCKET_CIPHER_METHODDEF
2736 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2737 _SSL__SSLSOCKET_VERSION_METHODDEF
2738 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2739 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2740 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2741 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002742 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002743};
2744
Antoine Pitrou152efa22010-05-16 18:19:27 +00002745static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002746 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002747 "_ssl._SSLSocket", /*tp_name*/
2748 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002749 0, /*tp_itemsize*/
2750 /* methods */
2751 (destructor)PySSL_dealloc, /*tp_dealloc*/
2752 0, /*tp_print*/
2753 0, /*tp_getattr*/
2754 0, /*tp_setattr*/
2755 0, /*tp_reserved*/
2756 0, /*tp_repr*/
2757 0, /*tp_as_number*/
2758 0, /*tp_as_sequence*/
2759 0, /*tp_as_mapping*/
2760 0, /*tp_hash*/
2761 0, /*tp_call*/
2762 0, /*tp_str*/
2763 0, /*tp_getattro*/
2764 0, /*tp_setattro*/
2765 0, /*tp_as_buffer*/
2766 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2767 0, /*tp_doc*/
2768 0, /*tp_traverse*/
2769 0, /*tp_clear*/
2770 0, /*tp_richcompare*/
2771 0, /*tp_weaklistoffset*/
2772 0, /*tp_iter*/
2773 0, /*tp_iternext*/
2774 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002775 0, /*tp_members*/
2776 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002777};
2778
Antoine Pitrou152efa22010-05-16 18:19:27 +00002779
2780/*
2781 * _SSLContext objects
2782 */
2783
Christian Heimes5fe668c2016-09-12 00:01:11 +02002784static int
2785_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2786{
2787 int mode;
2788 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2789
2790 switch(n) {
2791 case PY_SSL_CERT_NONE:
2792 mode = SSL_VERIFY_NONE;
2793 break;
2794 case PY_SSL_CERT_OPTIONAL:
2795 mode = SSL_VERIFY_PEER;
2796 break;
2797 case PY_SSL_CERT_REQUIRED:
2798 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2799 break;
2800 default:
2801 PyErr_SetString(PyExc_ValueError,
2802 "invalid value for verify_mode");
2803 return -1;
2804 }
2805 /* keep current verify cb */
2806 verify_cb = SSL_CTX_get_verify_callback(ctx);
2807 SSL_CTX_set_verify(ctx, mode, verify_cb);
2808 return 0;
2809}
2810
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002811/*[clinic input]
2812@classmethod
2813_ssl._SSLContext.__new__
2814 protocol as proto_version: int
2815 /
2816[clinic start generated code]*/
2817
Antoine Pitrou152efa22010-05-16 18:19:27 +00002818static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002819_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2820/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002821{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002822 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002823 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002824 SSL_CTX *ctx = NULL;
Christian Heimes61d478c2018-01-27 15:51:38 +01002825 X509_VERIFY_PARAM *params;
Christian Heimes358cfd42016-09-10 22:43:48 +02002826 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002827#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002828 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002829#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002830
Antoine Pitrou152efa22010-05-16 18:19:27 +00002831 PySSL_BEGIN_ALLOW_THREADS
2832 if (proto_version == PY_SSL_VERSION_TLS1)
2833 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002834#if HAVE_TLSv1_2
2835 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2836 ctx = SSL_CTX_new(TLSv1_1_method());
2837 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2838 ctx = SSL_CTX_new(TLSv1_2_method());
2839#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002840#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002841 else if (proto_version == PY_SSL_VERSION_SSL3)
2842 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002843#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002844#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002845 else if (proto_version == PY_SSL_VERSION_SSL2)
2846 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002847#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002848 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002849 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002850 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2851 ctx = SSL_CTX_new(TLS_client_method());
2852 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2853 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002854 else
2855 proto_version = -1;
2856 PySSL_END_ALLOW_THREADS
2857
2858 if (proto_version == -1) {
2859 PyErr_SetString(PyExc_ValueError,
2860 "invalid protocol version");
2861 return NULL;
2862 }
2863 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002864 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002865 return NULL;
2866 }
2867
2868 assert(type != NULL && type->tp_alloc != NULL);
2869 self = (PySSLContext *) type->tp_alloc(type, 0);
2870 if (self == NULL) {
2871 SSL_CTX_free(ctx);
2872 return NULL;
2873 }
2874 self->ctx = ctx;
Christian Heimes61d478c2018-01-27 15:51:38 +01002875 self->hostflags = X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS;
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002876 self->protocol = proto_version;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002877#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002878 self->npn_protocols = NULL;
2879#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002880#ifdef HAVE_ALPN
2881 self->alpn_protocols = NULL;
2882#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002883#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002884 self->set_sni_cb = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002885#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002886 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002887 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2888 self->check_hostname = 1;
2889 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2890 Py_DECREF(self);
2891 return NULL;
2892 }
2893 } else {
2894 self->check_hostname = 0;
2895 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2896 Py_DECREF(self);
2897 return NULL;
2898 }
2899 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002900 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002901 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2902 if (proto_version != PY_SSL_VERSION_SSL2)
2903 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002904 if (proto_version != PY_SSL_VERSION_SSL3)
2905 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002906 /* Minimal security flags for server and client side context.
2907 * Client sockets ignore server-side parameters. */
2908#ifdef SSL_OP_NO_COMPRESSION
2909 options |= SSL_OP_NO_COMPRESSION;
2910#endif
2911#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2912 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2913#endif
2914#ifdef SSL_OP_SINGLE_DH_USE
2915 options |= SSL_OP_SINGLE_DH_USE;
2916#endif
2917#ifdef SSL_OP_SINGLE_ECDH_USE
2918 options |= SSL_OP_SINGLE_ECDH_USE;
2919#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002920 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002921
Semen Zhydenko1295e112017-10-15 21:28:31 +02002922 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002923 * It's far from perfect but gives users a better head start. */
2924 if (proto_version != PY_SSL_VERSION_SSL2) {
Christian Heimes892d66e2018-01-29 14:10:18 +01002925#if PY_SSL_DEFAULT_CIPHERS == 2
2926 /* stick to OpenSSL's default settings */
2927 result = 1;
2928#else
2929 result = SSL_CTX_set_cipher_list(ctx, PY_SSL_DEFAULT_CIPHER_STRING);
2930#endif
Christian Heimes358cfd42016-09-10 22:43:48 +02002931 } else {
2932 /* SSLv2 needs MD5 */
2933 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2934 }
2935 if (result == 0) {
2936 Py_DECREF(self);
2937 ERR_clear_error();
2938 PyErr_SetString(PySSLErrorObject,
2939 "No cipher can be selected.");
2940 return NULL;
2941 }
2942
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002943#if defined(SSL_MODE_RELEASE_BUFFERS)
2944 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2945 usage for no cost at all. However, don't do this for OpenSSL versions
2946 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2947 2014-0198. I can't find exactly which beta fixed this CVE, so be
2948 conservative and assume it wasn't fixed until release. We do this check
2949 at runtime to avoid problems from the dynamic linker.
2950 See #25672 for more on this. */
2951 libver = SSLeay();
2952 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2953 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2954 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2955 }
2956#endif
2957
2958
Donald Stufft8ae264c2017-03-02 11:45:29 -05002959#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002960 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2961 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002962 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2963 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002964#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002965 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2966#else
2967 {
2968 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2969 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2970 EC_KEY_free(key);
2971 }
2972#endif
2973#endif
2974
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002975#define SID_CTX "Python"
2976 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2977 sizeof(SID_CTX));
2978#undef SID_CTX
2979
Christian Heimes61d478c2018-01-27 15:51:38 +01002980 params = SSL_CTX_get0_param(self->ctx);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002981#ifdef X509_V_FLAG_TRUSTED_FIRST
Christian Heimes61d478c2018-01-27 15:51:38 +01002982 /* Improve trust chain building when cross-signed intermediate
2983 certificates are present. See https://bugs.python.org/issue23476. */
2984 X509_VERIFY_PARAM_set_flags(params, X509_V_FLAG_TRUSTED_FIRST);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002985#endif
Christian Heimes61d478c2018-01-27 15:51:38 +01002986 X509_VERIFY_PARAM_set_hostflags(params, self->hostflags);
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002987
Antoine Pitrou152efa22010-05-16 18:19:27 +00002988 return (PyObject *)self;
2989}
2990
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002991static int
2992context_traverse(PySSLContext *self, visitproc visit, void *arg)
2993{
2994#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08002995 Py_VISIT(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002996#endif
2997 return 0;
2998}
2999
3000static int
3001context_clear(PySSLContext *self)
3002{
3003#ifndef OPENSSL_NO_TLSEXT
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003004 Py_CLEAR(self->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003005#endif
3006 return 0;
3007}
3008
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009static void
3010context_dealloc(PySSLContext *self)
3011{
INADA Naokia6296d32017-08-24 14:55:17 +09003012 /* bpo-31095: UnTrack is needed before calling any callbacks */
3013 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003014 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003015 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003016#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003017 PyMem_FREE(self->npn_protocols);
3018#endif
3019#ifdef HAVE_ALPN
3020 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003021#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00003022 Py_TYPE(self)->tp_free(self);
3023}
3024
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003025/*[clinic input]
3026_ssl._SSLContext.set_ciphers
3027 cipherlist: str
3028 /
3029[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003030
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003031static PyObject *
3032_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
3033/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
3034{
3035 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003036 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00003037 /* Clearing the error queue is necessary on some OpenSSL versions,
3038 otherwise the error will be reported again when another SSL call
3039 is done. */
3040 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003041 PyErr_SetString(PySSLErrorObject,
3042 "No cipher can be selected.");
3043 return NULL;
3044 }
3045 Py_RETURN_NONE;
3046}
3047
Christian Heimes25bfcd52016-09-06 00:04:45 +02003048#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
3049/*[clinic input]
3050_ssl._SSLContext.get_ciphers
3051[clinic start generated code]*/
3052
3053static PyObject *
3054_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
3055/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
3056{
3057 SSL *ssl = NULL;
3058 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02003059 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02003060 int i=0;
3061 PyObject *result = NULL, *dct;
3062
3063 ssl = SSL_new(self->ctx);
3064 if (ssl == NULL) {
3065 _setSSLError(NULL, 0, __FILE__, __LINE__);
3066 goto exit;
3067 }
3068 sk = SSL_get_ciphers(ssl);
3069
3070 result = PyList_New(sk_SSL_CIPHER_num(sk));
3071 if (result == NULL) {
3072 goto exit;
3073 }
3074
3075 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
3076 cipher = sk_SSL_CIPHER_value(sk, i);
3077 dct = cipher_to_dict(cipher);
3078 if (dct == NULL) {
3079 Py_CLEAR(result);
3080 goto exit;
3081 }
3082 PyList_SET_ITEM(result, i, dct);
3083 }
3084
3085 exit:
3086 if (ssl != NULL)
3087 SSL_free(ssl);
3088 return result;
3089
3090}
3091#endif
3092
3093
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003094#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003095static int
Benjamin Peterson88615022015-01-23 17:30:26 -05003096do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
3097 const unsigned char *server_protocols, unsigned int server_protocols_len,
3098 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05003099{
Benjamin Peterson88615022015-01-23 17:30:26 -05003100 int ret;
3101 if (client_protocols == NULL) {
3102 client_protocols = (unsigned char *)"";
3103 client_protocols_len = 0;
3104 }
3105 if (server_protocols == NULL) {
3106 server_protocols = (unsigned char *)"";
3107 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003108 }
3109
Benjamin Peterson88615022015-01-23 17:30:26 -05003110 ret = SSL_select_next_proto(out, outlen,
3111 server_protocols, server_protocols_len,
3112 client_protocols, client_protocols_len);
3113 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
3114 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003115
3116 return SSL_TLSEXT_ERR_OK;
3117}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003118#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003119
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003120#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003121/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3122static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003123_advertiseNPN_cb(SSL *s,
3124 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003125 void *args)
3126{
3127 PySSLContext *ssl_ctx = (PySSLContext *) args;
3128
3129 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003130 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003131 *len = 0;
3132 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003133 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003134 *len = ssl_ctx->npn_protocols_len;
3135 }
3136
3137 return SSL_TLSEXT_ERR_OK;
3138}
3139/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3140static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003141_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003142 unsigned char **out, unsigned char *outlen,
3143 const unsigned char *server, unsigned int server_len,
3144 void *args)
3145{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003146 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003147 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003148 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003149}
3150#endif
3151
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003152/*[clinic input]
3153_ssl._SSLContext._set_npn_protocols
3154 protos: Py_buffer
3155 /
3156[clinic start generated code]*/
3157
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003158static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003159_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3160 Py_buffer *protos)
3161/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003162{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003163#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003164 PyMem_Free(self->npn_protocols);
3165 self->npn_protocols = PyMem_Malloc(protos->len);
3166 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003167 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003168 memcpy(self->npn_protocols, protos->buf, protos->len);
3169 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003170
3171 /* set both server and client callbacks, because the context can
3172 * be used to create both types of sockets */
3173 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3174 _advertiseNPN_cb,
3175 self);
3176 SSL_CTX_set_next_proto_select_cb(self->ctx,
3177 _selectNPN_cb,
3178 self);
3179
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003180 Py_RETURN_NONE;
3181#else
3182 PyErr_SetString(PyExc_NotImplementedError,
3183 "The NPN extension requires OpenSSL 1.0.1 or later.");
3184 return NULL;
3185#endif
3186}
3187
Benjamin Petersoncca27322015-01-23 16:35:37 -05003188#ifdef HAVE_ALPN
3189static int
3190_selectALPN_cb(SSL *s,
3191 const unsigned char **out, unsigned char *outlen,
3192 const unsigned char *client_protocols, unsigned int client_protocols_len,
3193 void *args)
3194{
3195 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003196 return do_protocol_selection(1, (unsigned char **)out, outlen,
3197 ctx->alpn_protocols, ctx->alpn_protocols_len,
3198 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003199}
3200#endif
3201
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003202/*[clinic input]
3203_ssl._SSLContext._set_alpn_protocols
3204 protos: Py_buffer
3205 /
3206[clinic start generated code]*/
3207
Benjamin Petersoncca27322015-01-23 16:35:37 -05003208static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003209_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3210 Py_buffer *protos)
3211/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003212{
3213#ifdef HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003214 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003215 PyErr_Format(PyExc_OverflowError,
3216 "protocols longer than %d bytes", UINT_MAX);
3217 return NULL;
3218 }
3219
Benjamin Petersoncca27322015-01-23 16:35:37 -05003220 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003221 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003222 if (!self->alpn_protocols)
3223 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003224 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003225 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003226
3227 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3228 return PyErr_NoMemory();
3229 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3230
Benjamin Petersoncca27322015-01-23 16:35:37 -05003231 Py_RETURN_NONE;
3232#else
3233 PyErr_SetString(PyExc_NotImplementedError,
3234 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3235 return NULL;
3236#endif
3237}
3238
Antoine Pitrou152efa22010-05-16 18:19:27 +00003239static PyObject *
3240get_verify_mode(PySSLContext *self, void *c)
3241{
3242 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3243 case SSL_VERIFY_NONE:
3244 return PyLong_FromLong(PY_SSL_CERT_NONE);
3245 case SSL_VERIFY_PEER:
3246 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3247 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3248 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3249 }
3250 PyErr_SetString(PySSLErrorObject,
3251 "invalid return value from SSL_CTX_get_verify_mode");
3252 return NULL;
3253}
3254
3255static int
3256set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3257{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003258 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003259 if (!PyArg_Parse(arg, "i", &n))
3260 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003261 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003262 PyErr_SetString(PyExc_ValueError,
3263 "Cannot set verify_mode to CERT_NONE when "
3264 "check_hostname is enabled.");
3265 return -1;
3266 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003267 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003268}
3269
3270static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003271get_verify_flags(PySSLContext *self, void *c)
3272{
Christian Heimes598894f2016-09-05 23:19:05 +02003273 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003274 unsigned long flags;
3275
Christian Heimes61d478c2018-01-27 15:51:38 +01003276 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003277 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003278 return PyLong_FromUnsignedLong(flags);
3279}
3280
3281static int
3282set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3283{
Christian Heimes598894f2016-09-05 23:19:05 +02003284 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003285 unsigned long new_flags, flags, set, clear;
3286
3287 if (!PyArg_Parse(arg, "k", &new_flags))
3288 return -1;
Christian Heimes61d478c2018-01-27 15:51:38 +01003289 param = SSL_CTX_get0_param(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003290 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003291 clear = flags & ~new_flags;
3292 set = ~flags & new_flags;
3293 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003294 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003295 _setSSLError(NULL, 0, __FILE__, __LINE__);
3296 return -1;
3297 }
3298 }
3299 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003300 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003301 _setSSLError(NULL, 0, __FILE__, __LINE__);
3302 return -1;
3303 }
3304 }
3305 return 0;
3306}
3307
3308static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003309get_options(PySSLContext *self, void *c)
3310{
3311 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3312}
3313
3314static int
3315set_options(PySSLContext *self, PyObject *arg, void *c)
3316{
3317 long new_opts, opts, set, clear;
3318 if (!PyArg_Parse(arg, "l", &new_opts))
3319 return -1;
3320 opts = SSL_CTX_get_options(self->ctx);
3321 clear = opts & ~new_opts;
3322 set = ~opts & new_opts;
3323 if (clear) {
3324#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3325 SSL_CTX_clear_options(self->ctx, clear);
3326#else
3327 PyErr_SetString(PyExc_ValueError,
3328 "can't clear options before OpenSSL 0.9.8m");
3329 return -1;
3330#endif
3331 }
3332 if (set)
3333 SSL_CTX_set_options(self->ctx, set);
3334 return 0;
3335}
3336
Christian Heimes1aa9a752013-12-02 02:41:19 +01003337static PyObject *
Christian Heimes61d478c2018-01-27 15:51:38 +01003338get_host_flags(PySSLContext *self, void *c)
3339{
3340 return PyLong_FromUnsignedLong(self->hostflags);
3341}
3342
3343static int
3344set_host_flags(PySSLContext *self, PyObject *arg, void *c)
3345{
3346 X509_VERIFY_PARAM *param;
3347 unsigned int new_flags = 0;
3348
3349 if (!PyArg_Parse(arg, "I", &new_flags))
3350 return -1;
3351
3352 param = SSL_CTX_get0_param(self->ctx);
3353 self->hostflags = new_flags;
3354 X509_VERIFY_PARAM_set_hostflags(param, new_flags);
3355 return 0;
3356}
3357
3358static PyObject *
Christian Heimes1aa9a752013-12-02 02:41:19 +01003359get_check_hostname(PySSLContext *self, void *c)
3360{
3361 return PyBool_FromLong(self->check_hostname);
3362}
3363
3364static int
3365set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3366{
3367 int check_hostname;
3368 if (!PyArg_Parse(arg, "p", &check_hostname))
3369 return -1;
3370 if (check_hostname &&
3371 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003372 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3373 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3374 return -1;
3375 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003376 }
3377 self->check_hostname = check_hostname;
3378 return 0;
3379}
3380
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003381static PyObject *
3382get_protocol(PySSLContext *self, void *c) {
3383 return PyLong_FromLong(self->protocol);
3384}
Christian Heimes1aa9a752013-12-02 02:41:19 +01003385
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003386typedef struct {
3387 PyThreadState *thread_state;
3388 PyObject *callable;
3389 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003390 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003391 int error;
3392} _PySSLPasswordInfo;
3393
3394static int
3395_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3396 const char *bad_type_error)
3397{
3398 /* Set the password and size fields of a _PySSLPasswordInfo struct
3399 from a unicode, bytes, or byte array object.
3400 The password field will be dynamically allocated and must be freed
3401 by the caller */
3402 PyObject *password_bytes = NULL;
3403 const char *data = NULL;
3404 Py_ssize_t size;
3405
3406 if (PyUnicode_Check(password)) {
3407 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3408 if (!password_bytes) {
3409 goto error;
3410 }
3411 data = PyBytes_AS_STRING(password_bytes);
3412 size = PyBytes_GET_SIZE(password_bytes);
3413 } else if (PyBytes_Check(password)) {
3414 data = PyBytes_AS_STRING(password);
3415 size = PyBytes_GET_SIZE(password);
3416 } else if (PyByteArray_Check(password)) {
3417 data = PyByteArray_AS_STRING(password);
3418 size = PyByteArray_GET_SIZE(password);
3419 } else {
3420 PyErr_SetString(PyExc_TypeError, bad_type_error);
3421 goto error;
3422 }
3423
Victor Stinner9ee02032013-06-23 15:08:23 +02003424 if (size > (Py_ssize_t)INT_MAX) {
3425 PyErr_Format(PyExc_ValueError,
3426 "password cannot be longer than %d bytes", INT_MAX);
3427 goto error;
3428 }
3429
Victor Stinner11ebff22013-07-07 17:07:52 +02003430 PyMem_Free(pw_info->password);
3431 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003432 if (!pw_info->password) {
3433 PyErr_SetString(PyExc_MemoryError,
3434 "unable to allocate password buffer");
3435 goto error;
3436 }
3437 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003438 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003439
3440 Py_XDECREF(password_bytes);
3441 return 1;
3442
3443error:
3444 Py_XDECREF(password_bytes);
3445 return 0;
3446}
3447
3448static int
3449_password_callback(char *buf, int size, int rwflag, void *userdata)
3450{
3451 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3452 PyObject *fn_ret = NULL;
3453
3454 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3455
3456 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003457 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003458 if (!fn_ret) {
3459 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3460 core python API, so we could use it to add a frame here */
3461 goto error;
3462 }
3463
3464 if (!_pwinfo_set(pw_info, fn_ret,
3465 "password callback must return a string")) {
3466 goto error;
3467 }
3468 Py_CLEAR(fn_ret);
3469 }
3470
3471 if (pw_info->size > size) {
3472 PyErr_Format(PyExc_ValueError,
3473 "password cannot be longer than %d bytes", size);
3474 goto error;
3475 }
3476
3477 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3478 memcpy(buf, pw_info->password, pw_info->size);
3479 return pw_info->size;
3480
3481error:
3482 Py_XDECREF(fn_ret);
3483 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3484 pw_info->error = 1;
3485 return -1;
3486}
3487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003488/*[clinic input]
3489_ssl._SSLContext.load_cert_chain
3490 certfile: object
3491 keyfile: object = NULL
3492 password: object = NULL
3493
3494[clinic start generated code]*/
3495
Antoine Pitroub5218772010-05-21 09:56:06 +00003496static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003497_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3498 PyObject *keyfile, PyObject *password)
3499/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003500{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003501 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003502 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3503 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003504 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003505 int r;
3506
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003507 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003508 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003509 if (keyfile == Py_None)
3510 keyfile = NULL;
3511 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3512 PyErr_SetString(PyExc_TypeError,
3513 "certfile should be a valid filesystem path");
3514 return NULL;
3515 }
3516 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3517 PyErr_SetString(PyExc_TypeError,
3518 "keyfile should be a valid filesystem path");
3519 goto error;
3520 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003521 if (password && password != Py_None) {
3522 if (PyCallable_Check(password)) {
3523 pw_info.callable = password;
3524 } else if (!_pwinfo_set(&pw_info, password,
3525 "password should be a string or callable")) {
3526 goto error;
3527 }
3528 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3529 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3530 }
3531 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003532 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3533 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003534 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003535 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003536 if (pw_info.error) {
3537 ERR_clear_error();
3538 /* the password callback has already set the error information */
3539 }
3540 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003541 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003542 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003543 }
3544 else {
3545 _setSSLError(NULL, 0, __FILE__, __LINE__);
3546 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003547 goto error;
3548 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003549 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003550 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003551 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3552 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003553 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3554 Py_CLEAR(keyfile_bytes);
3555 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003556 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003557 if (pw_info.error) {
3558 ERR_clear_error();
3559 /* the password callback has already set the error information */
3560 }
3561 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003562 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003563 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003564 }
3565 else {
3566 _setSSLError(NULL, 0, __FILE__, __LINE__);
3567 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003568 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003569 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003570 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003571 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003572 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003573 if (r != 1) {
3574 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003575 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003576 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003577 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3578 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003579 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003580 Py_RETURN_NONE;
3581
3582error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003583 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3584 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003585 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003586 Py_XDECREF(keyfile_bytes);
3587 Py_XDECREF(certfile_bytes);
3588 return NULL;
3589}
3590
Christian Heimesefff7062013-11-21 03:35:02 +01003591/* internal helper function, returns -1 on error
3592 */
3593static int
3594_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3595 int filetype)
3596{
3597 BIO *biobuf = NULL;
3598 X509_STORE *store;
3599 int retval = 0, err, loaded = 0;
3600
3601 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3602
3603 if (len <= 0) {
3604 PyErr_SetString(PyExc_ValueError,
3605 "Empty certificate data");
3606 return -1;
3607 } else if (len > INT_MAX) {
3608 PyErr_SetString(PyExc_OverflowError,
3609 "Certificate data is too long.");
3610 return -1;
3611 }
3612
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003613 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003614 if (biobuf == NULL) {
3615 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3616 return -1;
3617 }
3618
3619 store = SSL_CTX_get_cert_store(self->ctx);
3620 assert(store != NULL);
3621
3622 while (1) {
3623 X509 *cert = NULL;
3624 int r;
3625
3626 if (filetype == SSL_FILETYPE_ASN1) {
3627 cert = d2i_X509_bio(biobuf, NULL);
3628 } else {
3629 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003630 SSL_CTX_get_default_passwd_cb(self->ctx),
3631 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3632 );
Christian Heimesefff7062013-11-21 03:35:02 +01003633 }
3634 if (cert == NULL) {
3635 break;
3636 }
3637 r = X509_STORE_add_cert(store, cert);
3638 X509_free(cert);
3639 if (!r) {
3640 err = ERR_peek_last_error();
3641 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3642 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3643 /* cert already in hash table, not an error */
3644 ERR_clear_error();
3645 } else {
3646 break;
3647 }
3648 }
3649 loaded++;
3650 }
3651
3652 err = ERR_peek_last_error();
3653 if ((filetype == SSL_FILETYPE_ASN1) &&
3654 (loaded > 0) &&
3655 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3656 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3657 /* EOF ASN1 file, not an error */
3658 ERR_clear_error();
3659 retval = 0;
3660 } else if ((filetype == SSL_FILETYPE_PEM) &&
3661 (loaded > 0) &&
3662 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3663 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3664 /* EOF PEM file, not an error */
3665 ERR_clear_error();
3666 retval = 0;
3667 } else {
3668 _setSSLError(NULL, 0, __FILE__, __LINE__);
3669 retval = -1;
3670 }
3671
3672 BIO_free(biobuf);
3673 return retval;
3674}
3675
3676
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003677/*[clinic input]
3678_ssl._SSLContext.load_verify_locations
3679 cafile: object = NULL
3680 capath: object = NULL
3681 cadata: object = NULL
3682
3683[clinic start generated code]*/
3684
Antoine Pitrou152efa22010-05-16 18:19:27 +00003685static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003686_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3687 PyObject *cafile,
3688 PyObject *capath,
3689 PyObject *cadata)
3690/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003691{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003692 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3693 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003694 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003695
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003696 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003697 if (cafile == Py_None)
3698 cafile = NULL;
3699 if (capath == Py_None)
3700 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003701 if (cadata == Py_None)
3702 cadata = NULL;
3703
3704 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003705 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003706 "cafile, capath and cadata cannot be all omitted");
3707 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708 }
3709 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3710 PyErr_SetString(PyExc_TypeError,
3711 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003712 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003713 }
3714 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003715 PyErr_SetString(PyExc_TypeError,
3716 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003717 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003718 }
Christian Heimesefff7062013-11-21 03:35:02 +01003719
3720 /* validata cadata type and load cadata */
3721 if (cadata) {
3722 Py_buffer buf;
3723 PyObject *cadata_ascii = NULL;
3724
3725 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3726 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3727 PyBuffer_Release(&buf);
3728 PyErr_SetString(PyExc_TypeError,
3729 "cadata should be a contiguous buffer with "
3730 "a single dimension");
3731 goto error;
3732 }
3733 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3734 PyBuffer_Release(&buf);
3735 if (r == -1) {
3736 goto error;
3737 }
3738 } else {
3739 PyErr_Clear();
3740 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3741 if (cadata_ascii == NULL) {
3742 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003743 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003744 "bytes-like object");
3745 goto error;
3746 }
3747 r = _add_ca_certs(self,
3748 PyBytes_AS_STRING(cadata_ascii),
3749 PyBytes_GET_SIZE(cadata_ascii),
3750 SSL_FILETYPE_PEM);
3751 Py_DECREF(cadata_ascii);
3752 if (r == -1) {
3753 goto error;
3754 }
3755 }
3756 }
3757
3758 /* load cafile or capath */
3759 if (cafile || capath) {
3760 if (cafile)
3761 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3762 if (capath)
3763 capath_buf = PyBytes_AS_STRING(capath_bytes);
3764 PySSL_BEGIN_ALLOW_THREADS
3765 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3766 PySSL_END_ALLOW_THREADS
3767 if (r != 1) {
3768 ok = 0;
3769 if (errno != 0) {
3770 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003771 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003772 }
3773 else {
3774 _setSSLError(NULL, 0, __FILE__, __LINE__);
3775 }
3776 goto error;
3777 }
3778 }
3779 goto end;
3780
3781 error:
3782 ok = 0;
3783 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003784 Py_XDECREF(cafile_bytes);
3785 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003786 if (ok) {
3787 Py_RETURN_NONE;
3788 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003789 return NULL;
3790 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003791}
3792
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003793/*[clinic input]
3794_ssl._SSLContext.load_dh_params
3795 path as filepath: object
3796 /
3797
3798[clinic start generated code]*/
3799
Antoine Pitrou152efa22010-05-16 18:19:27 +00003800static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003801_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3802/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003803{
3804 FILE *f;
3805 DH *dh;
3806
Victor Stinnerdaf45552013-08-28 00:53:59 +02003807 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003808 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003809 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003810
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003811 errno = 0;
3812 PySSL_BEGIN_ALLOW_THREADS
3813 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003814 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003815 PySSL_END_ALLOW_THREADS
3816 if (dh == NULL) {
3817 if (errno != 0) {
3818 ERR_clear_error();
3819 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3820 }
3821 else {
3822 _setSSLError(NULL, 0, __FILE__, __LINE__);
3823 }
3824 return NULL;
3825 }
3826 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3827 _setSSLError(NULL, 0, __FILE__, __LINE__);
3828 DH_free(dh);
3829 Py_RETURN_NONE;
3830}
3831
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003832/*[clinic input]
3833_ssl._SSLContext._wrap_socket
3834 sock: object(subclass_of="PySocketModule.Sock_Type")
3835 server_side: int
3836 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08003837 *
3838 owner: object = None
3839 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003840
3841[clinic start generated code]*/
3842
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003843static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003844_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08003845 int server_side, PyObject *hostname_obj,
3846 PyObject *owner, PyObject *session)
3847/*[clinic end generated code: output=f103f238633940b4 input=957d5006183d1894]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003848{
Antoine Pitroud5323212010-10-22 18:19:07 +00003849 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003850 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003851
Antoine Pitroud5323212010-10-22 18:19:07 +00003852 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003853 as IDN A-label (ASCII str). */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003854 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003855 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003856 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003857 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003858
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003859 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3860 server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08003861 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003862 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003863 if (hostname != NULL)
3864 PyMem_Free(hostname);
3865 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003866}
3867
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003868/*[clinic input]
3869_ssl._SSLContext._wrap_bio
3870 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3871 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3872 server_side: int
3873 server_hostname as hostname_obj: object = None
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08003874 *
3875 owner: object = None
3876 session: object = None
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003877
3878[clinic start generated code]*/
3879
Antoine Pitroub0182c82010-10-12 20:09:02 +00003880static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003881_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3882 PySSLMemoryBIO *outgoing, int server_side,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08003883 PyObject *hostname_obj, PyObject *owner,
3884 PyObject *session)
3885/*[clinic end generated code: output=5c5d6d9b41f99332 input=8cf22f4d586ac56a]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003886{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003887 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003888 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003889
3890 /* server_hostname is either None (or absent), or to be encoded
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003891 as IDN A-label (ASCII str). */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003892 if (hostname_obj != Py_None) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08003893 if (!PyArg_Parse(hostname_obj, "es", "ascii", &hostname))
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003894 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003895 }
3896
3897 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
Miss Islington (bot)8fa84782018-02-24 12:51:56 -08003898 owner, session,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003899 incoming, outgoing);
3900
3901 PyMem_Free(hostname);
3902 return res;
3903}
3904
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003905/*[clinic input]
3906_ssl._SSLContext.session_stats
3907[clinic start generated code]*/
3908
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003909static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003910_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3911/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003912{
3913 int r;
3914 PyObject *value, *stats = PyDict_New();
3915 if (!stats)
3916 return NULL;
3917
3918#define ADD_STATS(SSL_NAME, KEY_NAME) \
3919 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3920 if (value == NULL) \
3921 goto error; \
3922 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3923 Py_DECREF(value); \
3924 if (r < 0) \
3925 goto error;
3926
3927 ADD_STATS(number, "number");
3928 ADD_STATS(connect, "connect");
3929 ADD_STATS(connect_good, "connect_good");
3930 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3931 ADD_STATS(accept, "accept");
3932 ADD_STATS(accept_good, "accept_good");
3933 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3934 ADD_STATS(accept, "accept");
3935 ADD_STATS(hits, "hits");
3936 ADD_STATS(misses, "misses");
3937 ADD_STATS(timeouts, "timeouts");
3938 ADD_STATS(cache_full, "cache_full");
3939
3940#undef ADD_STATS
3941
3942 return stats;
3943
3944error:
3945 Py_DECREF(stats);
3946 return NULL;
3947}
3948
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003949/*[clinic input]
3950_ssl._SSLContext.set_default_verify_paths
3951[clinic start generated code]*/
3952
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003953static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003954_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3955/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003956{
3957 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3958 _setSSLError(NULL, 0, __FILE__, __LINE__);
3959 return NULL;
3960 }
3961 Py_RETURN_NONE;
3962}
3963
Antoine Pitrou501da612011-12-21 09:27:41 +01003964#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003965/*[clinic input]
3966_ssl._SSLContext.set_ecdh_curve
3967 name: object
3968 /
3969
3970[clinic start generated code]*/
3971
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003972static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003973_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3974/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003975{
3976 PyObject *name_bytes;
3977 int nid;
3978 EC_KEY *key;
3979
3980 if (!PyUnicode_FSConverter(name, &name_bytes))
3981 return NULL;
3982 assert(PyBytes_Check(name_bytes));
3983 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3984 Py_DECREF(name_bytes);
3985 if (nid == 0) {
3986 PyErr_Format(PyExc_ValueError,
3987 "unknown elliptic curve name %R", name);
3988 return NULL;
3989 }
3990 key = EC_KEY_new_by_curve_name(nid);
3991 if (key == NULL) {
3992 _setSSLError(NULL, 0, __FILE__, __LINE__);
3993 return NULL;
3994 }
3995 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3996 EC_KEY_free(key);
3997 Py_RETURN_NONE;
3998}
Antoine Pitrou501da612011-12-21 09:27:41 +01003999#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01004000
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004001#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004002static int
4003_servername_callback(SSL *s, int *al, void *args)
4004{
4005 int ret;
4006 PySSLContext *ssl_ctx = (PySSLContext *) args;
4007 PySSLSocket *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004008 PyObject *result;
4009 /* The high-level ssl.SSLSocket object */
4010 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004011 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01004012 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004013
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004014 if (ssl_ctx->set_sni_cb == NULL) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004015 /* remove race condition in this the call back while if removing the
4016 * callback is in progress */
4017 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01004018 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004019 }
4020
4021 ssl = SSL_get_app_data(s);
4022 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004023
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02004024 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004025 * SSL connection and that has a .context attribute that can be changed to
4026 * identify the requested hostname. Since the official API is the Python
4027 * level API we want to pass the callback a Python level object rather than
4028 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
4029 * SSLObject) that will be passed. Otherwise if there's a socket then that
4030 * will be passed. If both do not exist only then the C-level object is
4031 * passed. */
4032 if (ssl->owner)
4033 ssl_socket = PyWeakref_GetObject(ssl->owner);
4034 else if (ssl->Socket)
4035 ssl_socket = PyWeakref_GetObject(ssl->Socket);
4036 else
4037 ssl_socket = (PyObject *) ssl;
4038
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004039 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004040 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004041 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02004042
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004043 if (servername == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004044 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_sni_cb, ssl_socket,
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004045 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004046 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004047 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004048 PyObject *servername_bytes;
4049 PyObject *servername_str;
4050
4051 servername_bytes = PyBytes_FromString(servername);
4052 if (servername_bytes == NULL) {
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004053 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
4054 goto error;
4055 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004056 /* server_hostname was encoded to an A-label by our caller; put it
4057 * back into a str object, but still as an A-label (bpo-28414)
4058 */
4059 servername_str = PyUnicode_FromEncodedObject(servername_bytes, "ascii", NULL);
4060 Py_DECREF(servername_bytes);
4061 if (servername_str == NULL) {
4062 PyErr_WriteUnraisable(servername_bytes);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02004063 goto error;
4064 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004065 result = PyObject_CallFunctionObjArgs(
4066 ssl_ctx->set_sni_cb, ssl_socket, servername_str,
4067 ssl_ctx, NULL);
4068 Py_DECREF(servername_str);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004069 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004070 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004071
4072 if (result == NULL) {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004073 PyErr_WriteUnraisable(ssl_ctx->set_sni_cb);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004074 *al = SSL_AD_HANDSHAKE_FAILURE;
4075 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4076 }
4077 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004078 /* Result may be None, a SSLContext or an integer
4079 * None and SSLContext are OK, integer or other values are an error.
4080 */
4081 if (result == Py_None) {
4082 ret = SSL_TLSEXT_ERR_OK;
4083 } else {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004084 *al = (int) PyLong_AsLong(result);
4085 if (PyErr_Occurred()) {
4086 PyErr_WriteUnraisable(result);
4087 *al = SSL_AD_INTERNAL_ERROR;
4088 }
4089 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4090 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004091 Py_DECREF(result);
4092 }
4093
4094 PyGILState_Release(gstate);
4095 return ret;
4096
4097error:
4098 Py_DECREF(ssl_socket);
4099 *al = SSL_AD_INTERNAL_ERROR;
4100 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
4101 PyGILState_Release(gstate);
4102 return ret;
4103}
Antoine Pitroua5963382013-03-30 16:39:00 +01004104#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004105
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004106static PyObject *
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004107get_sni_callback(PySSLContext *self, void *c)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004108{
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004109 PyObject *cb = self->set_sni_cb;
4110 if (cb == NULL) {
4111 Py_RETURN_NONE;
4112 }
4113 Py_INCREF(cb);
4114 return cb;
4115}
4116
4117static int
4118set_sni_callback(PySSLContext *self, PyObject *arg, void *c)
4119{
4120 if (self->protocol == PY_SSL_VERSION_TLS_CLIENT) {
4121 PyErr_SetString(PyExc_ValueError,
4122 "sni_callback cannot be set on TLS_CLIENT context");
4123 return -1;
4124 }
Antoine Pitrou912fbff2013-03-30 16:29:32 +01004125#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004126 Py_CLEAR(self->set_sni_cb);
4127 if (arg == Py_None) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004128 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4129 }
4130 else {
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004131 if (!PyCallable_Check(arg)) {
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004132 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
4133 PyErr_SetString(PyExc_TypeError,
4134 "not a callable object");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004135 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004136 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004137 Py_INCREF(arg);
4138 self->set_sni_cb = arg;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004139 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
4140 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
4141 }
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004142 return 0;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004143#else
4144 PyErr_SetString(PyExc_NotImplementedError,
4145 "The TLS extension servername callback, "
4146 "SSL_CTX_set_tlsext_servername_callback, "
4147 "is not in the current OpenSSL library.");
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004148 return -1;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004149#endif
4150}
4151
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004152PyDoc_STRVAR(PySSLContext_sni_callback_doc,
4153"Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.\n\
4154\n\
4155If the argument is None then the callback is disabled. The method is called\n\
4156with the SSLSocket, the server name as a string, and the SSLContext object.\n\
4157See RFC 6066 for details of the SNI extension.");
4158
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159/*[clinic input]
4160_ssl._SSLContext.cert_store_stats
4161
4162Returns quantities of loaded X.509 certificates.
4163
4164X.509 certificates with a CA extension and certificate revocation lists
4165inside the context's cert store.
4166
4167NOTE: Certificates in a capath directory aren't loaded unless they have
4168been used at least once.
4169[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004170
4171static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004172_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4173/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004174{
4175 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004176 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004177 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004178 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004179
4180 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004181 objs = X509_STORE_get0_objects(store);
4182 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4183 obj = sk_X509_OBJECT_value(objs, i);
4184 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004185 case X509_LU_X509:
4186 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004187 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004188 ca++;
4189 }
4190 break;
4191 case X509_LU_CRL:
4192 crl++;
4193 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004194 default:
4195 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4196 * As far as I can tell they are internal states and never
4197 * stored in a cert store */
4198 break;
4199 }
4200 }
4201 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4202 "x509_ca", ca);
4203}
4204
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004205/*[clinic input]
4206_ssl._SSLContext.get_ca_certs
4207 binary_form: bool = False
4208
4209Returns a list of dicts with information of loaded CA certs.
4210
4211If the optional argument is True, returns a DER-encoded copy of the CA
4212certificate.
4213
4214NOTE: Certificates in a capath directory aren't loaded unless they have
4215been used at least once.
4216[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004217
4218static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004219_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4220/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004221{
4222 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004223 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004224 PyObject *ci = NULL, *rlist = NULL;
4225 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004226
4227 if ((rlist = PyList_New(0)) == NULL) {
4228 return NULL;
4229 }
4230
4231 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004232 objs = X509_STORE_get0_objects(store);
4233 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004234 X509_OBJECT *obj;
4235 X509 *cert;
4236
Christian Heimes598894f2016-09-05 23:19:05 +02004237 obj = sk_X509_OBJECT_value(objs, i);
4238 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004239 /* not a x509 cert */
4240 continue;
4241 }
4242 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004243 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004244 if (!X509_check_ca(cert)) {
4245 continue;
4246 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004247 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004248 ci = _certificate_to_der(cert);
4249 } else {
4250 ci = _decode_certificate(cert);
4251 }
4252 if (ci == NULL) {
4253 goto error;
4254 }
4255 if (PyList_Append(rlist, ci) == -1) {
4256 goto error;
4257 }
4258 Py_CLEAR(ci);
4259 }
4260 return rlist;
4261
4262 error:
4263 Py_XDECREF(ci);
4264 Py_XDECREF(rlist);
4265 return NULL;
4266}
4267
4268
Antoine Pitrou152efa22010-05-16 18:19:27 +00004269static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004270 {"check_hostname", (getter) get_check_hostname,
4271 (setter) set_check_hostname, NULL},
Christian Heimes61d478c2018-01-27 15:51:38 +01004272 {"_host_flags", (getter) get_host_flags,
4273 (setter) set_host_flags, NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004274 {"sni_callback", (getter) get_sni_callback,
4275 (setter) set_sni_callback, PySSLContext_sni_callback_doc},
Antoine Pitroub5218772010-05-21 09:56:06 +00004276 {"options", (getter) get_options,
4277 (setter) set_options, NULL},
Miss Islington (bot)1c37e272018-02-23 19:18:28 -08004278 {"protocol", (getter) get_protocol,
4279 NULL, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004280 {"verify_flags", (getter) get_verify_flags,
4281 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004282 {"verify_mode", (getter) get_verify_mode,
4283 (setter) set_verify_mode, NULL},
4284 {NULL}, /* sentinel */
4285};
4286
4287static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004288 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4289 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4290 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4291 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4292 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4293 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4294 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4295 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4296 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4297 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4298 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004299 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4300 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004301 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004302 {NULL, NULL} /* sentinel */
4303};
4304
4305static PyTypeObject PySSLContext_Type = {
4306 PyVarObject_HEAD_INIT(NULL, 0)
4307 "_ssl._SSLContext", /*tp_name*/
4308 sizeof(PySSLContext), /*tp_basicsize*/
4309 0, /*tp_itemsize*/
4310 (destructor)context_dealloc, /*tp_dealloc*/
4311 0, /*tp_print*/
4312 0, /*tp_getattr*/
4313 0, /*tp_setattr*/
4314 0, /*tp_reserved*/
4315 0, /*tp_repr*/
4316 0, /*tp_as_number*/
4317 0, /*tp_as_sequence*/
4318 0, /*tp_as_mapping*/
4319 0, /*tp_hash*/
4320 0, /*tp_call*/
4321 0, /*tp_str*/
4322 0, /*tp_getattro*/
4323 0, /*tp_setattro*/
4324 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004325 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004326 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004327 (traverseproc) context_traverse, /*tp_traverse*/
4328 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004329 0, /*tp_richcompare*/
4330 0, /*tp_weaklistoffset*/
4331 0, /*tp_iter*/
4332 0, /*tp_iternext*/
4333 context_methods, /*tp_methods*/
4334 0, /*tp_members*/
4335 context_getsetlist, /*tp_getset*/
4336 0, /*tp_base*/
4337 0, /*tp_dict*/
4338 0, /*tp_descr_get*/
4339 0, /*tp_descr_set*/
4340 0, /*tp_dictoffset*/
4341 0, /*tp_init*/
4342 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004343 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004344};
4345
4346
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004347/*
4348 * MemoryBIO objects
4349 */
4350
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004351/*[clinic input]
4352@classmethod
4353_ssl.MemoryBIO.__new__
4354
4355[clinic start generated code]*/
4356
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004357static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004358_ssl_MemoryBIO_impl(PyTypeObject *type)
4359/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004360{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004361 BIO *bio;
4362 PySSLMemoryBIO *self;
4363
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004364 bio = BIO_new(BIO_s_mem());
4365 if (bio == NULL) {
4366 PyErr_SetString(PySSLErrorObject,
4367 "failed to allocate BIO");
4368 return NULL;
4369 }
4370 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4371 * just that no data is currently available. The SSL routines should retry
4372 * the read, which we can achieve by calling BIO_set_retry_read(). */
4373 BIO_set_retry_read(bio);
4374 BIO_set_mem_eof_return(bio, -1);
4375
4376 assert(type != NULL && type->tp_alloc != NULL);
4377 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4378 if (self == NULL) {
4379 BIO_free(bio);
4380 return NULL;
4381 }
4382 self->bio = bio;
4383 self->eof_written = 0;
4384
4385 return (PyObject *) self;
4386}
4387
4388static void
4389memory_bio_dealloc(PySSLMemoryBIO *self)
4390{
4391 BIO_free(self->bio);
4392 Py_TYPE(self)->tp_free(self);
4393}
4394
4395static PyObject *
4396memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4397{
Segev Finer5cff6372017-07-27 01:19:17 +03004398 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004399}
4400
4401PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4402"The number of bytes pending in the memory BIO.");
4403
4404static PyObject *
4405memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4406{
4407 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4408 && self->eof_written);
4409}
4410
4411PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4412"Whether the memory BIO is at EOF.");
4413
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004414/*[clinic input]
4415_ssl.MemoryBIO.read
4416 size as len: int = -1
4417 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004418
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004419Read up to size bytes from the memory BIO.
4420
4421If size is not specified, read the entire buffer.
4422If the return value is an empty bytes instance, this means either
4423EOF or that no data is available. Use the "eof" property to
4424distinguish between the two.
4425[clinic start generated code]*/
4426
4427static PyObject *
4428_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4429/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4430{
4431 int avail, nbytes;
4432 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004433
Segev Finer5cff6372017-07-27 01:19:17 +03004434 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004435 if ((len < 0) || (len > avail))
4436 len = avail;
4437
4438 result = PyBytes_FromStringAndSize(NULL, len);
4439 if ((result == NULL) || (len == 0))
4440 return result;
4441
4442 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4443 /* There should never be any short reads but check anyway. */
4444 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4445 Py_DECREF(result);
4446 return NULL;
4447 }
4448
4449 return result;
4450}
4451
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004452/*[clinic input]
4453_ssl.MemoryBIO.write
4454 b: Py_buffer
4455 /
4456
4457Writes the bytes b into the memory BIO.
4458
4459Returns the number of bytes written.
4460[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004461
4462static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004463_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4464/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004465{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004466 int nbytes;
4467
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004468 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004469 PyErr_Format(PyExc_OverflowError,
4470 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004471 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004472 }
4473
4474 if (self->eof_written) {
4475 PyErr_SetString(PySSLErrorObject,
4476 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004477 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004478 }
4479
Segev Finer5cff6372017-07-27 01:19:17 +03004480 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004481 if (nbytes < 0) {
4482 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004483 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004484 }
4485
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004486 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004487}
4488
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004489/*[clinic input]
4490_ssl.MemoryBIO.write_eof
4491
4492Write an EOF marker to the memory BIO.
4493
4494When all data has been read, the "eof" property will be True.
4495[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004496
4497static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004498_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4499/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004500{
4501 self->eof_written = 1;
4502 /* After an EOF is written, a zero return from read() should be a real EOF
4503 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4504 BIO_clear_retry_flags(self->bio);
4505 BIO_set_mem_eof_return(self->bio, 0);
4506
4507 Py_RETURN_NONE;
4508}
4509
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004510static PyGetSetDef memory_bio_getsetlist[] = {
4511 {"pending", (getter) memory_bio_get_pending, NULL,
4512 PySSL_memory_bio_pending_doc},
4513 {"eof", (getter) memory_bio_get_eof, NULL,
4514 PySSL_memory_bio_eof_doc},
4515 {NULL}, /* sentinel */
4516};
4517
4518static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004519 _SSL_MEMORYBIO_READ_METHODDEF
4520 _SSL_MEMORYBIO_WRITE_METHODDEF
4521 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004522 {NULL, NULL} /* sentinel */
4523};
4524
4525static PyTypeObject PySSLMemoryBIO_Type = {
4526 PyVarObject_HEAD_INIT(NULL, 0)
4527 "_ssl.MemoryBIO", /*tp_name*/
4528 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4529 0, /*tp_itemsize*/
4530 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4531 0, /*tp_print*/
4532 0, /*tp_getattr*/
4533 0, /*tp_setattr*/
4534 0, /*tp_reserved*/
4535 0, /*tp_repr*/
4536 0, /*tp_as_number*/
4537 0, /*tp_as_sequence*/
4538 0, /*tp_as_mapping*/
4539 0, /*tp_hash*/
4540 0, /*tp_call*/
4541 0, /*tp_str*/
4542 0, /*tp_getattro*/
4543 0, /*tp_setattro*/
4544 0, /*tp_as_buffer*/
4545 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4546 0, /*tp_doc*/
4547 0, /*tp_traverse*/
4548 0, /*tp_clear*/
4549 0, /*tp_richcompare*/
4550 0, /*tp_weaklistoffset*/
4551 0, /*tp_iter*/
4552 0, /*tp_iternext*/
4553 memory_bio_methods, /*tp_methods*/
4554 0, /*tp_members*/
4555 memory_bio_getsetlist, /*tp_getset*/
4556 0, /*tp_base*/
4557 0, /*tp_dict*/
4558 0, /*tp_descr_get*/
4559 0, /*tp_descr_set*/
4560 0, /*tp_dictoffset*/
4561 0, /*tp_init*/
4562 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004563 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004564};
4565
Antoine Pitrou152efa22010-05-16 18:19:27 +00004566
Christian Heimes99a65702016-09-10 23:44:53 +02004567/*
4568 * SSL Session object
4569 */
4570
4571static void
4572PySSLSession_dealloc(PySSLSession *self)
4573{
INADA Naokia6296d32017-08-24 14:55:17 +09004574 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004575 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004576 Py_XDECREF(self->ctx);
4577 if (self->session != NULL) {
4578 SSL_SESSION_free(self->session);
4579 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004580 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004581}
4582
4583static PyObject *
4584PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4585{
4586 int result;
4587
4588 if (left == NULL || right == NULL) {
4589 PyErr_BadInternalCall();
4590 return NULL;
4591 }
4592
4593 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4594 Py_RETURN_NOTIMPLEMENTED;
4595 }
4596
4597 if (left == right) {
4598 result = 0;
4599 } else {
4600 const unsigned char *left_id, *right_id;
4601 unsigned int left_len, right_len;
4602 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4603 &left_len);
4604 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4605 &right_len);
4606 if (left_len == right_len) {
4607 result = memcmp(left_id, right_id, left_len);
4608 } else {
4609 result = 1;
4610 }
4611 }
4612
4613 switch (op) {
4614 case Py_EQ:
4615 if (result == 0) {
4616 Py_RETURN_TRUE;
4617 } else {
4618 Py_RETURN_FALSE;
4619 }
4620 break;
4621 case Py_NE:
4622 if (result != 0) {
4623 Py_RETURN_TRUE;
4624 } else {
4625 Py_RETURN_FALSE;
4626 }
4627 break;
4628 case Py_LT:
4629 case Py_LE:
4630 case Py_GT:
4631 case Py_GE:
4632 Py_RETURN_NOTIMPLEMENTED;
4633 break;
4634 default:
4635 PyErr_BadArgument();
4636 return NULL;
4637 }
4638}
4639
4640static int
4641PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4642{
4643 Py_VISIT(self->ctx);
4644 return 0;
4645}
4646
4647static int
4648PySSLSession_clear(PySSLSession *self)
4649{
4650 Py_CLEAR(self->ctx);
4651 return 0;
4652}
4653
4654
4655static PyObject *
4656PySSLSession_get_time(PySSLSession *self, void *closure) {
4657 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4658}
4659
4660PyDoc_STRVAR(PySSLSession_get_time_doc,
4661"Session creation time (seconds since epoch).");
4662
4663
4664static PyObject *
4665PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4666 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4667}
4668
4669PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4670"Session timeout (delta in seconds).");
4671
4672
4673static PyObject *
4674PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4675 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4676 return PyLong_FromUnsignedLong(hint);
4677}
4678
4679PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4680"Ticket life time hint.");
4681
4682
4683static PyObject *
4684PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4685 const unsigned char *id;
4686 unsigned int len;
4687 id = SSL_SESSION_get_id(self->session, &len);
4688 return PyBytes_FromStringAndSize((const char *)id, len);
4689}
4690
4691PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4692"Session id");
4693
4694
4695static PyObject *
4696PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4697 if (SSL_SESSION_has_ticket(self->session)) {
4698 Py_RETURN_TRUE;
4699 } else {
4700 Py_RETURN_FALSE;
4701 }
4702}
4703
4704PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4705"Does the session contain a ticket?");
4706
4707
4708static PyGetSetDef PySSLSession_getsetlist[] = {
4709 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4710 PySSLSession_get_has_ticket_doc},
4711 {"id", (getter) PySSLSession_get_session_id, NULL,
4712 PySSLSession_get_session_id_doc},
4713 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4714 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4715 {"time", (getter) PySSLSession_get_time, NULL,
4716 PySSLSession_get_time_doc},
4717 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4718 PySSLSession_get_timeout_doc},
4719 {NULL}, /* sentinel */
4720};
4721
4722static PyTypeObject PySSLSession_Type = {
4723 PyVarObject_HEAD_INIT(NULL, 0)
4724 "_ssl.Session", /*tp_name*/
4725 sizeof(PySSLSession), /*tp_basicsize*/
4726 0, /*tp_itemsize*/
4727 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4728 0, /*tp_print*/
4729 0, /*tp_getattr*/
4730 0, /*tp_setattr*/
4731 0, /*tp_reserved*/
4732 0, /*tp_repr*/
4733 0, /*tp_as_number*/
4734 0, /*tp_as_sequence*/
4735 0, /*tp_as_mapping*/
4736 0, /*tp_hash*/
4737 0, /*tp_call*/
4738 0, /*tp_str*/
4739 0, /*tp_getattro*/
4740 0, /*tp_setattro*/
4741 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004742 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004743 0, /*tp_doc*/
4744 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4745 (inquiry)PySSLSession_clear, /*tp_clear*/
4746 PySSLSession_richcompare, /*tp_richcompare*/
4747 0, /*tp_weaklistoffset*/
4748 0, /*tp_iter*/
4749 0, /*tp_iternext*/
4750 0, /*tp_methods*/
4751 0, /*tp_members*/
4752 PySSLSession_getsetlist, /*tp_getset*/
4753};
4754
4755
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004756/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004757/*[clinic input]
4758_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004759 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004760 entropy: double
4761 /
4762
4763Mix string into the OpenSSL PRNG state.
4764
4765entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304766string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004767[clinic start generated code]*/
4768
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004769static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004770_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004771/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004772{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004773 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004774 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004775
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004776 buf = (const char *)view->buf;
4777 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004778 do {
4779 written = Py_MIN(len, INT_MAX);
4780 RAND_add(buf, (int)written, entropy);
4781 buf += written;
4782 len -= written;
4783 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004784 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004785}
4786
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004787static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004788PySSL_RAND(int len, int pseudo)
4789{
4790 int ok;
4791 PyObject *bytes;
4792 unsigned long err;
4793 const char *errstr;
4794 PyObject *v;
4795
Victor Stinner1e81a392013-12-19 16:47:04 +01004796 if (len < 0) {
4797 PyErr_SetString(PyExc_ValueError, "num must be positive");
4798 return NULL;
4799 }
4800
Victor Stinner99c8b162011-05-24 12:05:19 +02004801 bytes = PyBytes_FromStringAndSize(NULL, len);
4802 if (bytes == NULL)
4803 return NULL;
4804 if (pseudo) {
4805 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4806 if (ok == 0 || ok == 1)
4807 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4808 }
4809 else {
4810 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4811 if (ok == 1)
4812 return bytes;
4813 }
4814 Py_DECREF(bytes);
4815
4816 err = ERR_get_error();
4817 errstr = ERR_reason_error_string(err);
4818 v = Py_BuildValue("(ks)", err, errstr);
4819 if (v != NULL) {
4820 PyErr_SetObject(PySSLErrorObject, v);
4821 Py_DECREF(v);
4822 }
4823 return NULL;
4824}
4825
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004826/*[clinic input]
4827_ssl.RAND_bytes
4828 n: int
4829 /
4830
4831Generate n cryptographically strong pseudo-random bytes.
4832[clinic start generated code]*/
4833
Victor Stinner99c8b162011-05-24 12:05:19 +02004834static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004835_ssl_RAND_bytes_impl(PyObject *module, int n)
4836/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004837{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004838 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004839}
4840
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004841/*[clinic input]
4842_ssl.RAND_pseudo_bytes
4843 n: int
4844 /
4845
4846Generate n pseudo-random bytes.
4847
4848Return a pair (bytes, is_cryptographic). is_cryptographic is True
4849if the bytes generated are cryptographically strong.
4850[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004851
4852static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004853_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4854/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004855{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004856 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004857}
4858
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004859/*[clinic input]
4860_ssl.RAND_status
4861
4862Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4863
4864It is necessary to seed the PRNG with RAND_add() on some platforms before
4865using the ssl() function.
4866[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004867
4868static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004869_ssl_RAND_status_impl(PyObject *module)
4870/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004871{
Christian Heimes217cfd12007-12-02 14:31:20 +00004872 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004873}
4874
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004875#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004876/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004877/*[clinic input]
4878_ssl.RAND_egd
4879 path: object(converter="PyUnicode_FSConverter")
4880 /
4881
4882Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4883
4884Returns number of bytes read. Raises SSLError if connection to EGD
4885fails or if it does not provide enough data to seed PRNG.
4886[clinic start generated code]*/
4887
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004888static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004889_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4890/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004891{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004892 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004893 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004894 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004895 PyErr_SetString(PySSLErrorObject,
4896 "EGD connection failed or EGD did not return "
4897 "enough data to seed the PRNG");
4898 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004899 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004900 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004901}
Christian Heimesa5d07652016-09-24 10:48:05 +02004902/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004903#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004904
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004905
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004906
4907/*[clinic input]
4908_ssl.get_default_verify_paths
4909
4910Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4911
4912The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4913[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004914
4915static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004916_ssl_get_default_verify_paths_impl(PyObject *module)
4917/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004918{
4919 PyObject *ofile_env = NULL;
4920 PyObject *ofile = NULL;
4921 PyObject *odir_env = NULL;
4922 PyObject *odir = NULL;
4923
Benjamin Petersond113c962015-07-18 10:59:13 -07004924#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004925 const char *tmp = (info); \
4926 target = NULL; \
4927 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4928 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4929 target = PyBytes_FromString(tmp); } \
4930 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004931 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004932
Benjamin Petersond113c962015-07-18 10:59:13 -07004933 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4934 CONVERT(X509_get_default_cert_file(), ofile);
4935 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4936 CONVERT(X509_get_default_cert_dir(), odir);
4937#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004938
Christian Heimes200bb1b2013-06-14 15:14:29 +02004939 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004940
4941 error:
4942 Py_XDECREF(ofile_env);
4943 Py_XDECREF(ofile);
4944 Py_XDECREF(odir_env);
4945 Py_XDECREF(odir);
4946 return NULL;
4947}
4948
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004949static PyObject*
4950asn1obj2py(ASN1_OBJECT *obj)
4951{
4952 int nid;
4953 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004954
4955 nid = OBJ_obj2nid(obj);
4956 if (nid == NID_undef) {
4957 PyErr_Format(PyExc_ValueError, "Unknown object");
4958 return NULL;
4959 }
4960 sn = OBJ_nid2sn(nid);
4961 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004962 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004963}
4964
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004965/*[clinic input]
4966_ssl.txt2obj
4967 txt: str
4968 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004969
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004970Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4971
4972By default objects are looked up by OID. With name=True short and
4973long name are also matched.
4974[clinic start generated code]*/
4975
4976static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004977_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4978/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004979{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004980 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004981 ASN1_OBJECT *obj;
4982
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004983 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4984 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004985 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004986 return NULL;
4987 }
4988 result = asn1obj2py(obj);
4989 ASN1_OBJECT_free(obj);
4990 return result;
4991}
4992
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004993/*[clinic input]
4994_ssl.nid2obj
4995 nid: int
4996 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004997
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004998Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4999[clinic start generated code]*/
5000
5001static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005002_ssl_nid2obj_impl(PyObject *module, int nid)
5003/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005004{
5005 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005006 ASN1_OBJECT *obj;
5007
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005008 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005009 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005010 return NULL;
5011 }
5012 obj = OBJ_nid2obj(nid);
5013 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01005014 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01005015 return NULL;
5016 }
5017 result = asn1obj2py(obj);
5018 ASN1_OBJECT_free(obj);
5019 return result;
5020}
5021
Christian Heimes46bebee2013-06-09 19:03:31 +02005022#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01005023
5024static PyObject*
5025certEncodingType(DWORD encodingType)
5026{
5027 static PyObject *x509_asn = NULL;
5028 static PyObject *pkcs_7_asn = NULL;
5029
5030 if (x509_asn == NULL) {
5031 x509_asn = PyUnicode_InternFromString("x509_asn");
5032 if (x509_asn == NULL)
5033 return NULL;
5034 }
5035 if (pkcs_7_asn == NULL) {
5036 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
5037 if (pkcs_7_asn == NULL)
5038 return NULL;
5039 }
5040 switch(encodingType) {
5041 case X509_ASN_ENCODING:
5042 Py_INCREF(x509_asn);
5043 return x509_asn;
5044 case PKCS_7_ASN_ENCODING:
5045 Py_INCREF(pkcs_7_asn);
5046 return pkcs_7_asn;
5047 default:
5048 return PyLong_FromLong(encodingType);
5049 }
5050}
5051
5052static PyObject*
5053parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
5054{
5055 CERT_ENHKEY_USAGE *usage;
5056 DWORD size, error, i;
5057 PyObject *retval;
5058
5059 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
5060 error = GetLastError();
5061 if (error == CRYPT_E_NOT_FOUND) {
5062 Py_RETURN_TRUE;
5063 }
5064 return PyErr_SetFromWindowsErr(error);
5065 }
5066
5067 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
5068 if (usage == NULL) {
5069 return PyErr_NoMemory();
5070 }
5071
5072 /* Now get the actual enhanced usage property */
5073 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
5074 PyMem_Free(usage);
5075 error = GetLastError();
5076 if (error == CRYPT_E_NOT_FOUND) {
5077 Py_RETURN_TRUE;
5078 }
5079 return PyErr_SetFromWindowsErr(error);
5080 }
5081 retval = PySet_New(NULL);
5082 if (retval == NULL) {
5083 goto error;
5084 }
5085 for (i = 0; i < usage->cUsageIdentifier; ++i) {
5086 if (usage->rgpszUsageIdentifier[i]) {
5087 PyObject *oid;
5088 int err;
5089 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
5090 if (oid == NULL) {
5091 Py_CLEAR(retval);
5092 goto error;
5093 }
5094 err = PySet_Add(retval, oid);
5095 Py_DECREF(oid);
5096 if (err == -1) {
5097 Py_CLEAR(retval);
5098 goto error;
5099 }
5100 }
5101 }
5102 error:
5103 PyMem_Free(usage);
5104 return retval;
5105}
5106
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005107/*[clinic input]
5108_ssl.enum_certificates
5109 store_name: str
5110
5111Retrieve certificates from Windows' cert store.
5112
5113store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5114more cert storages, too. The function returns a list of (bytes,
5115encoding_type, trust) tuples. The encoding_type flag can be interpreted
5116with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
5117a set of OIDs or the boolean True.
5118[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00005119
Christian Heimes46bebee2013-06-09 19:03:31 +02005120static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005121_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
5122/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02005123{
Christian Heimes46bebee2013-06-09 19:03:31 +02005124 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01005125 PCCERT_CONTEXT pCertCtx = NULL;
5126 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005127 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02005128
Christian Heimes44109d72013-11-22 01:51:30 +01005129 result = PyList_New(0);
5130 if (result == NULL) {
5131 return NULL;
5132 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005133 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5134 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5135 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005136 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005137 Py_DECREF(result);
5138 return PyErr_SetFromWindowsErr(GetLastError());
5139 }
5140
Christian Heimes44109d72013-11-22 01:51:30 +01005141 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
5142 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
5143 pCertCtx->cbCertEncoded);
5144 if (!cert) {
5145 Py_CLEAR(result);
5146 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005147 }
Christian Heimes44109d72013-11-22 01:51:30 +01005148 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
5149 Py_CLEAR(result);
5150 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005151 }
Christian Heimes44109d72013-11-22 01:51:30 +01005152 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
5153 if (keyusage == Py_True) {
5154 Py_DECREF(keyusage);
5155 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02005156 }
Christian Heimes44109d72013-11-22 01:51:30 +01005157 if (keyusage == NULL) {
5158 Py_CLEAR(result);
5159 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02005160 }
Christian Heimes44109d72013-11-22 01:51:30 +01005161 if ((tup = PyTuple_New(3)) == NULL) {
5162 Py_CLEAR(result);
5163 break;
5164 }
5165 PyTuple_SET_ITEM(tup, 0, cert);
5166 cert = NULL;
5167 PyTuple_SET_ITEM(tup, 1, enc);
5168 enc = NULL;
5169 PyTuple_SET_ITEM(tup, 2, keyusage);
5170 keyusage = NULL;
5171 if (PyList_Append(result, tup) < 0) {
5172 Py_CLEAR(result);
5173 break;
5174 }
5175 Py_CLEAR(tup);
5176 }
5177 if (pCertCtx) {
5178 /* loop ended with an error, need to clean up context manually */
5179 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005180 }
5181
5182 /* In error cases cert, enc and tup may not be NULL */
5183 Py_XDECREF(cert);
5184 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005185 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005186 Py_XDECREF(tup);
5187
5188 if (!CertCloseStore(hStore, 0)) {
5189 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005190 Py_XDECREF(result);
5191 return PyErr_SetFromWindowsErr(GetLastError());
5192 }
5193 return result;
5194}
5195
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005196/*[clinic input]
5197_ssl.enum_crls
5198 store_name: str
5199
5200Retrieve CRLs from Windows' cert store.
5201
5202store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5203more cert storages, too. The function returns a list of (bytes,
5204encoding_type) tuples. The encoding_type flag can be interpreted with
5205X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5206[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005207
5208static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005209_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5210/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005211{
Christian Heimes44109d72013-11-22 01:51:30 +01005212 HCERTSTORE hStore = NULL;
5213 PCCRL_CONTEXT pCrlCtx = NULL;
5214 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5215 PyObject *result = NULL;
5216
Christian Heimes44109d72013-11-22 01:51:30 +01005217 result = PyList_New(0);
5218 if (result == NULL) {
5219 return NULL;
5220 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005221 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5222 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5223 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005224 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005225 Py_DECREF(result);
5226 return PyErr_SetFromWindowsErr(GetLastError());
5227 }
Christian Heimes44109d72013-11-22 01:51:30 +01005228
5229 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5230 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5231 pCrlCtx->cbCrlEncoded);
5232 if (!crl) {
5233 Py_CLEAR(result);
5234 break;
5235 }
5236 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5237 Py_CLEAR(result);
5238 break;
5239 }
5240 if ((tup = PyTuple_New(2)) == NULL) {
5241 Py_CLEAR(result);
5242 break;
5243 }
5244 PyTuple_SET_ITEM(tup, 0, crl);
5245 crl = NULL;
5246 PyTuple_SET_ITEM(tup, 1, enc);
5247 enc = NULL;
5248
5249 if (PyList_Append(result, tup) < 0) {
5250 Py_CLEAR(result);
5251 break;
5252 }
5253 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005254 }
Christian Heimes44109d72013-11-22 01:51:30 +01005255 if (pCrlCtx) {
5256 /* loop ended with an error, need to clean up context manually */
5257 CertFreeCRLContext(pCrlCtx);
5258 }
5259
5260 /* In error cases cert, enc and tup may not be NULL */
5261 Py_XDECREF(crl);
5262 Py_XDECREF(enc);
5263 Py_XDECREF(tup);
5264
5265 if (!CertCloseStore(hStore, 0)) {
5266 /* This error case might shadow another exception.*/
5267 Py_XDECREF(result);
5268 return PyErr_SetFromWindowsErr(GetLastError());
5269 }
5270 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005271}
Christian Heimes44109d72013-11-22 01:51:30 +01005272
5273#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005274
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005275/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005276static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005277 _SSL__TEST_DECODE_CERT_METHODDEF
5278 _SSL_RAND_ADD_METHODDEF
5279 _SSL_RAND_BYTES_METHODDEF
5280 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5281 _SSL_RAND_EGD_METHODDEF
5282 _SSL_RAND_STATUS_METHODDEF
5283 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5284 _SSL_ENUM_CERTIFICATES_METHODDEF
5285 _SSL_ENUM_CRLS_METHODDEF
5286 _SSL_TXT2OBJ_METHODDEF
5287 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005288 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005289};
5290
5291
Christian Heimes598894f2016-09-05 23:19:05 +02005292#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005293
5294/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005295 * of the Python C thread library
5296 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5297 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005298
5299static PyThread_type_lock *_ssl_locks = NULL;
5300
Christian Heimes4d98ca92013-08-19 17:36:29 +02005301#if OPENSSL_VERSION_NUMBER >= 0x10000000
5302/* use new CRYPTO_THREADID API. */
5303static void
5304_ssl_threadid_callback(CRYPTO_THREADID *id)
5305{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005306 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005307}
5308#else
5309/* deprecated CRYPTO_set_id_callback() API. */
5310static unsigned long
5311_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005312 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005313}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005314#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005315
Bill Janssen6e027db2007-11-15 22:23:56 +00005316static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005317 (int mode, int n, const char *file, int line) {
5318 /* this function is needed to perform locking on shared data
5319 structures. (Note that OpenSSL uses a number of global data
5320 structures that will be implicitly shared whenever multiple
5321 threads use OpenSSL.) Multi-threaded applications will
5322 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005323
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005324 locking_function() must be able to handle up to
5325 CRYPTO_num_locks() different mutex locks. It sets the n-th
5326 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005328 file and line are the file number of the function setting the
5329 lock. They can be useful for debugging.
5330 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005332 if ((_ssl_locks == NULL) ||
5333 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5334 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005335
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005336 if (mode & CRYPTO_LOCK) {
5337 PyThread_acquire_lock(_ssl_locks[n], 1);
5338 } else {
5339 PyThread_release_lock(_ssl_locks[n]);
5340 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005341}
5342
5343static int _setup_ssl_threads(void) {
5344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005345 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005346
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005347 if (_ssl_locks == NULL) {
5348 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005349 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5350 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005351 if (_ssl_locks == NULL) {
5352 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005353 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005354 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005355 for (i = 0; i < _ssl_locks_count; i++) {
5356 _ssl_locks[i] = PyThread_allocate_lock();
5357 if (_ssl_locks[i] == NULL) {
5358 unsigned int j;
5359 for (j = 0; j < i; j++) {
5360 PyThread_free_lock(_ssl_locks[j]);
5361 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005362 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005363 return 0;
5364 }
5365 }
5366 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005367#if OPENSSL_VERSION_NUMBER >= 0x10000000
5368 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5369#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005370 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005371#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005372 }
5373 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005374}
5375
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005376#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005377
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005378PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005379"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005380for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005381
Martin v. Löwis1a214512008-06-11 05:26:20 +00005382
5383static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005384 PyModuleDef_HEAD_INIT,
5385 "_ssl",
5386 module_doc,
5387 -1,
5388 PySSL_methods,
5389 NULL,
5390 NULL,
5391 NULL,
5392 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005393};
5394
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005395
5396static void
5397parse_openssl_version(unsigned long libver,
5398 unsigned int *major, unsigned int *minor,
5399 unsigned int *fix, unsigned int *patch,
5400 unsigned int *status)
5401{
5402 *status = libver & 0xF;
5403 libver >>= 4;
5404 *patch = libver & 0xFF;
5405 libver >>= 8;
5406 *fix = libver & 0xFF;
5407 libver >>= 8;
5408 *minor = libver & 0xFF;
5409 libver >>= 8;
5410 *major = libver & 0xFF;
5411}
5412
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005413PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005414PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005415{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005416 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005417 unsigned long libver;
5418 unsigned int major, minor, fix, patch, status;
5419 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005420 struct py_ssl_error_code *errcode;
5421 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005422
Antoine Pitrou152efa22010-05-16 18:19:27 +00005423 if (PyType_Ready(&PySSLContext_Type) < 0)
5424 return NULL;
5425 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005426 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005427 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5428 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005429 if (PyType_Ready(&PySSLSession_Type) < 0)
5430 return NULL;
5431
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005432
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005433 m = PyModule_Create(&_sslmodule);
5434 if (m == NULL)
5435 return NULL;
5436 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005437
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005438 /* Load _socket module and its C API */
5439 socket_api = PySocketModule_ImportModuleAndAPI();
5440 if (!socket_api)
5441 return NULL;
5442 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005443
Christian Heimesc941e622017-09-05 15:47:11 +02005444#ifndef OPENSSL_VERSION_1_1
5445 /* Load all algorithms and initialize cpuid */
5446 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005447 /* Init OpenSSL */
5448 SSL_load_error_strings();
5449 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005450#endif
5451
Christian Heimes598894f2016-09-05 23:19:05 +02005452#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005453 /* note that this will start threading if not already started */
5454 if (!_setup_ssl_threads()) {
5455 return NULL;
5456 }
Christian Heimes598894f2016-09-05 23:19:05 +02005457#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5458 /* OpenSSL 1.1.0 builtin thread support is enabled */
5459 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005460#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005461
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005462 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005463 sslerror_type_slots[0].pfunc = PyExc_OSError;
5464 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005465 if (PySSLErrorObject == NULL)
5466 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005467
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005468 /* ssl.CertificateError used to be a subclass of ValueError */
5469 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5470 if (bases == NULL)
5471 return NULL;
5472 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5473 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5474 bases, NULL);
5475 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005476 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5477 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5478 PySSLErrorObject, NULL);
5479 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5480 "ssl.SSLWantReadError", SSLWantReadError_doc,
5481 PySSLErrorObject, NULL);
5482 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5483 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5484 PySSLErrorObject, NULL);
5485 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5486 "ssl.SSLSyscallError", SSLSyscallError_doc,
5487 PySSLErrorObject, NULL);
5488 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5489 "ssl.SSLEOFError", SSLEOFError_doc,
5490 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005491 if (PySSLCertVerificationErrorObject == NULL
5492 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005493 || PySSLWantReadErrorObject == NULL
5494 || PySSLWantWriteErrorObject == NULL
5495 || PySSLSyscallErrorObject == NULL
5496 || PySSLEOFErrorObject == NULL)
5497 return NULL;
5498 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005499 || PyDict_SetItemString(d, "SSLCertVerificationError",
5500 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005501 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5502 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5503 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5504 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5505 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005506 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005507 if (PyDict_SetItemString(d, "_SSLContext",
5508 (PyObject *)&PySSLContext_Type) != 0)
5509 return NULL;
5510 if (PyDict_SetItemString(d, "_SSLSocket",
5511 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005512 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005513 if (PyDict_SetItemString(d, "MemoryBIO",
5514 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5515 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005516 if (PyDict_SetItemString(d, "SSLSession",
5517 (PyObject *)&PySSLSession_Type) != 0)
5518 return NULL;
5519
Christian Heimes892d66e2018-01-29 14:10:18 +01005520 PyModule_AddStringConstant(m, "_DEFAULT_CIPHERS",
5521 PY_SSL_DEFAULT_CIPHER_STRING);
5522
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005523 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5524 PY_SSL_ERROR_ZERO_RETURN);
5525 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5526 PY_SSL_ERROR_WANT_READ);
5527 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5528 PY_SSL_ERROR_WANT_WRITE);
5529 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5530 PY_SSL_ERROR_WANT_X509_LOOKUP);
5531 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5532 PY_SSL_ERROR_SYSCALL);
5533 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5534 PY_SSL_ERROR_SSL);
5535 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5536 PY_SSL_ERROR_WANT_CONNECT);
5537 /* non ssl.h errorcodes */
5538 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5539 PY_SSL_ERROR_EOF);
5540 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5541 PY_SSL_ERROR_INVALID_ERROR_CODE);
5542 /* cert requirements */
5543 PyModule_AddIntConstant(m, "CERT_NONE",
5544 PY_SSL_CERT_NONE);
5545 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5546 PY_SSL_CERT_OPTIONAL);
5547 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5548 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005549 /* CRL verification for verification_flags */
5550 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5551 0);
5552 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5553 X509_V_FLAG_CRL_CHECK);
5554 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5555 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5556 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5557 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005558#ifdef X509_V_FLAG_TRUSTED_FIRST
5559 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5560 X509_V_FLAG_TRUSTED_FIRST);
5561#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005562
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005563 /* Alert Descriptions from ssl.h */
5564 /* note RESERVED constants no longer intended for use have been removed */
5565 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5566
5567#define ADD_AD_CONSTANT(s) \
5568 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5569 SSL_AD_##s)
5570
5571 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5572 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5573 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5574 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5575 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5576 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5577 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5578 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5579 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5580 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5581 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5582 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5583 ADD_AD_CONSTANT(UNKNOWN_CA);
5584 ADD_AD_CONSTANT(ACCESS_DENIED);
5585 ADD_AD_CONSTANT(DECODE_ERROR);
5586 ADD_AD_CONSTANT(DECRYPT_ERROR);
5587 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5588 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5589 ADD_AD_CONSTANT(INTERNAL_ERROR);
5590 ADD_AD_CONSTANT(USER_CANCELLED);
5591 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005592 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005593#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5594 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5595#endif
5596#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5597 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5598#endif
5599#ifdef SSL_AD_UNRECOGNIZED_NAME
5600 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5601#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005602#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5603 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5604#endif
5605#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5606 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5607#endif
5608#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5609 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5610#endif
5611
5612#undef ADD_AD_CONSTANT
5613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005614 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005615#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005616 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5617 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005618#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005619#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005620 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5621 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005622#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005623 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005624 PY_SSL_VERSION_TLS);
5625 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5626 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005627 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5628 PY_SSL_VERSION_TLS_CLIENT);
5629 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5630 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005631 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5632 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005633#if HAVE_TLSv1_2
5634 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5635 PY_SSL_VERSION_TLS1_1);
5636 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5637 PY_SSL_VERSION_TLS1_2);
5638#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005639
Antoine Pitroub5218772010-05-21 09:56:06 +00005640 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005641 PyModule_AddIntConstant(m, "OP_ALL",
5642 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005643 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5644 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5645 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005646#if HAVE_TLSv1_2
5647 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5648 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5649#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005650#ifdef SSL_OP_NO_TLSv1_3
5651 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5652#else
5653 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5654#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005655 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5656 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005657 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005658 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005659#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005660 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005661#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005662#ifdef SSL_OP_NO_COMPRESSION
5663 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5664 SSL_OP_NO_COMPRESSION);
5665#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005666
Christian Heimes61d478c2018-01-27 15:51:38 +01005667#ifdef X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT
5668 PyModule_AddIntConstant(m, "HOSTFLAG_ALWAYS_CHECK_SUBJECT",
5669 X509_CHECK_FLAG_ALWAYS_CHECK_SUBJECT);
5670#endif
5671#ifdef X509_CHECK_FLAG_NEVER_CHECK_SUBJECT
5672 PyModule_AddIntConstant(m, "HOSTFLAG_NEVER_CHECK_SUBJECT",
5673 X509_CHECK_FLAG_NEVER_CHECK_SUBJECT);
5674#endif
5675#ifdef X509_CHECK_FLAG_NO_WILDCARDS
5676 PyModule_AddIntConstant(m, "HOSTFLAG_NO_WILDCARDS",
5677 X509_CHECK_FLAG_NO_WILDCARDS);
5678#endif
5679#ifdef X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS
5680 PyModule_AddIntConstant(m, "HOSTFLAG_NO_PARTIAL_WILDCARDS",
5681 X509_CHECK_FLAG_NO_PARTIAL_WILDCARDS);
5682#endif
5683#ifdef X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS
5684 PyModule_AddIntConstant(m, "HOSTFLAG_MULTI_LABEL_WILDCARDS",
5685 X509_CHECK_FLAG_MULTI_LABEL_WILDCARDS);
5686#endif
5687#ifdef X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS
5688 PyModule_AddIntConstant(m, "HOSTFLAG_SINGLE_LABEL_SUBDOMAINS",
5689 X509_CHECK_FLAG_SINGLE_LABEL_SUBDOMAINS);
5690#endif
5691
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005692#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005693 r = Py_True;
5694#else
5695 r = Py_False;
5696#endif
5697 Py_INCREF(r);
5698 PyModule_AddObject(m, "HAS_SNI", r);
5699
Antoine Pitrou501da612011-12-21 09:27:41 +01005700#ifdef OPENSSL_NO_ECDH
5701 r = Py_False;
5702#else
5703 r = Py_True;
5704#endif
5705 Py_INCREF(r);
5706 PyModule_AddObject(m, "HAS_ECDH", r);
5707
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005708#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005709 r = Py_True;
5710#else
5711 r = Py_False;
5712#endif
5713 Py_INCREF(r);
5714 PyModule_AddObject(m, "HAS_NPN", r);
5715
Benjamin Petersoncca27322015-01-23 16:35:37 -05005716#ifdef HAVE_ALPN
5717 r = Py_True;
5718#else
5719 r = Py_False;
5720#endif
5721 Py_INCREF(r);
5722 PyModule_AddObject(m, "HAS_ALPN", r);
5723
Christian Heimescb5b68a2017-09-07 18:07:00 -07005724#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5725 r = Py_True;
5726#else
5727 r = Py_False;
5728#endif
5729 Py_INCREF(r);
5730 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5731
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005732 /* Mappings for error codes */
5733 err_codes_to_names = PyDict_New();
5734 err_names_to_codes = PyDict_New();
5735 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5736 return NULL;
5737 errcode = error_codes;
5738 while (errcode->mnemonic != NULL) {
5739 PyObject *mnemo, *key;
5740 mnemo = PyUnicode_FromString(errcode->mnemonic);
5741 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5742 if (mnemo == NULL || key == NULL)
5743 return NULL;
5744 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5745 return NULL;
5746 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5747 return NULL;
5748 Py_DECREF(key);
5749 Py_DECREF(mnemo);
5750 errcode++;
5751 }
5752 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5753 return NULL;
5754 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5755 return NULL;
5756
5757 lib_codes_to_names = PyDict_New();
5758 if (lib_codes_to_names == NULL)
5759 return NULL;
5760 libcode = library_codes;
5761 while (libcode->library != NULL) {
5762 PyObject *mnemo, *key;
5763 key = PyLong_FromLong(libcode->code);
5764 mnemo = PyUnicode_FromString(libcode->library);
5765 if (key == NULL || mnemo == NULL)
5766 return NULL;
5767 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5768 return NULL;
5769 Py_DECREF(key);
5770 Py_DECREF(mnemo);
5771 libcode++;
5772 }
5773 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5774 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005776 /* OpenSSL version */
5777 /* SSLeay() gives us the version of the library linked against,
5778 which could be different from the headers version.
5779 */
5780 libver = SSLeay();
5781 r = PyLong_FromUnsignedLong(libver);
5782 if (r == NULL)
5783 return NULL;
5784 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5785 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005786 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005787 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5788 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5789 return NULL;
5790 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5791 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5792 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005793
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005794 libver = OPENSSL_VERSION_NUMBER;
5795 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5796 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5797 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5798 return NULL;
5799
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005800 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005801}