blob: 5b27f2fda2c3797e3fc0a14dbb3b515f0bd83c8c [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
67/* SSL error object */
68static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070069static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010070static PyObject *PySSLZeroReturnErrorObject;
71static PyObject *PySSLWantReadErrorObject;
72static PyObject *PySSLWantWriteErrorObject;
73static PyObject *PySSLSyscallErrorObject;
74static PyObject *PySSLEOFErrorObject;
75
76/* Error mappings */
77static PyObject *err_codes_to_names;
78static PyObject *err_names_to_codes;
79static PyObject *lib_codes_to_names;
80
81struct py_ssl_error_code {
82 const char *mnemonic;
83 int library, reason;
84};
85struct py_ssl_library_code {
86 const char *library;
87 int code;
88};
89
Steve Dower68d663c2017-07-17 11:15:48 +020090#if defined(MS_WINDOWS) && defined(Py_DEBUG)
91/* Debug builds on Windows rely on getting errno directly from OpenSSL.
92 * However, because it uses a different CRT, we need to transfer the
93 * value of errno from OpenSSL into our debug CRT.
94 *
95 * Don't be fooled - this is horribly ugly code. The only reasonable
96 * alternative is to do both debug and release builds of OpenSSL, which
97 * requires much uglier code to transform their automatically generated
98 * makefile. This is the lesser of all the evils.
99 */
100
101static void _PySSLFixErrno(void) {
102 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
103 if (!ucrtbase) {
104 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
105 * have a catastrophic failure, but this function is not the
106 * place to raise it. */
107 return;
108 }
109
110 typedef int *(__stdcall *errno_func)(void);
111 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
112 if (ssl_errno) {
113 errno = *ssl_errno();
114 *ssl_errno() = 0;
115 } else {
116 errno = ENOTRECOVERABLE;
117 }
118}
119
120#undef _PySSL_FIX_ERRNO
121#define _PySSL_FIX_ERRNO _PySSLFixErrno()
122#endif
123
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100124/* Include generated data (error codes) */
125#include "_ssl_data.h"
126
Christian Heimes598894f2016-09-05 23:19:05 +0200127#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
128# define OPENSSL_VERSION_1_1 1
129#endif
130
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100131/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
132 http://www.openssl.org/news/changelog.html
133 */
134#if OPENSSL_VERSION_NUMBER >= 0x10001000L
135# define HAVE_TLSv1_2 1
136#else
137# define HAVE_TLSv1_2 0
138#endif
139
Christian Heimes470fba12013-11-28 15:12:15 +0100140/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100141 * This includes the SSL_set_SSL_CTX() function.
142 */
143#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
144# define HAVE_SNI 1
145#else
146# define HAVE_SNI 0
147#endif
148
Benjamin Petersond3308222015-09-27 00:09:02 -0700149#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500150# define HAVE_ALPN
151#endif
152
Victor Stinner524714e2016-07-22 17:43:59 +0200153#ifndef INVALID_SOCKET /* MS defines this */
154#define INVALID_SOCKET (-1)
155#endif
156
Christian Heimes598894f2016-09-05 23:19:05 +0200157#ifdef OPENSSL_VERSION_1_1
158/* OpenSSL 1.1.0+ */
159#ifndef OPENSSL_NO_SSL2
160#define OPENSSL_NO_SSL2
161#endif
162#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200163#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200164
165#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200166#define TLS_client_method SSLv23_client_method
167#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200168
169static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
170{
171 return ne->set;
172}
173
174#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200175/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200176static int COMP_get_type(const COMP_METHOD *meth)
177{
178 return meth->type;
179}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200180/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200181#endif
182
183static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
184{
185 return ctx->default_passwd_callback;
186}
187
188static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
189{
190 return ctx->default_passwd_callback_userdata;
191}
192
193static int X509_OBJECT_get_type(X509_OBJECT *x)
194{
195 return x->type;
196}
197
198static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
199{
200 return x->data.x509;
201}
202
203static int BIO_up_ref(BIO *b)
204{
205 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
206 return 1;
207}
208
209static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
210 return store->objs;
211}
212
213static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
214{
215 return store->param;
216}
Christian Heimes99a65702016-09-10 23:44:53 +0200217
218static int
219SSL_SESSION_has_ticket(const SSL_SESSION *s)
220{
221 return (s->tlsext_ticklen > 0) ? 1 : 0;
222}
223
224static unsigned long
225SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
226{
227 return s->tlsext_tick_lifetime_hint;
228}
229
Christian Heimes598894f2016-09-05 23:19:05 +0200230#endif /* OpenSSL < 1.1.0 or LibreSSL */
231
232
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000233enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 /* these mirror ssl.h */
235 PY_SSL_ERROR_NONE,
236 PY_SSL_ERROR_SSL,
237 PY_SSL_ERROR_WANT_READ,
238 PY_SSL_ERROR_WANT_WRITE,
239 PY_SSL_ERROR_WANT_X509_LOOKUP,
240 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
241 PY_SSL_ERROR_ZERO_RETURN,
242 PY_SSL_ERROR_WANT_CONNECT,
243 /* start of non ssl.h errorcodes */
244 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
245 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
246 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000247};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000248
Thomas Woutersed03b412007-08-28 21:37:11 +0000249enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000250 PY_SSL_CLIENT,
251 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000252};
253
254enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000255 PY_SSL_CERT_NONE,
256 PY_SSL_CERT_OPTIONAL,
257 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000258};
259
260enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000261 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200262 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200263 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100264#if HAVE_TLSv1_2
265 PY_SSL_VERSION_TLS1,
266 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200267 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100268#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200269 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000270#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200271 PY_SSL_VERSION_TLS_CLIENT=0x10,
272 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100273};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200274
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000275/* serves as a flag to see whether we've initialized the SSL thread support. */
276/* 0 means no, greater than 0 means yes */
277
278static unsigned int _ssl_locks_count = 0;
279
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280/* SSL socket object */
281
282#define X509_NAME_MAXLEN 256
283
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000284/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
285 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
286 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
287#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000288# define HAVE_SSL_CTX_CLEAR_OPTIONS
289#else
290# undef HAVE_SSL_CTX_CLEAR_OPTIONS
291#endif
292
Antoine Pitroud6494802011-07-21 01:11:30 +0200293/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
294 * older SSL, but let's be safe */
295#define PySSL_CB_MAXLEN 128
296
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100297
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000298typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000299 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000300 SSL_CTX *ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +0200301#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500302 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100303 int npn_protocols_len;
304#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500305#ifdef HAVE_ALPN
306 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300307 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500308#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100309#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200310 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100311#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100312 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000313} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000314
Antoine Pitrou152efa22010-05-16 18:19:27 +0000315typedef struct {
316 PyObject_HEAD
317 PyObject *Socket; /* weakref to socket on which we're layered */
318 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100319 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200320 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200321 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200322 PyObject *owner; /* Python level "owner" passed to servername callback */
323 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000324} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000325
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200326typedef struct {
327 PyObject_HEAD
328 BIO *bio;
329 int eof_written;
330} PySSLMemoryBIO;
331
Christian Heimes99a65702016-09-10 23:44:53 +0200332typedef struct {
333 PyObject_HEAD
334 SSL_SESSION *session;
335 PySSLContext *ctx;
336} PySSLSession;
337
Antoine Pitrou152efa22010-05-16 18:19:27 +0000338static PyTypeObject PySSLContext_Type;
339static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200340static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200341static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000342
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300343/*[clinic input]
344module _ssl
345class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
346class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
347class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200348class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300349[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200350/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300351
352#include "clinic/_ssl.c.h"
353
Victor Stinner14690702015-04-06 22:46:13 +0200354static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000355
Christian Heimes99a65702016-09-10 23:44:53 +0200356
Antoine Pitrou152efa22010-05-16 18:19:27 +0000357#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
358#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200359#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200360#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000361
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000362typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000363 SOCKET_IS_NONBLOCKING,
364 SOCKET_IS_BLOCKING,
365 SOCKET_HAS_TIMED_OUT,
366 SOCKET_HAS_BEEN_CLOSED,
367 SOCKET_TOO_LARGE_FOR_SELECT,
368 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000369} timeout_state;
370
Thomas Woutersed03b412007-08-28 21:37:11 +0000371/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000372#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200373#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000374
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200375/* Get the socket from a PySSLSocket, if it has one */
376#define GET_SOCKET(obj) ((obj)->Socket ? \
377 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200378
Victor Stinner14690702015-04-06 22:46:13 +0200379/* If sock is NULL, use a timeout of 0 second */
380#define GET_SOCKET_TIMEOUT(sock) \
381 ((sock != NULL) ? (sock)->sock_timeout : 0)
382
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200383/*
384 * SSL errors.
385 */
386
387PyDoc_STRVAR(SSLError_doc,
388"An error occurred in the SSL implementation.");
389
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700390PyDoc_STRVAR(SSLCertVerificationError_doc,
391"A certificate could not be verified.");
392
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200393PyDoc_STRVAR(SSLZeroReturnError_doc,
394"SSL/TLS session closed cleanly.");
395
396PyDoc_STRVAR(SSLWantReadError_doc,
397"Non-blocking SSL socket needs to read more data\n"
398"before the requested operation can be completed.");
399
400PyDoc_STRVAR(SSLWantWriteError_doc,
401"Non-blocking SSL socket needs to write more data\n"
402"before the requested operation can be completed.");
403
404PyDoc_STRVAR(SSLSyscallError_doc,
405"System error when attempting SSL operation.");
406
407PyDoc_STRVAR(SSLEOFError_doc,
408"SSL/TLS connection terminated abruptly.");
409
410static PyObject *
411SSLError_str(PyOSErrorObject *self)
412{
413 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
414 Py_INCREF(self->strerror);
415 return self->strerror;
416 }
417 else
418 return PyObject_Str(self->args);
419}
420
421static PyType_Slot sslerror_type_slots[] = {
422 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
423 {Py_tp_doc, SSLError_doc},
424 {Py_tp_str, SSLError_str},
425 {0, 0},
426};
427
428static PyType_Spec sslerror_type_spec = {
429 "ssl.SSLError",
430 sizeof(PyOSErrorObject),
431 0,
432 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
433 sslerror_type_slots
434};
435
436static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700437fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
438 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200439{
440 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700441 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200442 PyObject *init_value, *msg, *key;
443 _Py_IDENTIFIER(reason);
444 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700445 _Py_IDENTIFIER(verify_message);
446 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200447
448 if (errcode != 0) {
449 int lib, reason;
450
451 lib = ERR_GET_LIB(errcode);
452 reason = ERR_GET_REASON(errcode);
453 key = Py_BuildValue("ii", lib, reason);
454 if (key == NULL)
455 goto fail;
456 reason_obj = PyDict_GetItem(err_codes_to_names, key);
457 Py_DECREF(key);
458 if (reason_obj == NULL) {
459 /* XXX if reason < 100, it might reflect a library number (!!) */
460 PyErr_Clear();
461 }
462 key = PyLong_FromLong(lib);
463 if (key == NULL)
464 goto fail;
465 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
466 Py_DECREF(key);
467 if (lib_obj == NULL) {
468 PyErr_Clear();
469 }
470 if (errstr == NULL)
471 errstr = ERR_reason_error_string(errcode);
472 }
473 if (errstr == NULL)
474 errstr = "unknown error";
475
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700476 /* verify code for cert validation error */
477 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
478 const char *verify_str = NULL;
479 long verify_code;
480
481 verify_code = SSL_get_verify_result(sslsock->ssl);
482 verify_code_obj = PyLong_FromLong(verify_code);
483 if (verify_code_obj == NULL) {
484 goto fail;
485 }
486
487 switch (verify_code) {
488 case X509_V_ERR_HOSTNAME_MISMATCH:
489 verify_obj = PyUnicode_FromFormat(
490 "Hostname mismatch, certificate is not valid for '%S'.",
491 sslsock->server_hostname
492 );
493 break;
494 case X509_V_ERR_IP_ADDRESS_MISMATCH:
495 verify_obj = PyUnicode_FromFormat(
496 "IP address mismatch, certificate is not valid for '%S'.",
497 sslsock->server_hostname
498 );
499 break;
500 default:
501 verify_str = X509_verify_cert_error_string(verify_code);
502 if (verify_str != NULL) {
503 verify_obj = PyUnicode_FromString(verify_str);
504 } else {
505 verify_obj = Py_None;
506 Py_INCREF(verify_obj);
507 }
508 break;
509 }
510 if (verify_obj == NULL) {
511 goto fail;
512 }
513 }
514
515 if (verify_obj && reason_obj && lib_obj)
516 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
517 lib_obj, reason_obj, errstr, verify_obj,
518 lineno);
519 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200520 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
521 lib_obj, reason_obj, errstr, lineno);
522 else if (lib_obj)
523 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
524 lib_obj, errstr, lineno);
525 else
526 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527 if (msg == NULL)
528 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100529
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200530 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100531 if (init_value == NULL)
532 goto fail;
533
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200534 err_value = PyObject_CallObject(type, init_value);
535 Py_DECREF(init_value);
536 if (err_value == NULL)
537 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100538
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200539 if (reason_obj == NULL)
540 reason_obj = Py_None;
541 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
542 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700543
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200544 if (lib_obj == NULL)
545 lib_obj = Py_None;
546 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
547 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700548
549 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
550 /* Only set verify code / message for SSLCertVerificationError */
551 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
552 verify_code_obj))
553 goto fail;
554 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
555 goto fail;
556 }
557
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200558 PyErr_SetObject(type, err_value);
559fail:
560 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700561 Py_XDECREF(verify_code_obj);
562 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200563}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000564
565static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700566PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000567{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200568 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000570 int err;
571 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200572 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000573
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200575 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000576
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700577 if (sslsock->ssl != NULL) {
578 err = SSL_get_error(sslsock->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000579
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000580 switch (err) {
581 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200582 errstr = "TLS/SSL connection has been closed (EOF)";
583 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000584 p = PY_SSL_ERROR_ZERO_RETURN;
585 break;
586 case SSL_ERROR_WANT_READ:
587 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200588 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 p = PY_SSL_ERROR_WANT_READ;
590 break;
591 case SSL_ERROR_WANT_WRITE:
592 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200593 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 errstr = "The operation did not complete (write)";
595 break;
596 case SSL_ERROR_WANT_X509_LOOKUP:
597 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000598 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 break;
600 case SSL_ERROR_WANT_CONNECT:
601 p = PY_SSL_ERROR_WANT_CONNECT;
602 errstr = "The operation did not complete (connect)";
603 break;
604 case SSL_ERROR_SYSCALL:
605 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700607 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000608 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000609 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200610 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000611 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200612 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000613 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000614 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000615 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200616 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000617 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200618 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000620 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200621 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000622 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000623 }
624 } else {
625 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 }
627 break;
628 }
629 case SSL_ERROR_SSL:
630 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700632 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200633 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000634 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700635 }
636 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
637 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
638 type = PySSLCertVerificationErrorObject;
639 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 break;
641 }
642 default:
643 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
644 errstr = "Invalid error code";
645 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000646 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700647 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000648 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000650}
651
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200653_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000654
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200655 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200657 else
658 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700659 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000660 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000662}
663
Antoine Pitrou152efa22010-05-16 18:19:27 +0000664static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100665newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000666 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200667 char *server_hostname,
668 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000669{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000670 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100671 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200672 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000673
Antoine Pitrou152efa22010-05-16 18:19:27 +0000674 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000675 if (self == NULL)
676 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100680 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700681 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200682 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200683 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700684 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200685 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700686 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
687 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200688 if (hostname == NULL) {
689 Py_DECREF(self);
690 return NULL;
691 }
692 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700693 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200694
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000695 /* Make sure the SSL error state is initialized */
696 (void) ERR_get_state();
697 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000698
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000699 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000700 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200702 SSL_set_app_data(self->ssl, self);
703 if (sock) {
704 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
705 } else {
706 /* BIOs are reference counted and SSL_set_bio borrows our reference.
707 * To prevent a double free in memory_bio_dealloc() we need to take an
708 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200709 BIO_up_ref(inbio->bio);
710 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200711 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
712 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200713 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000714#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200715 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000716#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200717 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000718
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100719#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000720 if (server_hostname != NULL)
721 SSL_set_tlsext_host_name(self->ssl, server_hostname);
722#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000723 /* If the socket is in non-blocking mode or timeout mode, set the BIO
724 * to non-blocking mode (blocking is the default)
725 */
Victor Stinnere2452312015-03-28 03:00:46 +0100726 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000727 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
728 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
729 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000730
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000731 PySSL_BEGIN_ALLOW_THREADS
732 if (socket_type == PY_SSL_CLIENT)
733 SSL_set_connect_state(self->ssl);
734 else
735 SSL_set_accept_state(self->ssl);
736 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000737
Antoine Pitroud6494802011-07-21 01:11:30 +0200738 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200739 if (sock != NULL) {
740 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
741 if (self->Socket == NULL) {
742 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200743 return NULL;
744 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100745 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000747}
748
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000749/* SSL object methods */
750
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300751/*[clinic input]
752_ssl._SSLSocket.do_handshake
753[clinic start generated code]*/
754
755static PyObject *
756_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
757/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000758{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000759 int ret;
760 int err;
761 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200762 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200763 _PyTime_t timeout, deadline = 0;
764 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000765
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200766 if (sock) {
767 if (((PyObject*)sock) == Py_None) {
768 _setSSLError("Underlying socket connection gone",
769 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
770 return NULL;
771 }
772 Py_INCREF(sock);
773
774 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100775 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200776 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
777 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000778 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000779
Victor Stinner14690702015-04-06 22:46:13 +0200780 timeout = GET_SOCKET_TIMEOUT(sock);
781 has_timeout = (timeout > 0);
782 if (has_timeout)
783 deadline = _PyTime_GetMonotonicClock() + timeout;
784
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000785 /* Actually negotiate SSL connection */
786 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000787 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000788 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000789 ret = SSL_do_handshake(self->ssl);
790 err = SSL_get_error(self->ssl, ret);
791 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200792
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000793 if (PyErr_CheckSignals())
794 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200795
Victor Stinner14690702015-04-06 22:46:13 +0200796 if (has_timeout)
797 timeout = deadline - _PyTime_GetMonotonicClock();
798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200800 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200802 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000803 } else {
804 sockstate = SOCKET_OPERATION_OK;
805 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200806
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000807 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000808 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000809 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000810 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000811 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
812 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000813 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000814 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000815 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
816 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000817 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000818 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000819 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
820 break;
821 }
822 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200823 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 if (ret < 1)
825 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000826
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200827 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000828
829error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200830 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000831 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000832}
833
Thomas Woutersed03b412007-08-28 21:37:11 +0000834static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300835_asn1obj2py(const ASN1_OBJECT *name, int no_name)
836{
837 char buf[X509_NAME_MAXLEN];
838 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000839 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300840 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000841
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300842 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000843 if (buflen < 0) {
844 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300845 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300847 /* initial buffer is too small for oid + terminating null byte */
848 if (buflen > X509_NAME_MAXLEN - 1) {
849 /* make OBJ_obj2txt() calculate the required buflen */
850 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
851 /* allocate len + 1 for terminating NULL byte */
852 namebuf = PyMem_Malloc(buflen + 1);
853 if (namebuf == NULL) {
854 PyErr_NoMemory();
855 return NULL;
856 }
857 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
858 if (buflen < 0) {
859 _setSSLError(NULL, 0, __FILE__, __LINE__);
860 goto done;
861 }
862 }
863 if (!buflen && no_name) {
864 Py_INCREF(Py_None);
865 name_obj = Py_None;
866 }
867 else {
868 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
869 }
870
871 done:
872 if (buf != namebuf) {
873 PyMem_Free(namebuf);
874 }
875 return name_obj;
876}
877
878static PyObject *
879_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
880{
881 Py_ssize_t buflen;
882 unsigned char *valuebuf = NULL;
883 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
886 if (buflen < 0) {
887 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300888 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300890 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000891 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000893}
894
895static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000896_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000897{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000898 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
899 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
900 PyObject *rdnt;
901 PyObject *attr = NULL; /* tuple to hold an attribute */
902 int entry_count = X509_NAME_entry_count(xname);
903 X509_NAME_ENTRY *entry;
904 ASN1_OBJECT *name;
905 ASN1_STRING *value;
906 int index_counter;
907 int rdn_level = -1;
908 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000909
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000910 dn = PyList_New(0);
911 if (dn == NULL)
912 return NULL;
913 /* now create another tuple to hold the top-level RDN */
914 rdn = PyList_New(0);
915 if (rdn == NULL)
916 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000917
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000918 for (index_counter = 0;
919 index_counter < entry_count;
920 index_counter++)
921 {
922 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 /* check to see if we've gotten to a new RDN */
925 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200926 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 /* yes, new RDN */
928 /* add old RDN to DN */
929 rdnt = PyList_AsTuple(rdn);
930 Py_DECREF(rdn);
931 if (rdnt == NULL)
932 goto fail0;
933 retcode = PyList_Append(dn, rdnt);
934 Py_DECREF(rdnt);
935 if (retcode < 0)
936 goto fail0;
937 /* create new RDN */
938 rdn = PyList_New(0);
939 if (rdn == NULL)
940 goto fail0;
941 }
942 }
Christian Heimes598894f2016-09-05 23:19:05 +0200943 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000944
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 /* now add this attribute to the current RDN */
946 name = X509_NAME_ENTRY_get_object(entry);
947 value = X509_NAME_ENTRY_get_data(entry);
948 attr = _create_tuple_for_attribute(name, value);
949 /*
950 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
951 entry->set,
952 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
953 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
954 */
955 if (attr == NULL)
956 goto fail1;
957 retcode = PyList_Append(rdn, attr);
958 Py_DECREF(attr);
959 if (retcode < 0)
960 goto fail1;
961 }
962 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100963 if (rdn != NULL) {
964 if (PyList_GET_SIZE(rdn) > 0) {
965 rdnt = PyList_AsTuple(rdn);
966 Py_DECREF(rdn);
967 if (rdnt == NULL)
968 goto fail0;
969 retcode = PyList_Append(dn, rdnt);
970 Py_DECREF(rdnt);
971 if (retcode < 0)
972 goto fail0;
973 }
974 else {
975 Py_DECREF(rdn);
976 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000978
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000979 /* convert list to tuple */
980 rdnt = PyList_AsTuple(dn);
981 Py_DECREF(dn);
982 if (rdnt == NULL)
983 return NULL;
984 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000985
986 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000987 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000988
989 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000990 Py_XDECREF(dn);
991 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000992}
993
994static PyObject *
995_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000996
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000997 /* this code follows the procedure outlined in
998 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
999 function to extract the STACK_OF(GENERAL_NAME),
1000 then iterates through the stack to add the
1001 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001002
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001003 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001004 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001005 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001006 GENERAL_NAMES *names = NULL;
1007 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001008 BIO *biobuf = NULL;
1009 char buf[2048];
1010 char *vptr;
1011 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001012
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 if (certificate == NULL)
1014 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 /* get a memory buffer */
1017 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001018
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001019 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1020 certificate, NID_subject_alt_name, NULL, NULL);
1021 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001022 if (peer_alt_names == Py_None) {
1023 peer_alt_names = PyList_New(0);
1024 if (peer_alt_names == NULL)
1025 goto fail;
1026 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001027
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001028 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001030 int gntype;
1031 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001034 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001035 switch (gntype) {
1036 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001037 /* we special-case DirName as a tuple of
1038 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001039
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001040 t = PyTuple_New(2);
1041 if (t == NULL) {
1042 goto fail;
1043 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 v = PyUnicode_FromString("DirName");
1046 if (v == NULL) {
1047 Py_DECREF(t);
1048 goto fail;
1049 }
1050 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 v = _create_tuple_for_X509_NAME (name->d.dirn);
1053 if (v == NULL) {
1054 Py_DECREF(t);
1055 goto fail;
1056 }
1057 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001058 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001059
Christian Heimes824f7f32013-08-17 00:54:47 +02001060 case GEN_EMAIL:
1061 case GEN_DNS:
1062 case GEN_URI:
1063 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1064 correctly, CVE-2013-4238 */
1065 t = PyTuple_New(2);
1066 if (t == NULL)
1067 goto fail;
1068 switch (gntype) {
1069 case GEN_EMAIL:
1070 v = PyUnicode_FromString("email");
1071 as = name->d.rfc822Name;
1072 break;
1073 case GEN_DNS:
1074 v = PyUnicode_FromString("DNS");
1075 as = name->d.dNSName;
1076 break;
1077 case GEN_URI:
1078 v = PyUnicode_FromString("URI");
1079 as = name->d.uniformResourceIdentifier;
1080 break;
1081 }
1082 if (v == NULL) {
1083 Py_DECREF(t);
1084 goto fail;
1085 }
1086 PyTuple_SET_ITEM(t, 0, v);
1087 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1088 ASN1_STRING_length(as));
1089 if (v == NULL) {
1090 Py_DECREF(t);
1091 goto fail;
1092 }
1093 PyTuple_SET_ITEM(t, 1, v);
1094 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001095
Christian Heimes1c03abd2016-09-06 23:25:35 +02001096 case GEN_RID:
1097 t = PyTuple_New(2);
1098 if (t == NULL)
1099 goto fail;
1100
1101 v = PyUnicode_FromString("Registered ID");
1102 if (v == NULL) {
1103 Py_DECREF(t);
1104 goto fail;
1105 }
1106 PyTuple_SET_ITEM(t, 0, v);
1107
1108 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1109 if (len < 0) {
1110 Py_DECREF(t);
1111 _setSSLError(NULL, 0, __FILE__, __LINE__);
1112 goto fail;
1113 } else if (len >= (int)sizeof(buf)) {
1114 v = PyUnicode_FromString("<INVALID>");
1115 } else {
1116 v = PyUnicode_FromStringAndSize(buf, len);
1117 }
1118 if (v == NULL) {
1119 Py_DECREF(t);
1120 goto fail;
1121 }
1122 PyTuple_SET_ITEM(t, 1, v);
1123 break;
1124
Christian Heimes824f7f32013-08-17 00:54:47 +02001125 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001126 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001127 switch (gntype) {
1128 /* check for new general name type */
1129 case GEN_OTHERNAME:
1130 case GEN_X400:
1131 case GEN_EDIPARTY:
1132 case GEN_IPADD:
1133 case GEN_RID:
1134 break;
1135 default:
1136 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1137 "Unknown general name type %d",
1138 gntype) == -1) {
1139 goto fail;
1140 }
1141 break;
1142 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001143 (void) BIO_reset(biobuf);
1144 GENERAL_NAME_print(biobuf, name);
1145 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1146 if (len < 0) {
1147 _setSSLError(NULL, 0, __FILE__, __LINE__);
1148 goto fail;
1149 }
1150 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001151 if (vptr == NULL) {
1152 PyErr_Format(PyExc_ValueError,
1153 "Invalid value %.200s",
1154 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001156 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001157 t = PyTuple_New(2);
1158 if (t == NULL)
1159 goto fail;
1160 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1161 if (v == NULL) {
1162 Py_DECREF(t);
1163 goto fail;
1164 }
1165 PyTuple_SET_ITEM(t, 0, v);
1166 v = PyUnicode_FromStringAndSize((vptr + 1),
1167 (len - (vptr - buf + 1)));
1168 if (v == NULL) {
1169 Py_DECREF(t);
1170 goto fail;
1171 }
1172 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001173 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001174 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001175
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001176 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001178 if (PyList_Append(peer_alt_names, t) < 0) {
1179 Py_DECREF(t);
1180 goto fail;
1181 }
1182 Py_DECREF(t);
1183 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001184 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001185 }
1186 BIO_free(biobuf);
1187 if (peer_alt_names != Py_None) {
1188 v = PyList_AsTuple(peer_alt_names);
1189 Py_DECREF(peer_alt_names);
1190 return v;
1191 } else {
1192 return peer_alt_names;
1193 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001194
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001195
1196 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001197 if (biobuf != NULL)
1198 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001199
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001200 if (peer_alt_names != Py_None) {
1201 Py_XDECREF(peer_alt_names);
1202 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001204 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001205}
1206
1207static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001208_get_aia_uri(X509 *certificate, int nid) {
1209 PyObject *lst = NULL, *ostr = NULL;
1210 int i, result;
1211 AUTHORITY_INFO_ACCESS *info;
1212
1213 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001214 if (info == NULL)
1215 return Py_None;
1216 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1217 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001218 return Py_None;
1219 }
1220
1221 if ((lst = PyList_New(0)) == NULL) {
1222 goto fail;
1223 }
1224
1225 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1226 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1227 ASN1_IA5STRING *uri;
1228
1229 if ((OBJ_obj2nid(ad->method) != nid) ||
1230 (ad->location->type != GEN_URI)) {
1231 continue;
1232 }
1233 uri = ad->location->d.uniformResourceIdentifier;
1234 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1235 uri->length);
1236 if (ostr == NULL) {
1237 goto fail;
1238 }
1239 result = PyList_Append(lst, ostr);
1240 Py_DECREF(ostr);
1241 if (result < 0) {
1242 goto fail;
1243 }
1244 }
1245 AUTHORITY_INFO_ACCESS_free(info);
1246
1247 /* convert to tuple or None */
1248 if (PyList_Size(lst) == 0) {
1249 Py_DECREF(lst);
1250 return Py_None;
1251 } else {
1252 PyObject *tup;
1253 tup = PyList_AsTuple(lst);
1254 Py_DECREF(lst);
1255 return tup;
1256 }
1257
1258 fail:
1259 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001260 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001261 return NULL;
1262}
1263
1264static PyObject *
1265_get_crl_dp(X509 *certificate) {
1266 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001267 int i, j;
1268 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001269
Christian Heimes598894f2016-09-05 23:19:05 +02001270 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001271
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001272 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001273 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001274
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001275 lst = PyList_New(0);
1276 if (lst == NULL)
1277 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001278
1279 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1280 DIST_POINT *dp;
1281 STACK_OF(GENERAL_NAME) *gns;
1282
1283 dp = sk_DIST_POINT_value(dps, i);
1284 gns = dp->distpoint->name.fullname;
1285
1286 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1287 GENERAL_NAME *gn;
1288 ASN1_IA5STRING *uri;
1289 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001290 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001291
1292 gn = sk_GENERAL_NAME_value(gns, j);
1293 if (gn->type != GEN_URI) {
1294 continue;
1295 }
1296 uri = gn->d.uniformResourceIdentifier;
1297 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1298 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001299 if (ouri == NULL)
1300 goto done;
1301
1302 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001303 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001304 if (err < 0)
1305 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001306 }
1307 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001308
1309 /* Convert to tuple. */
1310 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1311
1312 done:
1313 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001314 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001315 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001316}
1317
1318static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001319_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001320
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001321 PyObject *retval = NULL;
1322 BIO *biobuf = NULL;
1323 PyObject *peer;
1324 PyObject *peer_alt_names = NULL;
1325 PyObject *issuer;
1326 PyObject *version;
1327 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001328 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001329 ASN1_INTEGER *serialNumber;
1330 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001331 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001332 ASN1_TIME *notBefore, *notAfter;
1333 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001334
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001335 retval = PyDict_New();
1336 if (retval == NULL)
1337 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001338
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001339 peer = _create_tuple_for_X509_NAME(
1340 X509_get_subject_name(certificate));
1341 if (peer == NULL)
1342 goto fail0;
1343 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1344 Py_DECREF(peer);
1345 goto fail0;
1346 }
1347 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001348
Antoine Pitroufb046912010-11-09 20:21:19 +00001349 issuer = _create_tuple_for_X509_NAME(
1350 X509_get_issuer_name(certificate));
1351 if (issuer == NULL)
1352 goto fail0;
1353 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001354 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001355 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001356 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001357 Py_DECREF(issuer);
1358
1359 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001360 if (version == NULL)
1361 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001362 if (PyDict_SetItemString(retval, "version", version) < 0) {
1363 Py_DECREF(version);
1364 goto fail0;
1365 }
1366 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001367
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 /* get a memory buffer */
1369 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001370
Antoine Pitroufb046912010-11-09 20:21:19 +00001371 (void) BIO_reset(biobuf);
1372 serialNumber = X509_get_serialNumber(certificate);
1373 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1374 i2a_ASN1_INTEGER(biobuf, serialNumber);
1375 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1376 if (len < 0) {
1377 _setSSLError(NULL, 0, __FILE__, __LINE__);
1378 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001379 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001380 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1381 if (sn_obj == NULL)
1382 goto fail1;
1383 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1384 Py_DECREF(sn_obj);
1385 goto fail1;
1386 }
1387 Py_DECREF(sn_obj);
1388
1389 (void) BIO_reset(biobuf);
1390 notBefore = X509_get_notBefore(certificate);
1391 ASN1_TIME_print(biobuf, notBefore);
1392 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1393 if (len < 0) {
1394 _setSSLError(NULL, 0, __FILE__, __LINE__);
1395 goto fail1;
1396 }
1397 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1398 if (pnotBefore == NULL)
1399 goto fail1;
1400 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1401 Py_DECREF(pnotBefore);
1402 goto fail1;
1403 }
1404 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001405
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001406 (void) BIO_reset(biobuf);
1407 notAfter = X509_get_notAfter(certificate);
1408 ASN1_TIME_print(biobuf, notAfter);
1409 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1410 if (len < 0) {
1411 _setSSLError(NULL, 0, __FILE__, __LINE__);
1412 goto fail1;
1413 }
1414 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1415 if (pnotAfter == NULL)
1416 goto fail1;
1417 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1418 Py_DECREF(pnotAfter);
1419 goto fail1;
1420 }
1421 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001422
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001423 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001424
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 peer_alt_names = _get_peer_alt_names(certificate);
1426 if (peer_alt_names == NULL)
1427 goto fail1;
1428 else if (peer_alt_names != Py_None) {
1429 if (PyDict_SetItemString(retval, "subjectAltName",
1430 peer_alt_names) < 0) {
1431 Py_DECREF(peer_alt_names);
1432 goto fail1;
1433 }
1434 Py_DECREF(peer_alt_names);
1435 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001436
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001437 /* Authority Information Access: OCSP URIs */
1438 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1439 if (obj == NULL) {
1440 goto fail1;
1441 } else if (obj != Py_None) {
1442 result = PyDict_SetItemString(retval, "OCSP", obj);
1443 Py_DECREF(obj);
1444 if (result < 0) {
1445 goto fail1;
1446 }
1447 }
1448
1449 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1450 if (obj == NULL) {
1451 goto fail1;
1452 } else if (obj != Py_None) {
1453 result = PyDict_SetItemString(retval, "caIssuers", obj);
1454 Py_DECREF(obj);
1455 if (result < 0) {
1456 goto fail1;
1457 }
1458 }
1459
1460 /* CDP (CRL distribution points) */
1461 obj = _get_crl_dp(certificate);
1462 if (obj == NULL) {
1463 goto fail1;
1464 } else if (obj != Py_None) {
1465 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1466 Py_DECREF(obj);
1467 if (result < 0) {
1468 goto fail1;
1469 }
1470 }
1471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 BIO_free(biobuf);
1473 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001474
1475 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001476 if (biobuf != NULL)
1477 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001478 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 Py_XDECREF(retval);
1480 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001481}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001482
Christian Heimes9a5395a2013-06-17 15:44:12 +02001483static PyObject *
1484_certificate_to_der(X509 *certificate)
1485{
1486 unsigned char *bytes_buf = NULL;
1487 int len;
1488 PyObject *retval;
1489
1490 bytes_buf = NULL;
1491 len = i2d_X509(certificate, &bytes_buf);
1492 if (len < 0) {
1493 _setSSLError(NULL, 0, __FILE__, __LINE__);
1494 return NULL;
1495 }
1496 /* this is actually an immutable bytes sequence */
1497 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1498 OPENSSL_free(bytes_buf);
1499 return retval;
1500}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001501
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001502/*[clinic input]
1503_ssl._test_decode_cert
1504 path: object(converter="PyUnicode_FSConverter")
1505 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001507[clinic start generated code]*/
1508
1509static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001510_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1511/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001512{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001513 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 X509 *x=NULL;
1515 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1518 PyErr_SetString(PySSLErrorObject,
1519 "Can't malloc memory to read file");
1520 goto fail0;
1521 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001522
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001523 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 PyErr_SetString(PySSLErrorObject,
1525 "Can't open file");
1526 goto fail0;
1527 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1530 if (x == NULL) {
1531 PyErr_SetString(PySSLErrorObject,
1532 "Error decoding PEM-encoded file");
1533 goto fail0;
1534 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001535
Antoine Pitroufb046912010-11-09 20:21:19 +00001536 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001537 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001538
1539 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001540 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 if (cert != NULL) BIO_free(cert);
1542 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543}
1544
1545
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001546/*[clinic input]
1547_ssl._SSLSocket.peer_certificate
1548 der as binary_mode: bool = False
1549 /
1550
1551Returns the certificate for the peer.
1552
1553If no certificate was provided, returns None. If a certificate was
1554provided, but not validated, returns an empty dictionary. Otherwise
1555returns a dict containing information about the peer certificate.
1556
1557If the optional argument is True, returns a DER-encoded copy of the
1558peer certificate, or None if no certificate was provided. This will
1559return the certificate even if it wasn't validated.
1560[clinic start generated code]*/
1561
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001562static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001563_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1564/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001565{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001567 X509 *peer_cert;
1568 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001569
Christian Heimes66dc33b2017-05-23 16:02:02 -07001570 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001571 PyErr_SetString(PyExc_ValueError,
1572 "handshake not done yet");
1573 return NULL;
1574 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001575 peer_cert = SSL_get_peer_certificate(self->ssl);
1576 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001577 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001578
Antoine Pitrou721738f2012-08-15 23:20:39 +02001579 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001581 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001583 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001584 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001585 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001587 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001588 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001589 X509_free(peer_cert);
1590 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001591}
1592
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001593static PyObject *
1594cipher_to_tuple(const SSL_CIPHER *cipher)
1595{
1596 const char *cipher_name, *cipher_protocol;
1597 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001598 if (retval == NULL)
1599 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001600
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001601 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001602 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001603 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001604 PyTuple_SET_ITEM(retval, 0, Py_None);
1605 } else {
1606 v = PyUnicode_FromString(cipher_name);
1607 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001608 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 PyTuple_SET_ITEM(retval, 0, v);
1610 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001611
1612 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001613 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001614 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001615 PyTuple_SET_ITEM(retval, 1, Py_None);
1616 } else {
1617 v = PyUnicode_FromString(cipher_protocol);
1618 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001619 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 PyTuple_SET_ITEM(retval, 1, v);
1621 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001622
1623 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001624 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001625 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001627
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001629
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001630 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 Py_DECREF(retval);
1632 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001633}
1634
Christian Heimes25bfcd52016-09-06 00:04:45 +02001635#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1636static PyObject *
1637cipher_to_dict(const SSL_CIPHER *cipher)
1638{
1639 const char *cipher_name, *cipher_protocol;
1640
1641 unsigned long cipher_id;
1642 int alg_bits, strength_bits, len;
1643 char buf[512] = {0};
1644#if OPENSSL_VERSION_1_1
1645 int aead, nid;
1646 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1647#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001648
1649 /* can be NULL */
1650 cipher_name = SSL_CIPHER_get_name(cipher);
1651 cipher_protocol = SSL_CIPHER_get_version(cipher);
1652 cipher_id = SSL_CIPHER_get_id(cipher);
1653 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001654 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1655 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001656 if (len > 1 && buf[len-1] == '\n')
1657 buf[len-1] = '\0';
1658 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1659
1660#if OPENSSL_VERSION_1_1
1661 aead = SSL_CIPHER_is_aead(cipher);
1662 nid = SSL_CIPHER_get_cipher_nid(cipher);
1663 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1664 nid = SSL_CIPHER_get_digest_nid(cipher);
1665 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1666 nid = SSL_CIPHER_get_kx_nid(cipher);
1667 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1668 nid = SSL_CIPHER_get_auth_nid(cipher);
1669 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1670#endif
1671
Victor Stinner410b9882016-09-12 12:00:23 +02001672 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001673 "{sksssssssisi"
1674#if OPENSSL_VERSION_1_1
1675 "sOssssssss"
1676#endif
1677 "}",
1678 "id", cipher_id,
1679 "name", cipher_name,
1680 "protocol", cipher_protocol,
1681 "description", buf,
1682 "strength_bits", strength_bits,
1683 "alg_bits", alg_bits
1684#if OPENSSL_VERSION_1_1
1685 ,"aead", aead ? Py_True : Py_False,
1686 "symmetric", skcipher,
1687 "digest", digest,
1688 "kea", kx,
1689 "auth", auth
1690#endif
1691 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001692}
1693#endif
1694
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001695/*[clinic input]
1696_ssl._SSLSocket.shared_ciphers
1697[clinic start generated code]*/
1698
1699static PyObject *
1700_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1701/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001702{
1703 STACK_OF(SSL_CIPHER) *ciphers;
1704 int i;
1705 PyObject *res;
1706
Christian Heimes598894f2016-09-05 23:19:05 +02001707 ciphers = SSL_get_ciphers(self->ssl);
1708 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001709 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001710 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1711 if (!res)
1712 return NULL;
1713 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1714 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1715 if (!tup) {
1716 Py_DECREF(res);
1717 return NULL;
1718 }
1719 PyList_SET_ITEM(res, i, tup);
1720 }
1721 return res;
1722}
1723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001724/*[clinic input]
1725_ssl._SSLSocket.cipher
1726[clinic start generated code]*/
1727
1728static PyObject *
1729_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1730/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001731{
1732 const SSL_CIPHER *current;
1733
1734 if (self->ssl == NULL)
1735 Py_RETURN_NONE;
1736 current = SSL_get_current_cipher(self->ssl);
1737 if (current == NULL)
1738 Py_RETURN_NONE;
1739 return cipher_to_tuple(current);
1740}
1741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001742/*[clinic input]
1743_ssl._SSLSocket.version
1744[clinic start generated code]*/
1745
1746static PyObject *
1747_ssl__SSLSocket_version_impl(PySSLSocket *self)
1748/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001749{
1750 const char *version;
1751
1752 if (self->ssl == NULL)
1753 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001754 if (!SSL_is_init_finished(self->ssl)) {
1755 /* handshake not finished */
1756 Py_RETURN_NONE;
1757 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001758 version = SSL_get_version(self->ssl);
1759 if (!strcmp(version, "unknown"))
1760 Py_RETURN_NONE;
1761 return PyUnicode_FromString(version);
1762}
1763
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001764#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001765/*[clinic input]
1766_ssl._SSLSocket.selected_npn_protocol
1767[clinic start generated code]*/
1768
1769static PyObject *
1770_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1771/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1772{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001773 const unsigned char *out;
1774 unsigned int outlen;
1775
Victor Stinner4569cd52013-06-23 14:58:43 +02001776 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001777 &out, &outlen);
1778
1779 if (out == NULL)
1780 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001781 return PyUnicode_FromStringAndSize((char *)out, outlen);
1782}
1783#endif
1784
1785#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001786/*[clinic input]
1787_ssl._SSLSocket.selected_alpn_protocol
1788[clinic start generated code]*/
1789
1790static PyObject *
1791_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1792/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1793{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001794 const unsigned char *out;
1795 unsigned int outlen;
1796
1797 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1798
1799 if (out == NULL)
1800 Py_RETURN_NONE;
1801 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001802}
1803#endif
1804
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001805/*[clinic input]
1806_ssl._SSLSocket.compression
1807[clinic start generated code]*/
1808
1809static PyObject *
1810_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1811/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1812{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001813#ifdef OPENSSL_NO_COMP
1814 Py_RETURN_NONE;
1815#else
1816 const COMP_METHOD *comp_method;
1817 const char *short_name;
1818
1819 if (self->ssl == NULL)
1820 Py_RETURN_NONE;
1821 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001822 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001823 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001824 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001825 if (short_name == NULL)
1826 Py_RETURN_NONE;
1827 return PyUnicode_DecodeFSDefault(short_name);
1828#endif
1829}
1830
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001831static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1832 Py_INCREF(self->ctx);
1833 return self->ctx;
1834}
1835
1836static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1837 void *closure) {
1838
1839 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001840#if !HAVE_SNI
1841 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1842 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001843 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001844#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001845 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001846 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001847 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001848#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001849 } else {
1850 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1851 return -1;
1852 }
1853
1854 return 0;
1855}
1856
1857PyDoc_STRVAR(PySSL_set_context_doc,
1858"_setter_context(ctx)\n\
1859\
1860This changes the context associated with the SSLSocket. This is typically\n\
1861used from within a callback function set by the set_servername_callback\n\
1862on the SSLContext to change the certificate information associated with the\n\
1863SSLSocket before the cryptographic exchange handshake messages\n");
1864
1865
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001866static PyObject *
1867PySSL_get_server_side(PySSLSocket *self, void *c)
1868{
1869 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1870}
1871
1872PyDoc_STRVAR(PySSL_get_server_side_doc,
1873"Whether this is a server-side socket.");
1874
1875static PyObject *
1876PySSL_get_server_hostname(PySSLSocket *self, void *c)
1877{
1878 if (self->server_hostname == NULL)
1879 Py_RETURN_NONE;
1880 Py_INCREF(self->server_hostname);
1881 return self->server_hostname;
1882}
1883
1884PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1885"The currently set server hostname (for SNI).");
1886
1887static PyObject *
1888PySSL_get_owner(PySSLSocket *self, void *c)
1889{
1890 PyObject *owner;
1891
1892 if (self->owner == NULL)
1893 Py_RETURN_NONE;
1894
1895 owner = PyWeakref_GetObject(self->owner);
1896 Py_INCREF(owner);
1897 return owner;
1898}
1899
1900static int
1901PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1902{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001903 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001904 if (self->owner == NULL)
1905 return -1;
1906 return 0;
1907}
1908
1909PyDoc_STRVAR(PySSL_get_owner_doc,
1910"The Python-level owner of this object.\
1911Passed as \"self\" in servername callback.");
1912
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001913
Antoine Pitrou152efa22010-05-16 18:19:27 +00001914static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001915{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001916 if (self->ssl)
1917 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001919 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001920 Py_XDECREF(self->server_hostname);
1921 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001923}
1924
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001925/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001926 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001927 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001928 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001929
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001930static int
Victor Stinner14690702015-04-06 22:46:13 +02001931PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001932{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001933 int rc;
1934#ifdef HAVE_POLL
1935 struct pollfd pollfd;
1936 _PyTime_t ms;
1937#else
1938 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001939 fd_set fds;
1940 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001941#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001942
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001943 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001944 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001946 else if (timeout < 0) {
1947 if (s->sock_timeout > 0)
1948 return SOCKET_HAS_TIMED_OUT;
1949 else
1950 return SOCKET_IS_BLOCKING;
1951 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001953 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001954 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001956
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 /* Prefer poll, if available, since you can poll() any fd
1958 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001959#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001960 pollfd.fd = s->sock_fd;
1961 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001962
Victor Stinner14690702015-04-06 22:46:13 +02001963 /* timeout is in seconds, poll() uses milliseconds */
1964 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001965 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001966
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001967 PySSL_BEGIN_ALLOW_THREADS
1968 rc = poll(&pollfd, 1, (int)ms);
1969 PySSL_END_ALLOW_THREADS
1970#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001971 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001972 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001973 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001974
Victor Stinner14690702015-04-06 22:46:13 +02001975 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001977 FD_ZERO(&fds);
1978 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001979
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001980 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001982 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001984 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001986 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001987 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001988#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001989
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001990 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1991 (when we are able to write or when there's something to read) */
1992 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001993}
1994
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001995/*[clinic input]
1996_ssl._SSLSocket.write
1997 b: Py_buffer
1998 /
1999
2000Writes the bytes-like object b into the SSL object.
2001
2002Returns the number of bytes written.
2003[clinic start generated code]*/
2004
2005static PyObject *
2006_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2007/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002008{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002009 int len;
2010 int sockstate;
2011 int err;
2012 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002013 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002014 _PyTime_t timeout, deadline = 0;
2015 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002016
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002017 if (sock != NULL) {
2018 if (((PyObject*)sock) == Py_None) {
2019 _setSSLError("Underlying socket connection gone",
2020 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2021 return NULL;
2022 }
2023 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002024 }
2025
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002026 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002027 PyErr_Format(PyExc_OverflowError,
2028 "string longer than %d bytes", INT_MAX);
2029 goto error;
2030 }
2031
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002032 if (sock != NULL) {
2033 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002034 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002035 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2036 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2037 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002038
Victor Stinner14690702015-04-06 22:46:13 +02002039 timeout = GET_SOCKET_TIMEOUT(sock);
2040 has_timeout = (timeout > 0);
2041 if (has_timeout)
2042 deadline = _PyTime_GetMonotonicClock() + timeout;
2043
2044 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002045 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002046 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002047 "The write operation timed out");
2048 goto error;
2049 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2050 PyErr_SetString(PySSLErrorObject,
2051 "Underlying socket has been closed.");
2052 goto error;
2053 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2054 PyErr_SetString(PySSLErrorObject,
2055 "Underlying socket too large for select().");
2056 goto error;
2057 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002059 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002060 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002061 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002062 err = SSL_get_error(self->ssl, len);
2063 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002064
2065 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002067
Victor Stinner14690702015-04-06 22:46:13 +02002068 if (has_timeout)
2069 timeout = deadline - _PyTime_GetMonotonicClock();
2070
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002072 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002073 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002074 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002075 } else {
2076 sockstate = SOCKET_OPERATION_OK;
2077 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002079 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002080 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002081 "The write operation timed out");
2082 goto error;
2083 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2084 PyErr_SetString(PySSLErrorObject,
2085 "Underlying socket has been closed.");
2086 goto error;
2087 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2088 break;
2089 }
2090 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002091
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002092 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 if (len > 0)
2094 return PyLong_FromLong(len);
2095 else
2096 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002097
2098error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002099 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002100 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002101}
2102
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002103/*[clinic input]
2104_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002105
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002106Returns the number of already decrypted bytes available for read, pending on the connection.
2107[clinic start generated code]*/
2108
2109static PyObject *
2110_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2111/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002112{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002113 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002114
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115 PySSL_BEGIN_ALLOW_THREADS
2116 count = SSL_pending(self->ssl);
2117 PySSL_END_ALLOW_THREADS
2118 if (count < 0)
2119 return PySSL_SetError(self, count, __FILE__, __LINE__);
2120 else
2121 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002122}
2123
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002124/*[clinic input]
2125_ssl._SSLSocket.read
2126 size as len: int
2127 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002128 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002129 ]
2130 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002131
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002132Read up to size bytes from the SSL socket.
2133[clinic start generated code]*/
2134
2135static PyObject *
2136_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2137 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002138/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002139{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002141 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002142 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002143 int sockstate;
2144 int err;
2145 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002146 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002147 _PyTime_t timeout, deadline = 0;
2148 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002149
Martin Panter5503d472016-03-27 05:35:19 +00002150 if (!group_right_1 && len < 0) {
2151 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2152 return NULL;
2153 }
2154
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002155 if (sock != NULL) {
2156 if (((PyObject*)sock) == Py_None) {
2157 _setSSLError("Underlying socket connection gone",
2158 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2159 return NULL;
2160 }
2161 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 }
2163
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002164 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002165 dest = PyBytes_FromStringAndSize(NULL, len);
2166 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002167 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002168 if (len == 0) {
2169 Py_XDECREF(sock);
2170 return dest;
2171 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002172 mem = PyBytes_AS_STRING(dest);
2173 }
2174 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002175 mem = buffer->buf;
2176 if (len <= 0 || len > buffer->len) {
2177 len = (int) buffer->len;
2178 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002179 PyErr_SetString(PyExc_OverflowError,
2180 "maximum length can't fit in a C 'int'");
2181 goto error;
2182 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002183 if (len == 0) {
2184 count = 0;
2185 goto done;
2186 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002187 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 }
2189
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002190 if (sock != NULL) {
2191 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002192 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002193 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2194 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2195 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002196
Victor Stinner14690702015-04-06 22:46:13 +02002197 timeout = GET_SOCKET_TIMEOUT(sock);
2198 has_timeout = (timeout > 0);
2199 if (has_timeout)
2200 deadline = _PyTime_GetMonotonicClock() + timeout;
2201
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002202 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 PySSL_BEGIN_ALLOW_THREADS
2204 count = SSL_read(self->ssl, mem, len);
2205 err = SSL_get_error(self->ssl, count);
2206 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002207
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 if (PyErr_CheckSignals())
2209 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002210
Victor Stinner14690702015-04-06 22:46:13 +02002211 if (has_timeout)
2212 timeout = deadline - _PyTime_GetMonotonicClock();
2213
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002214 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002215 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002216 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002217 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002218 } else if (err == SSL_ERROR_ZERO_RETURN &&
2219 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002220 {
2221 count = 0;
2222 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002223 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002224 else
2225 sockstate = SOCKET_OPERATION_OK;
2226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002228 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 "The read operation timed out");
2230 goto error;
2231 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2232 break;
2233 }
2234 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002235
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 if (count <= 0) {
2237 PySSL_SetError(self, count, __FILE__, __LINE__);
2238 goto error;
2239 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002240
2241done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002242 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002243 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002244 _PyBytes_Resize(&dest, count);
2245 return dest;
2246 }
2247 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 return PyLong_FromLong(count);
2249 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002250
2251error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002252 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002253 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002254 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002255 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002256}
2257
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002258/*[clinic input]
2259_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002260
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002261Does the SSL shutdown handshake with the remote end.
2262
2263Returns the underlying socket object.
2264[clinic start generated code]*/
2265
2266static PyObject *
2267_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2268/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002269{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002270 int err, ssl_err, sockstate, nonblocking;
2271 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002272 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002273 _PyTime_t timeout, deadline = 0;
2274 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002275
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002276 if (sock != NULL) {
2277 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002278 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002279 _setSSLError("Underlying socket connection gone",
2280 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2281 return NULL;
2282 }
2283 Py_INCREF(sock);
2284
2285 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002286 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002287 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2288 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002289 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290
Victor Stinner14690702015-04-06 22:46:13 +02002291 timeout = GET_SOCKET_TIMEOUT(sock);
2292 has_timeout = (timeout > 0);
2293 if (has_timeout)
2294 deadline = _PyTime_GetMonotonicClock() + timeout;
2295
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 while (1) {
2297 PySSL_BEGIN_ALLOW_THREADS
2298 /* Disable read-ahead so that unwrap can work correctly.
2299 * Otherwise OpenSSL might read in too much data,
2300 * eating clear text data that happens to be
2301 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002302 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002303 * function is used and the shutdown_seen_zero != 0
2304 * condition is met.
2305 */
2306 if (self->shutdown_seen_zero)
2307 SSL_set_read_ahead(self->ssl, 0);
2308 err = SSL_shutdown(self->ssl);
2309 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002310
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002311 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2312 if (err > 0)
2313 break;
2314 if (err == 0) {
2315 /* Don't loop endlessly; instead preserve legacy
2316 behaviour of trying SSL_shutdown() only twice.
2317 This looks necessary for OpenSSL < 0.9.8m */
2318 if (++zeros > 1)
2319 break;
2320 /* Shutdown was sent, now try receiving */
2321 self->shutdown_seen_zero = 1;
2322 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002323 }
2324
Victor Stinner14690702015-04-06 22:46:13 +02002325 if (has_timeout)
2326 timeout = deadline - _PyTime_GetMonotonicClock();
2327
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002328 /* Possibly retry shutdown until timeout or failure */
2329 ssl_err = SSL_get_error(self->ssl, err);
2330 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002331 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002333 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002334 else
2335 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002336
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2338 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002339 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002340 "The read operation timed out");
2341 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002342 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002343 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002344 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 }
2346 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2347 PyErr_SetString(PySSLErrorObject,
2348 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002349 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 }
2351 else if (sockstate != SOCKET_OPERATION_OK)
2352 /* Retain the SSL error code */
2353 break;
2354 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002355
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002356 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002357 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002358 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002360 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002361 /* It's already INCREF'ed */
2362 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002363 else
2364 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002365
2366error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002367 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002368 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002369}
2370
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002371/*[clinic input]
2372_ssl._SSLSocket.tls_unique_cb
2373
2374Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2375
2376If the TLS handshake is not yet complete, None is returned.
2377[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002378
Antoine Pitroud6494802011-07-21 01:11:30 +02002379static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002380_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2381/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002382{
2383 PyObject *retval = NULL;
2384 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002385 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002386
2387 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2388 /* if session is resumed XOR we are the client */
2389 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2390 }
2391 else {
2392 /* if a new session XOR we are the server */
2393 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2394 }
2395
2396 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002397 if (len == 0)
2398 Py_RETURN_NONE;
2399
2400 retval = PyBytes_FromStringAndSize(buf, len);
2401
2402 return retval;
2403}
2404
Christian Heimes99a65702016-09-10 23:44:53 +02002405#ifdef OPENSSL_VERSION_1_1
2406
2407static SSL_SESSION*
2408_ssl_session_dup(SSL_SESSION *session) {
2409 SSL_SESSION *newsession = NULL;
2410 int slen;
2411 unsigned char *senc = NULL, *p;
2412 const unsigned char *const_p;
2413
2414 if (session == NULL) {
2415 PyErr_SetString(PyExc_ValueError, "Invalid session");
2416 goto error;
2417 }
2418
2419 /* get length */
2420 slen = i2d_SSL_SESSION(session, NULL);
2421 if (slen == 0 || slen > 0xFF00) {
2422 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2423 goto error;
2424 }
2425 if ((senc = PyMem_Malloc(slen)) == NULL) {
2426 PyErr_NoMemory();
2427 goto error;
2428 }
2429 p = senc;
2430 if (!i2d_SSL_SESSION(session, &p)) {
2431 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2432 goto error;
2433 }
2434 const_p = senc;
2435 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2436 if (session == NULL) {
2437 goto error;
2438 }
2439 PyMem_Free(senc);
2440 return newsession;
2441 error:
2442 if (senc != NULL) {
2443 PyMem_Free(senc);
2444 }
2445 return NULL;
2446}
2447#endif
2448
2449static PyObject *
2450PySSL_get_session(PySSLSocket *self, void *closure) {
2451 /* get_session can return sessions from a server-side connection,
2452 * it does not check for handshake done or client socket. */
2453 PySSLSession *pysess;
2454 SSL_SESSION *session;
2455
2456#ifdef OPENSSL_VERSION_1_1
2457 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2458 * https://github.com/openssl/openssl/issues/1550 */
2459 session = SSL_get0_session(self->ssl); /* borrowed reference */
2460 if (session == NULL) {
2461 Py_RETURN_NONE;
2462 }
2463 if ((session = _ssl_session_dup(session)) == NULL) {
2464 return NULL;
2465 }
2466#else
2467 session = SSL_get1_session(self->ssl);
2468 if (session == NULL) {
2469 Py_RETURN_NONE;
2470 }
2471#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002472 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002473 if (pysess == NULL) {
2474 SSL_SESSION_free(session);
2475 return NULL;
2476 }
2477
2478 assert(self->ctx);
2479 pysess->ctx = self->ctx;
2480 Py_INCREF(pysess->ctx);
2481 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002482 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002483 return (PyObject *)pysess;
2484}
2485
2486static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2487 void *closure)
2488 {
2489 PySSLSession *pysess;
2490#ifdef OPENSSL_VERSION_1_1
2491 SSL_SESSION *session;
2492#endif
2493 int result;
2494
2495 if (!PySSLSession_Check(value)) {
2496 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2497 return -1;
2498 }
2499 pysess = (PySSLSession *)value;
2500
2501 if (self->ctx->ctx != pysess->ctx->ctx) {
2502 PyErr_SetString(PyExc_ValueError,
2503 "Session refers to a different SSLContext.");
2504 return -1;
2505 }
2506 if (self->socket_type != PY_SSL_CLIENT) {
2507 PyErr_SetString(PyExc_ValueError,
2508 "Cannot set session for server-side SSLSocket.");
2509 return -1;
2510 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002511 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002512 PyErr_SetString(PyExc_ValueError,
2513 "Cannot set session after handshake.");
2514 return -1;
2515 }
2516#ifdef OPENSSL_VERSION_1_1
2517 /* duplicate session */
2518 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2519 return -1;
2520 }
2521 result = SSL_set_session(self->ssl, session);
2522 /* free duplicate, SSL_set_session() bumps ref count */
2523 SSL_SESSION_free(session);
2524#else
2525 result = SSL_set_session(self->ssl, pysess->session);
2526#endif
2527 if (result == 0) {
2528 _setSSLError(NULL, 0, __FILE__, __LINE__);
2529 return -1;
2530 }
2531 return 0;
2532}
2533
2534PyDoc_STRVAR(PySSL_set_session_doc,
2535"_setter_session(session)\n\
2536\
2537Get / set SSLSession.");
2538
2539static PyObject *
2540PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2541 if (SSL_session_reused(self->ssl)) {
2542 Py_RETURN_TRUE;
2543 } else {
2544 Py_RETURN_FALSE;
2545 }
2546}
2547
2548PyDoc_STRVAR(PySSL_get_session_reused_doc,
2549"Was the client session reused during handshake?");
2550
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002551static PyGetSetDef ssl_getsetlist[] = {
2552 {"context", (getter) PySSL_get_context,
2553 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002554 {"server_side", (getter) PySSL_get_server_side, NULL,
2555 PySSL_get_server_side_doc},
2556 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2557 PySSL_get_server_hostname_doc},
2558 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2559 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002560 {"session", (getter) PySSL_get_session,
2561 (setter) PySSL_set_session, PySSL_set_session_doc},
2562 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2563 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002564 {NULL}, /* sentinel */
2565};
2566
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002567static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002568 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2569 _SSL__SSLSOCKET_WRITE_METHODDEF
2570 _SSL__SSLSOCKET_READ_METHODDEF
2571 _SSL__SSLSOCKET_PENDING_METHODDEF
2572 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2573 _SSL__SSLSOCKET_CIPHER_METHODDEF
2574 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2575 _SSL__SSLSOCKET_VERSION_METHODDEF
2576 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2577 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2578 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2579 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2580 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002581 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002582};
2583
Antoine Pitrou152efa22010-05-16 18:19:27 +00002584static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002585 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002586 "_ssl._SSLSocket", /*tp_name*/
2587 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002588 0, /*tp_itemsize*/
2589 /* methods */
2590 (destructor)PySSL_dealloc, /*tp_dealloc*/
2591 0, /*tp_print*/
2592 0, /*tp_getattr*/
2593 0, /*tp_setattr*/
2594 0, /*tp_reserved*/
2595 0, /*tp_repr*/
2596 0, /*tp_as_number*/
2597 0, /*tp_as_sequence*/
2598 0, /*tp_as_mapping*/
2599 0, /*tp_hash*/
2600 0, /*tp_call*/
2601 0, /*tp_str*/
2602 0, /*tp_getattro*/
2603 0, /*tp_setattro*/
2604 0, /*tp_as_buffer*/
2605 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2606 0, /*tp_doc*/
2607 0, /*tp_traverse*/
2608 0, /*tp_clear*/
2609 0, /*tp_richcompare*/
2610 0, /*tp_weaklistoffset*/
2611 0, /*tp_iter*/
2612 0, /*tp_iternext*/
2613 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002614 0, /*tp_members*/
2615 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002616};
2617
Antoine Pitrou152efa22010-05-16 18:19:27 +00002618
2619/*
2620 * _SSLContext objects
2621 */
2622
Christian Heimes5fe668c2016-09-12 00:01:11 +02002623static int
2624_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2625{
2626 int mode;
2627 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2628
2629 switch(n) {
2630 case PY_SSL_CERT_NONE:
2631 mode = SSL_VERIFY_NONE;
2632 break;
2633 case PY_SSL_CERT_OPTIONAL:
2634 mode = SSL_VERIFY_PEER;
2635 break;
2636 case PY_SSL_CERT_REQUIRED:
2637 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2638 break;
2639 default:
2640 PyErr_SetString(PyExc_ValueError,
2641 "invalid value for verify_mode");
2642 return -1;
2643 }
2644 /* keep current verify cb */
2645 verify_cb = SSL_CTX_get_verify_callback(ctx);
2646 SSL_CTX_set_verify(ctx, mode, verify_cb);
2647 return 0;
2648}
2649
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002650/*[clinic input]
2651@classmethod
2652_ssl._SSLContext.__new__
2653 protocol as proto_version: int
2654 /
2655[clinic start generated code]*/
2656
Antoine Pitrou152efa22010-05-16 18:19:27 +00002657static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002658_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2659/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002660{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002661 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002662 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002663 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002664 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002665#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002666 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002667#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002668
Antoine Pitrou152efa22010-05-16 18:19:27 +00002669 PySSL_BEGIN_ALLOW_THREADS
2670 if (proto_version == PY_SSL_VERSION_TLS1)
2671 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002672#if HAVE_TLSv1_2
2673 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2674 ctx = SSL_CTX_new(TLSv1_1_method());
2675 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2676 ctx = SSL_CTX_new(TLSv1_2_method());
2677#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002678#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002679 else if (proto_version == PY_SSL_VERSION_SSL3)
2680 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002681#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002682#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002683 else if (proto_version == PY_SSL_VERSION_SSL2)
2684 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002685#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002686 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002687 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002688 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2689 ctx = SSL_CTX_new(TLS_client_method());
2690 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2691 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002692 else
2693 proto_version = -1;
2694 PySSL_END_ALLOW_THREADS
2695
2696 if (proto_version == -1) {
2697 PyErr_SetString(PyExc_ValueError,
2698 "invalid protocol version");
2699 return NULL;
2700 }
2701 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002702 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002703 return NULL;
2704 }
2705
2706 assert(type != NULL && type->tp_alloc != NULL);
2707 self = (PySSLContext *) type->tp_alloc(type, 0);
2708 if (self == NULL) {
2709 SSL_CTX_free(ctx);
2710 return NULL;
2711 }
2712 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002713#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002714 self->npn_protocols = NULL;
2715#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002716#ifdef HAVE_ALPN
2717 self->alpn_protocols = NULL;
2718#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002719#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002720 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002721#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002722 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002723 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2724 self->check_hostname = 1;
2725 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2726 Py_DECREF(self);
2727 return NULL;
2728 }
2729 } else {
2730 self->check_hostname = 0;
2731 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2732 Py_DECREF(self);
2733 return NULL;
2734 }
2735 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002736 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002737 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2738 if (proto_version != PY_SSL_VERSION_SSL2)
2739 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002740 if (proto_version != PY_SSL_VERSION_SSL3)
2741 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002742 /* Minimal security flags for server and client side context.
2743 * Client sockets ignore server-side parameters. */
2744#ifdef SSL_OP_NO_COMPRESSION
2745 options |= SSL_OP_NO_COMPRESSION;
2746#endif
2747#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2748 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2749#endif
2750#ifdef SSL_OP_SINGLE_DH_USE
2751 options |= SSL_OP_SINGLE_DH_USE;
2752#endif
2753#ifdef SSL_OP_SINGLE_ECDH_USE
2754 options |= SSL_OP_SINGLE_ECDH_USE;
2755#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002756 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757
Christian Heimes358cfd42016-09-10 22:43:48 +02002758 /* A bare minimum cipher list without completly broken cipher suites.
2759 * It's far from perfect but gives users a better head start. */
2760 if (proto_version != PY_SSL_VERSION_SSL2) {
2761 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2762 } else {
2763 /* SSLv2 needs MD5 */
2764 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2765 }
2766 if (result == 0) {
2767 Py_DECREF(self);
2768 ERR_clear_error();
2769 PyErr_SetString(PySSLErrorObject,
2770 "No cipher can be selected.");
2771 return NULL;
2772 }
2773
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002774#if defined(SSL_MODE_RELEASE_BUFFERS)
2775 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2776 usage for no cost at all. However, don't do this for OpenSSL versions
2777 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2778 2014-0198. I can't find exactly which beta fixed this CVE, so be
2779 conservative and assume it wasn't fixed until release. We do this check
2780 at runtime to avoid problems from the dynamic linker.
2781 See #25672 for more on this. */
2782 libver = SSLeay();
2783 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2784 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2785 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2786 }
2787#endif
2788
2789
Donald Stufft8ae264c2017-03-02 11:45:29 -05002790#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002791 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2792 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002793 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2794 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002795#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002796 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2797#else
2798 {
2799 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2800 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2801 EC_KEY_free(key);
2802 }
2803#endif
2804#endif
2805
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002806#define SID_CTX "Python"
2807 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2808 sizeof(SID_CTX));
2809#undef SID_CTX
2810
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002811#ifdef X509_V_FLAG_TRUSTED_FIRST
2812 {
2813 /* Improve trust chain building when cross-signed intermediate
2814 certificates are present. See https://bugs.python.org/issue23476. */
2815 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2816 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2817 }
2818#endif
2819
Antoine Pitrou152efa22010-05-16 18:19:27 +00002820 return (PyObject *)self;
2821}
2822
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002823static int
2824context_traverse(PySSLContext *self, visitproc visit, void *arg)
2825{
2826#ifndef OPENSSL_NO_TLSEXT
2827 Py_VISIT(self->set_hostname);
2828#endif
2829 return 0;
2830}
2831
2832static int
2833context_clear(PySSLContext *self)
2834{
2835#ifndef OPENSSL_NO_TLSEXT
2836 Py_CLEAR(self->set_hostname);
2837#endif
2838 return 0;
2839}
2840
Antoine Pitrou152efa22010-05-16 18:19:27 +00002841static void
2842context_dealloc(PySSLContext *self)
2843{
INADA Naokia6296d32017-08-24 14:55:17 +09002844 /* bpo-31095: UnTrack is needed before calling any callbacks */
2845 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002846 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002847 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002848#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002849 PyMem_FREE(self->npn_protocols);
2850#endif
2851#ifdef HAVE_ALPN
2852 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002853#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002854 Py_TYPE(self)->tp_free(self);
2855}
2856
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002857/*[clinic input]
2858_ssl._SSLContext.set_ciphers
2859 cipherlist: str
2860 /
2861[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002862
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002863static PyObject *
2864_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2865/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2866{
2867 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002868 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002869 /* Clearing the error queue is necessary on some OpenSSL versions,
2870 otherwise the error will be reported again when another SSL call
2871 is done. */
2872 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873 PyErr_SetString(PySSLErrorObject,
2874 "No cipher can be selected.");
2875 return NULL;
2876 }
2877 Py_RETURN_NONE;
2878}
2879
Christian Heimes25bfcd52016-09-06 00:04:45 +02002880#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2881/*[clinic input]
2882_ssl._SSLContext.get_ciphers
2883[clinic start generated code]*/
2884
2885static PyObject *
2886_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2887/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2888{
2889 SSL *ssl = NULL;
2890 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002891 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002892 int i=0;
2893 PyObject *result = NULL, *dct;
2894
2895 ssl = SSL_new(self->ctx);
2896 if (ssl == NULL) {
2897 _setSSLError(NULL, 0, __FILE__, __LINE__);
2898 goto exit;
2899 }
2900 sk = SSL_get_ciphers(ssl);
2901
2902 result = PyList_New(sk_SSL_CIPHER_num(sk));
2903 if (result == NULL) {
2904 goto exit;
2905 }
2906
2907 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2908 cipher = sk_SSL_CIPHER_value(sk, i);
2909 dct = cipher_to_dict(cipher);
2910 if (dct == NULL) {
2911 Py_CLEAR(result);
2912 goto exit;
2913 }
2914 PyList_SET_ITEM(result, i, dct);
2915 }
2916
2917 exit:
2918 if (ssl != NULL)
2919 SSL_free(ssl);
2920 return result;
2921
2922}
2923#endif
2924
2925
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002926#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002927static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002928do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2929 const unsigned char *server_protocols, unsigned int server_protocols_len,
2930 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002931{
Benjamin Peterson88615022015-01-23 17:30:26 -05002932 int ret;
2933 if (client_protocols == NULL) {
2934 client_protocols = (unsigned char *)"";
2935 client_protocols_len = 0;
2936 }
2937 if (server_protocols == NULL) {
2938 server_protocols = (unsigned char *)"";
2939 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002940 }
2941
Benjamin Peterson88615022015-01-23 17:30:26 -05002942 ret = SSL_select_next_proto(out, outlen,
2943 server_protocols, server_protocols_len,
2944 client_protocols, client_protocols_len);
2945 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2946 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002947
2948 return SSL_TLSEXT_ERR_OK;
2949}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002950#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002951
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002952#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002953/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2954static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002955_advertiseNPN_cb(SSL *s,
2956 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002957 void *args)
2958{
2959 PySSLContext *ssl_ctx = (PySSLContext *) args;
2960
2961 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002962 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002963 *len = 0;
2964 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002965 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002966 *len = ssl_ctx->npn_protocols_len;
2967 }
2968
2969 return SSL_TLSEXT_ERR_OK;
2970}
2971/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2972static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002973_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002974 unsigned char **out, unsigned char *outlen,
2975 const unsigned char *server, unsigned int server_len,
2976 void *args)
2977{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002978 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002979 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002980 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002981}
2982#endif
2983
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002984/*[clinic input]
2985_ssl._SSLContext._set_npn_protocols
2986 protos: Py_buffer
2987 /
2988[clinic start generated code]*/
2989
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002990static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002991_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2992 Py_buffer *protos)
2993/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002994{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002995#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002996 PyMem_Free(self->npn_protocols);
2997 self->npn_protocols = PyMem_Malloc(protos->len);
2998 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002999 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003000 memcpy(self->npn_protocols, protos->buf, protos->len);
3001 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003002
3003 /* set both server and client callbacks, because the context can
3004 * be used to create both types of sockets */
3005 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3006 _advertiseNPN_cb,
3007 self);
3008 SSL_CTX_set_next_proto_select_cb(self->ctx,
3009 _selectNPN_cb,
3010 self);
3011
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003012 Py_RETURN_NONE;
3013#else
3014 PyErr_SetString(PyExc_NotImplementedError,
3015 "The NPN extension requires OpenSSL 1.0.1 or later.");
3016 return NULL;
3017#endif
3018}
3019
Benjamin Petersoncca27322015-01-23 16:35:37 -05003020#ifdef HAVE_ALPN
3021static int
3022_selectALPN_cb(SSL *s,
3023 const unsigned char **out, unsigned char *outlen,
3024 const unsigned char *client_protocols, unsigned int client_protocols_len,
3025 void *args)
3026{
3027 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003028 return do_protocol_selection(1, (unsigned char **)out, outlen,
3029 ctx->alpn_protocols, ctx->alpn_protocols_len,
3030 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003031}
3032#endif
3033
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003034/*[clinic input]
3035_ssl._SSLContext._set_alpn_protocols
3036 protos: Py_buffer
3037 /
3038[clinic start generated code]*/
3039
Benjamin Petersoncca27322015-01-23 16:35:37 -05003040static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003041_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3042 Py_buffer *protos)
3043/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003044{
3045#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03003046 if (protos->len > UINT_MAX) {
3047 PyErr_Format(PyExc_OverflowError,
3048 "protocols longer than %d bytes", UINT_MAX);
3049 return NULL;
3050 }
3051
Benjamin Petersoncca27322015-01-23 16:35:37 -05003052 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003053 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003054 if (!self->alpn_protocols)
3055 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003056 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003057 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003058
3059 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3060 return PyErr_NoMemory();
3061 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3062
Benjamin Petersoncca27322015-01-23 16:35:37 -05003063 Py_RETURN_NONE;
3064#else
3065 PyErr_SetString(PyExc_NotImplementedError,
3066 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3067 return NULL;
3068#endif
3069}
3070
Antoine Pitrou152efa22010-05-16 18:19:27 +00003071static PyObject *
3072get_verify_mode(PySSLContext *self, void *c)
3073{
3074 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3075 case SSL_VERIFY_NONE:
3076 return PyLong_FromLong(PY_SSL_CERT_NONE);
3077 case SSL_VERIFY_PEER:
3078 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3079 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3080 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3081 }
3082 PyErr_SetString(PySSLErrorObject,
3083 "invalid return value from SSL_CTX_get_verify_mode");
3084 return NULL;
3085}
3086
3087static int
3088set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3089{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003090 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003091 if (!PyArg_Parse(arg, "i", &n))
3092 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003093 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003094 PyErr_SetString(PyExc_ValueError,
3095 "Cannot set verify_mode to CERT_NONE when "
3096 "check_hostname is enabled.");
3097 return -1;
3098 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003099 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003100}
3101
3102static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003103get_verify_flags(PySSLContext *self, void *c)
3104{
3105 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003106 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003107 unsigned long flags;
3108
3109 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003110 param = X509_STORE_get0_param(store);
3111 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003112 return PyLong_FromUnsignedLong(flags);
3113}
3114
3115static int
3116set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3117{
3118 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003119 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003120 unsigned long new_flags, flags, set, clear;
3121
3122 if (!PyArg_Parse(arg, "k", &new_flags))
3123 return -1;
3124 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003125 param = X509_STORE_get0_param(store);
3126 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003127 clear = flags & ~new_flags;
3128 set = ~flags & new_flags;
3129 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003130 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003131 _setSSLError(NULL, 0, __FILE__, __LINE__);
3132 return -1;
3133 }
3134 }
3135 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003136 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003137 _setSSLError(NULL, 0, __FILE__, __LINE__);
3138 return -1;
3139 }
3140 }
3141 return 0;
3142}
3143
3144static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003145get_options(PySSLContext *self, void *c)
3146{
3147 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3148}
3149
3150static int
3151set_options(PySSLContext *self, PyObject *arg, void *c)
3152{
3153 long new_opts, opts, set, clear;
3154 if (!PyArg_Parse(arg, "l", &new_opts))
3155 return -1;
3156 opts = SSL_CTX_get_options(self->ctx);
3157 clear = opts & ~new_opts;
3158 set = ~opts & new_opts;
3159 if (clear) {
3160#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3161 SSL_CTX_clear_options(self->ctx, clear);
3162#else
3163 PyErr_SetString(PyExc_ValueError,
3164 "can't clear options before OpenSSL 0.9.8m");
3165 return -1;
3166#endif
3167 }
3168 if (set)
3169 SSL_CTX_set_options(self->ctx, set);
3170 return 0;
3171}
3172
Christian Heimes1aa9a752013-12-02 02:41:19 +01003173static PyObject *
3174get_check_hostname(PySSLContext *self, void *c)
3175{
3176 return PyBool_FromLong(self->check_hostname);
3177}
3178
3179static int
3180set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3181{
3182 int check_hostname;
3183 if (!PyArg_Parse(arg, "p", &check_hostname))
3184 return -1;
3185 if (check_hostname &&
3186 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3187 PyErr_SetString(PyExc_ValueError,
3188 "check_hostname needs a SSL context with either "
3189 "CERT_OPTIONAL or CERT_REQUIRED");
3190 return -1;
3191 }
3192 self->check_hostname = check_hostname;
3193 return 0;
3194}
3195
3196
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003197typedef struct {
3198 PyThreadState *thread_state;
3199 PyObject *callable;
3200 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003201 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003202 int error;
3203} _PySSLPasswordInfo;
3204
3205static int
3206_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3207 const char *bad_type_error)
3208{
3209 /* Set the password and size fields of a _PySSLPasswordInfo struct
3210 from a unicode, bytes, or byte array object.
3211 The password field will be dynamically allocated and must be freed
3212 by the caller */
3213 PyObject *password_bytes = NULL;
3214 const char *data = NULL;
3215 Py_ssize_t size;
3216
3217 if (PyUnicode_Check(password)) {
3218 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3219 if (!password_bytes) {
3220 goto error;
3221 }
3222 data = PyBytes_AS_STRING(password_bytes);
3223 size = PyBytes_GET_SIZE(password_bytes);
3224 } else if (PyBytes_Check(password)) {
3225 data = PyBytes_AS_STRING(password);
3226 size = PyBytes_GET_SIZE(password);
3227 } else if (PyByteArray_Check(password)) {
3228 data = PyByteArray_AS_STRING(password);
3229 size = PyByteArray_GET_SIZE(password);
3230 } else {
3231 PyErr_SetString(PyExc_TypeError, bad_type_error);
3232 goto error;
3233 }
3234
Victor Stinner9ee02032013-06-23 15:08:23 +02003235 if (size > (Py_ssize_t)INT_MAX) {
3236 PyErr_Format(PyExc_ValueError,
3237 "password cannot be longer than %d bytes", INT_MAX);
3238 goto error;
3239 }
3240
Victor Stinner11ebff22013-07-07 17:07:52 +02003241 PyMem_Free(pw_info->password);
3242 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003243 if (!pw_info->password) {
3244 PyErr_SetString(PyExc_MemoryError,
3245 "unable to allocate password buffer");
3246 goto error;
3247 }
3248 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003249 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003250
3251 Py_XDECREF(password_bytes);
3252 return 1;
3253
3254error:
3255 Py_XDECREF(password_bytes);
3256 return 0;
3257}
3258
3259static int
3260_password_callback(char *buf, int size, int rwflag, void *userdata)
3261{
3262 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3263 PyObject *fn_ret = NULL;
3264
3265 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3266
3267 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003268 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003269 if (!fn_ret) {
3270 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3271 core python API, so we could use it to add a frame here */
3272 goto error;
3273 }
3274
3275 if (!_pwinfo_set(pw_info, fn_ret,
3276 "password callback must return a string")) {
3277 goto error;
3278 }
3279 Py_CLEAR(fn_ret);
3280 }
3281
3282 if (pw_info->size > size) {
3283 PyErr_Format(PyExc_ValueError,
3284 "password cannot be longer than %d bytes", size);
3285 goto error;
3286 }
3287
3288 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3289 memcpy(buf, pw_info->password, pw_info->size);
3290 return pw_info->size;
3291
3292error:
3293 Py_XDECREF(fn_ret);
3294 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3295 pw_info->error = 1;
3296 return -1;
3297}
3298
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003299/*[clinic input]
3300_ssl._SSLContext.load_cert_chain
3301 certfile: object
3302 keyfile: object = NULL
3303 password: object = NULL
3304
3305[clinic start generated code]*/
3306
Antoine Pitroub5218772010-05-21 09:56:06 +00003307static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003308_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3309 PyObject *keyfile, PyObject *password)
3310/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003311{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003312 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003313 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3314 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003315 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316 int r;
3317
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003318 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003319 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003320 if (keyfile == Py_None)
3321 keyfile = NULL;
3322 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3323 PyErr_SetString(PyExc_TypeError,
3324 "certfile should be a valid filesystem path");
3325 return NULL;
3326 }
3327 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3328 PyErr_SetString(PyExc_TypeError,
3329 "keyfile should be a valid filesystem path");
3330 goto error;
3331 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003332 if (password && password != Py_None) {
3333 if (PyCallable_Check(password)) {
3334 pw_info.callable = password;
3335 } else if (!_pwinfo_set(&pw_info, password,
3336 "password should be a string or callable")) {
3337 goto error;
3338 }
3339 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3340 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3341 }
3342 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003343 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3344 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003345 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003346 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003347 if (pw_info.error) {
3348 ERR_clear_error();
3349 /* the password callback has already set the error information */
3350 }
3351 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003352 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003353 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003354 }
3355 else {
3356 _setSSLError(NULL, 0, __FILE__, __LINE__);
3357 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003358 goto error;
3359 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003360 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003361 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003362 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3363 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003364 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3365 Py_CLEAR(keyfile_bytes);
3366 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003367 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003368 if (pw_info.error) {
3369 ERR_clear_error();
3370 /* the password callback has already set the error information */
3371 }
3372 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003373 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003374 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003375 }
3376 else {
3377 _setSSLError(NULL, 0, __FILE__, __LINE__);
3378 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003379 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003380 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003381 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003382 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003383 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003384 if (r != 1) {
3385 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003386 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003387 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003388 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3389 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003390 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003391 Py_RETURN_NONE;
3392
3393error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003394 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3395 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003396 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003397 Py_XDECREF(keyfile_bytes);
3398 Py_XDECREF(certfile_bytes);
3399 return NULL;
3400}
3401
Christian Heimesefff7062013-11-21 03:35:02 +01003402/* internal helper function, returns -1 on error
3403 */
3404static int
3405_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3406 int filetype)
3407{
3408 BIO *biobuf = NULL;
3409 X509_STORE *store;
3410 int retval = 0, err, loaded = 0;
3411
3412 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3413
3414 if (len <= 0) {
3415 PyErr_SetString(PyExc_ValueError,
3416 "Empty certificate data");
3417 return -1;
3418 } else if (len > INT_MAX) {
3419 PyErr_SetString(PyExc_OverflowError,
3420 "Certificate data is too long.");
3421 return -1;
3422 }
3423
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003424 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003425 if (biobuf == NULL) {
3426 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3427 return -1;
3428 }
3429
3430 store = SSL_CTX_get_cert_store(self->ctx);
3431 assert(store != NULL);
3432
3433 while (1) {
3434 X509 *cert = NULL;
3435 int r;
3436
3437 if (filetype == SSL_FILETYPE_ASN1) {
3438 cert = d2i_X509_bio(biobuf, NULL);
3439 } else {
3440 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003441 SSL_CTX_get_default_passwd_cb(self->ctx),
3442 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3443 );
Christian Heimesefff7062013-11-21 03:35:02 +01003444 }
3445 if (cert == NULL) {
3446 break;
3447 }
3448 r = X509_STORE_add_cert(store, cert);
3449 X509_free(cert);
3450 if (!r) {
3451 err = ERR_peek_last_error();
3452 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3453 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3454 /* cert already in hash table, not an error */
3455 ERR_clear_error();
3456 } else {
3457 break;
3458 }
3459 }
3460 loaded++;
3461 }
3462
3463 err = ERR_peek_last_error();
3464 if ((filetype == SSL_FILETYPE_ASN1) &&
3465 (loaded > 0) &&
3466 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3467 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3468 /* EOF ASN1 file, not an error */
3469 ERR_clear_error();
3470 retval = 0;
3471 } else if ((filetype == SSL_FILETYPE_PEM) &&
3472 (loaded > 0) &&
3473 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3474 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3475 /* EOF PEM file, not an error */
3476 ERR_clear_error();
3477 retval = 0;
3478 } else {
3479 _setSSLError(NULL, 0, __FILE__, __LINE__);
3480 retval = -1;
3481 }
3482
3483 BIO_free(biobuf);
3484 return retval;
3485}
3486
3487
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003488/*[clinic input]
3489_ssl._SSLContext.load_verify_locations
3490 cafile: object = NULL
3491 capath: object = NULL
3492 cadata: object = NULL
3493
3494[clinic start generated code]*/
3495
Antoine Pitrou152efa22010-05-16 18:19:27 +00003496static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003497_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3498 PyObject *cafile,
3499 PyObject *capath,
3500 PyObject *cadata)
3501/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003502{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003503 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3504 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003505 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003506
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003507 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003508 if (cafile == Py_None)
3509 cafile = NULL;
3510 if (capath == Py_None)
3511 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003512 if (cadata == Py_None)
3513 cadata = NULL;
3514
3515 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003516 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003517 "cafile, capath and cadata cannot be all omitted");
3518 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003519 }
3520 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3521 PyErr_SetString(PyExc_TypeError,
3522 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003523 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003524 }
3525 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003526 PyErr_SetString(PyExc_TypeError,
3527 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003528 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003529 }
Christian Heimesefff7062013-11-21 03:35:02 +01003530
3531 /* validata cadata type and load cadata */
3532 if (cadata) {
3533 Py_buffer buf;
3534 PyObject *cadata_ascii = NULL;
3535
3536 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3537 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3538 PyBuffer_Release(&buf);
3539 PyErr_SetString(PyExc_TypeError,
3540 "cadata should be a contiguous buffer with "
3541 "a single dimension");
3542 goto error;
3543 }
3544 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3545 PyBuffer_Release(&buf);
3546 if (r == -1) {
3547 goto error;
3548 }
3549 } else {
3550 PyErr_Clear();
3551 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3552 if (cadata_ascii == NULL) {
3553 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003554 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003555 "bytes-like object");
3556 goto error;
3557 }
3558 r = _add_ca_certs(self,
3559 PyBytes_AS_STRING(cadata_ascii),
3560 PyBytes_GET_SIZE(cadata_ascii),
3561 SSL_FILETYPE_PEM);
3562 Py_DECREF(cadata_ascii);
3563 if (r == -1) {
3564 goto error;
3565 }
3566 }
3567 }
3568
3569 /* load cafile or capath */
3570 if (cafile || capath) {
3571 if (cafile)
3572 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3573 if (capath)
3574 capath_buf = PyBytes_AS_STRING(capath_bytes);
3575 PySSL_BEGIN_ALLOW_THREADS
3576 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3577 PySSL_END_ALLOW_THREADS
3578 if (r != 1) {
3579 ok = 0;
3580 if (errno != 0) {
3581 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003582 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003583 }
3584 else {
3585 _setSSLError(NULL, 0, __FILE__, __LINE__);
3586 }
3587 goto error;
3588 }
3589 }
3590 goto end;
3591
3592 error:
3593 ok = 0;
3594 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003595 Py_XDECREF(cafile_bytes);
3596 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003597 if (ok) {
3598 Py_RETURN_NONE;
3599 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003600 return NULL;
3601 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003602}
3603
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003604/*[clinic input]
3605_ssl._SSLContext.load_dh_params
3606 path as filepath: object
3607 /
3608
3609[clinic start generated code]*/
3610
Antoine Pitrou152efa22010-05-16 18:19:27 +00003611static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003612_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3613/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003614{
3615 FILE *f;
3616 DH *dh;
3617
Victor Stinnerdaf45552013-08-28 00:53:59 +02003618 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003619 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003620 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003621
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003622 errno = 0;
3623 PySSL_BEGIN_ALLOW_THREADS
3624 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003625 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003626 PySSL_END_ALLOW_THREADS
3627 if (dh == NULL) {
3628 if (errno != 0) {
3629 ERR_clear_error();
3630 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3631 }
3632 else {
3633 _setSSLError(NULL, 0, __FILE__, __LINE__);
3634 }
3635 return NULL;
3636 }
3637 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3638 _setSSLError(NULL, 0, __FILE__, __LINE__);
3639 DH_free(dh);
3640 Py_RETURN_NONE;
3641}
3642
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003643/*[clinic input]
3644_ssl._SSLContext._wrap_socket
3645 sock: object(subclass_of="PySocketModule.Sock_Type")
3646 server_side: int
3647 server_hostname as hostname_obj: object = None
3648
3649[clinic start generated code]*/
3650
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003651static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003652_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3653 int server_side, PyObject *hostname_obj)
3654/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003655{
Antoine Pitroud5323212010-10-22 18:19:07 +00003656 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003657 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003658
Antoine Pitroud5323212010-10-22 18:19:07 +00003659 /* server_hostname is either None (or absent), or to be encoded
3660 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003661 if (hostname_obj != Py_None) {
3662 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003663 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003664 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003665
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003666 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3667 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003668 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003669 if (hostname != NULL)
3670 PyMem_Free(hostname);
3671 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003672}
3673
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003674/*[clinic input]
3675_ssl._SSLContext._wrap_bio
3676 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3677 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3678 server_side: int
3679 server_hostname as hostname_obj: object = None
3680
3681[clinic start generated code]*/
3682
Antoine Pitroub0182c82010-10-12 20:09:02 +00003683static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003684_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3685 PySSLMemoryBIO *outgoing, int server_side,
3686 PyObject *hostname_obj)
3687/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003688{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003689 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003690 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003691
3692 /* server_hostname is either None (or absent), or to be encoded
3693 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003694 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003695 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3696 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003697 }
3698
3699 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3700 incoming, outgoing);
3701
3702 PyMem_Free(hostname);
3703 return res;
3704}
3705
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003706/*[clinic input]
3707_ssl._SSLContext.session_stats
3708[clinic start generated code]*/
3709
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003710static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003711_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3712/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003713{
3714 int r;
3715 PyObject *value, *stats = PyDict_New();
3716 if (!stats)
3717 return NULL;
3718
3719#define ADD_STATS(SSL_NAME, KEY_NAME) \
3720 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3721 if (value == NULL) \
3722 goto error; \
3723 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3724 Py_DECREF(value); \
3725 if (r < 0) \
3726 goto error;
3727
3728 ADD_STATS(number, "number");
3729 ADD_STATS(connect, "connect");
3730 ADD_STATS(connect_good, "connect_good");
3731 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3732 ADD_STATS(accept, "accept");
3733 ADD_STATS(accept_good, "accept_good");
3734 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3735 ADD_STATS(accept, "accept");
3736 ADD_STATS(hits, "hits");
3737 ADD_STATS(misses, "misses");
3738 ADD_STATS(timeouts, "timeouts");
3739 ADD_STATS(cache_full, "cache_full");
3740
3741#undef ADD_STATS
3742
3743 return stats;
3744
3745error:
3746 Py_DECREF(stats);
3747 return NULL;
3748}
3749
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003750/*[clinic input]
3751_ssl._SSLContext.set_default_verify_paths
3752[clinic start generated code]*/
3753
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003754static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003755_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3756/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003757{
3758 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3759 _setSSLError(NULL, 0, __FILE__, __LINE__);
3760 return NULL;
3761 }
3762 Py_RETURN_NONE;
3763}
3764
Antoine Pitrou501da612011-12-21 09:27:41 +01003765#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003766/*[clinic input]
3767_ssl._SSLContext.set_ecdh_curve
3768 name: object
3769 /
3770
3771[clinic start generated code]*/
3772
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003773static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003774_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3775/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003776{
3777 PyObject *name_bytes;
3778 int nid;
3779 EC_KEY *key;
3780
3781 if (!PyUnicode_FSConverter(name, &name_bytes))
3782 return NULL;
3783 assert(PyBytes_Check(name_bytes));
3784 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3785 Py_DECREF(name_bytes);
3786 if (nid == 0) {
3787 PyErr_Format(PyExc_ValueError,
3788 "unknown elliptic curve name %R", name);
3789 return NULL;
3790 }
3791 key = EC_KEY_new_by_curve_name(nid);
3792 if (key == NULL) {
3793 _setSSLError(NULL, 0, __FILE__, __LINE__);
3794 return NULL;
3795 }
3796 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3797 EC_KEY_free(key);
3798 Py_RETURN_NONE;
3799}
Antoine Pitrou501da612011-12-21 09:27:41 +01003800#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003801
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003802#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003803static int
3804_servername_callback(SSL *s, int *al, void *args)
3805{
3806 int ret;
3807 PySSLContext *ssl_ctx = (PySSLContext *) args;
3808 PySSLSocket *ssl;
3809 PyObject *servername_o;
3810 PyObject *servername_idna;
3811 PyObject *result;
3812 /* The high-level ssl.SSLSocket object */
3813 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003814 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003815 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003816
3817 if (ssl_ctx->set_hostname == NULL) {
3818 /* remove race condition in this the call back while if removing the
3819 * callback is in progress */
3820 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003821 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003822 }
3823
3824 ssl = SSL_get_app_data(s);
3825 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003826
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003827 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003828 * SSL connection and that has a .context attribute that can be changed to
3829 * identify the requested hostname. Since the official API is the Python
3830 * level API we want to pass the callback a Python level object rather than
3831 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3832 * SSLObject) that will be passed. Otherwise if there's a socket then that
3833 * will be passed. If both do not exist only then the C-level object is
3834 * passed. */
3835 if (ssl->owner)
3836 ssl_socket = PyWeakref_GetObject(ssl->owner);
3837 else if (ssl->Socket)
3838 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3839 else
3840 ssl_socket = (PyObject *) ssl;
3841
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003842 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003843 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003844 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003845
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003846 if (servername == NULL) {
3847 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3848 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003849 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003850 else {
3851 servername_o = PyBytes_FromString(servername);
3852 if (servername_o == NULL) {
3853 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3854 goto error;
3855 }
3856 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3857 if (servername_idna == NULL) {
3858 PyErr_WriteUnraisable(servername_o);
3859 Py_DECREF(servername_o);
3860 goto error;
3861 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003862 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003863 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3864 servername_idna, ssl_ctx, NULL);
3865 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003866 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003867 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003868
3869 if (result == NULL) {
3870 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3871 *al = SSL_AD_HANDSHAKE_FAILURE;
3872 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3873 }
3874 else {
3875 if (result != Py_None) {
3876 *al = (int) PyLong_AsLong(result);
3877 if (PyErr_Occurred()) {
3878 PyErr_WriteUnraisable(result);
3879 *al = SSL_AD_INTERNAL_ERROR;
3880 }
3881 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3882 }
3883 else {
3884 ret = SSL_TLSEXT_ERR_OK;
3885 }
3886 Py_DECREF(result);
3887 }
3888
3889 PyGILState_Release(gstate);
3890 return ret;
3891
3892error:
3893 Py_DECREF(ssl_socket);
3894 *al = SSL_AD_INTERNAL_ERROR;
3895 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3896 PyGILState_Release(gstate);
3897 return ret;
3898}
Antoine Pitroua5963382013-03-30 16:39:00 +01003899#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003900
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003901/*[clinic input]
3902_ssl._SSLContext.set_servername_callback
3903 method as cb: object
3904 /
3905
3906Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3907
3908If the argument is None then the callback is disabled. The method is called
3909with the SSLSocket, the server name as a string, and the SSLContext object.
3910See RFC 6066 for details of the SNI extension.
3911[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003912
3913static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003914_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3915/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003916{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003917#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003918 Py_CLEAR(self->set_hostname);
3919 if (cb == Py_None) {
3920 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3921 }
3922 else {
3923 if (!PyCallable_Check(cb)) {
3924 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3925 PyErr_SetString(PyExc_TypeError,
3926 "not a callable object");
3927 return NULL;
3928 }
3929 Py_INCREF(cb);
3930 self->set_hostname = cb;
3931 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3932 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3933 }
3934 Py_RETURN_NONE;
3935#else
3936 PyErr_SetString(PyExc_NotImplementedError,
3937 "The TLS extension servername callback, "
3938 "SSL_CTX_set_tlsext_servername_callback, "
3939 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003940 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003941#endif
3942}
3943
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003944/*[clinic input]
3945_ssl._SSLContext.cert_store_stats
3946
3947Returns quantities of loaded X.509 certificates.
3948
3949X.509 certificates with a CA extension and certificate revocation lists
3950inside the context's cert store.
3951
3952NOTE: Certificates in a capath directory aren't loaded unless they have
3953been used at least once.
3954[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003955
3956static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003957_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3958/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003959{
3960 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003961 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003962 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003963 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003964
3965 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003966 objs = X509_STORE_get0_objects(store);
3967 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3968 obj = sk_X509_OBJECT_value(objs, i);
3969 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003970 case X509_LU_X509:
3971 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003972 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003973 ca++;
3974 }
3975 break;
3976 case X509_LU_CRL:
3977 crl++;
3978 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003979 default:
3980 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3981 * As far as I can tell they are internal states and never
3982 * stored in a cert store */
3983 break;
3984 }
3985 }
3986 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3987 "x509_ca", ca);
3988}
3989
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003990/*[clinic input]
3991_ssl._SSLContext.get_ca_certs
3992 binary_form: bool = False
3993
3994Returns a list of dicts with information of loaded CA certs.
3995
3996If the optional argument is True, returns a DER-encoded copy of the CA
3997certificate.
3998
3999NOTE: Certificates in a capath directory aren't loaded unless they have
4000been used at least once.
4001[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004002
4003static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004004_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4005/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004006{
4007 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004008 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004009 PyObject *ci = NULL, *rlist = NULL;
4010 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004011
4012 if ((rlist = PyList_New(0)) == NULL) {
4013 return NULL;
4014 }
4015
4016 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004017 objs = X509_STORE_get0_objects(store);
4018 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004019 X509_OBJECT *obj;
4020 X509 *cert;
4021
Christian Heimes598894f2016-09-05 23:19:05 +02004022 obj = sk_X509_OBJECT_value(objs, i);
4023 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004024 /* not a x509 cert */
4025 continue;
4026 }
4027 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004028 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004029 if (!X509_check_ca(cert)) {
4030 continue;
4031 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004032 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004033 ci = _certificate_to_der(cert);
4034 } else {
4035 ci = _decode_certificate(cert);
4036 }
4037 if (ci == NULL) {
4038 goto error;
4039 }
4040 if (PyList_Append(rlist, ci) == -1) {
4041 goto error;
4042 }
4043 Py_CLEAR(ci);
4044 }
4045 return rlist;
4046
4047 error:
4048 Py_XDECREF(ci);
4049 Py_XDECREF(rlist);
4050 return NULL;
4051}
4052
4053
Antoine Pitrou152efa22010-05-16 18:19:27 +00004054static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004055 {"check_hostname", (getter) get_check_hostname,
4056 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004057 {"options", (getter) get_options,
4058 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004059 {"verify_flags", (getter) get_verify_flags,
4060 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004061 {"verify_mode", (getter) get_verify_mode,
4062 (setter) set_verify_mode, NULL},
4063 {NULL}, /* sentinel */
4064};
4065
4066static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004067 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4068 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4069 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4070 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4071 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4072 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4073 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4074 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4075 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4076 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4077 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4078 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4079 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4080 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004081 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004082 {NULL, NULL} /* sentinel */
4083};
4084
4085static PyTypeObject PySSLContext_Type = {
4086 PyVarObject_HEAD_INIT(NULL, 0)
4087 "_ssl._SSLContext", /*tp_name*/
4088 sizeof(PySSLContext), /*tp_basicsize*/
4089 0, /*tp_itemsize*/
4090 (destructor)context_dealloc, /*tp_dealloc*/
4091 0, /*tp_print*/
4092 0, /*tp_getattr*/
4093 0, /*tp_setattr*/
4094 0, /*tp_reserved*/
4095 0, /*tp_repr*/
4096 0, /*tp_as_number*/
4097 0, /*tp_as_sequence*/
4098 0, /*tp_as_mapping*/
4099 0, /*tp_hash*/
4100 0, /*tp_call*/
4101 0, /*tp_str*/
4102 0, /*tp_getattro*/
4103 0, /*tp_setattro*/
4104 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004105 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004106 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004107 (traverseproc) context_traverse, /*tp_traverse*/
4108 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004109 0, /*tp_richcompare*/
4110 0, /*tp_weaklistoffset*/
4111 0, /*tp_iter*/
4112 0, /*tp_iternext*/
4113 context_methods, /*tp_methods*/
4114 0, /*tp_members*/
4115 context_getsetlist, /*tp_getset*/
4116 0, /*tp_base*/
4117 0, /*tp_dict*/
4118 0, /*tp_descr_get*/
4119 0, /*tp_descr_set*/
4120 0, /*tp_dictoffset*/
4121 0, /*tp_init*/
4122 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004123 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004124};
4125
4126
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004127/*
4128 * MemoryBIO objects
4129 */
4130
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004131/*[clinic input]
4132@classmethod
4133_ssl.MemoryBIO.__new__
4134
4135[clinic start generated code]*/
4136
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004137static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004138_ssl_MemoryBIO_impl(PyTypeObject *type)
4139/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004140{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004141 BIO *bio;
4142 PySSLMemoryBIO *self;
4143
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004144 bio = BIO_new(BIO_s_mem());
4145 if (bio == NULL) {
4146 PyErr_SetString(PySSLErrorObject,
4147 "failed to allocate BIO");
4148 return NULL;
4149 }
4150 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4151 * just that no data is currently available. The SSL routines should retry
4152 * the read, which we can achieve by calling BIO_set_retry_read(). */
4153 BIO_set_retry_read(bio);
4154 BIO_set_mem_eof_return(bio, -1);
4155
4156 assert(type != NULL && type->tp_alloc != NULL);
4157 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4158 if (self == NULL) {
4159 BIO_free(bio);
4160 return NULL;
4161 }
4162 self->bio = bio;
4163 self->eof_written = 0;
4164
4165 return (PyObject *) self;
4166}
4167
4168static void
4169memory_bio_dealloc(PySSLMemoryBIO *self)
4170{
4171 BIO_free(self->bio);
4172 Py_TYPE(self)->tp_free(self);
4173}
4174
4175static PyObject *
4176memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4177{
Segev Finer5cff6372017-07-27 01:19:17 +03004178 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179}
4180
4181PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4182"The number of bytes pending in the memory BIO.");
4183
4184static PyObject *
4185memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4186{
4187 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4188 && self->eof_written);
4189}
4190
4191PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4192"Whether the memory BIO is at EOF.");
4193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194/*[clinic input]
4195_ssl.MemoryBIO.read
4196 size as len: int = -1
4197 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004199Read up to size bytes from the memory BIO.
4200
4201If size is not specified, read the entire buffer.
4202If the return value is an empty bytes instance, this means either
4203EOF or that no data is available. Use the "eof" property to
4204distinguish between the two.
4205[clinic start generated code]*/
4206
4207static PyObject *
4208_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4209/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4210{
4211 int avail, nbytes;
4212 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213
Segev Finer5cff6372017-07-27 01:19:17 +03004214 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004215 if ((len < 0) || (len > avail))
4216 len = avail;
4217
4218 result = PyBytes_FromStringAndSize(NULL, len);
4219 if ((result == NULL) || (len == 0))
4220 return result;
4221
4222 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4223 /* There should never be any short reads but check anyway. */
4224 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4225 Py_DECREF(result);
4226 return NULL;
4227 }
4228
4229 return result;
4230}
4231
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004232/*[clinic input]
4233_ssl.MemoryBIO.write
4234 b: Py_buffer
4235 /
4236
4237Writes the bytes b into the memory BIO.
4238
4239Returns the number of bytes written.
4240[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004241
4242static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004243_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4244/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004245{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004246 int nbytes;
4247
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004248 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004249 PyErr_Format(PyExc_OverflowError,
4250 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004251 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004252 }
4253
4254 if (self->eof_written) {
4255 PyErr_SetString(PySSLErrorObject,
4256 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004257 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004258 }
4259
Segev Finer5cff6372017-07-27 01:19:17 +03004260 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004261 if (nbytes < 0) {
4262 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004263 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004264 }
4265
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004266 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004267}
4268
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004269/*[clinic input]
4270_ssl.MemoryBIO.write_eof
4271
4272Write an EOF marker to the memory BIO.
4273
4274When all data has been read, the "eof" property will be True.
4275[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004276
4277static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004278_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4279/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004280{
4281 self->eof_written = 1;
4282 /* After an EOF is written, a zero return from read() should be a real EOF
4283 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4284 BIO_clear_retry_flags(self->bio);
4285 BIO_set_mem_eof_return(self->bio, 0);
4286
4287 Py_RETURN_NONE;
4288}
4289
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004290static PyGetSetDef memory_bio_getsetlist[] = {
4291 {"pending", (getter) memory_bio_get_pending, NULL,
4292 PySSL_memory_bio_pending_doc},
4293 {"eof", (getter) memory_bio_get_eof, NULL,
4294 PySSL_memory_bio_eof_doc},
4295 {NULL}, /* sentinel */
4296};
4297
4298static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004299 _SSL_MEMORYBIO_READ_METHODDEF
4300 _SSL_MEMORYBIO_WRITE_METHODDEF
4301 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004302 {NULL, NULL} /* sentinel */
4303};
4304
4305static PyTypeObject PySSLMemoryBIO_Type = {
4306 PyVarObject_HEAD_INIT(NULL, 0)
4307 "_ssl.MemoryBIO", /*tp_name*/
4308 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4309 0, /*tp_itemsize*/
4310 (destructor)memory_bio_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*/
4325 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4326 0, /*tp_doc*/
4327 0, /*tp_traverse*/
4328 0, /*tp_clear*/
4329 0, /*tp_richcompare*/
4330 0, /*tp_weaklistoffset*/
4331 0, /*tp_iter*/
4332 0, /*tp_iternext*/
4333 memory_bio_methods, /*tp_methods*/
4334 0, /*tp_members*/
4335 memory_bio_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_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004344};
4345
Antoine Pitrou152efa22010-05-16 18:19:27 +00004346
Christian Heimes99a65702016-09-10 23:44:53 +02004347/*
4348 * SSL Session object
4349 */
4350
4351static void
4352PySSLSession_dealloc(PySSLSession *self)
4353{
INADA Naokia6296d32017-08-24 14:55:17 +09004354 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004355 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004356 Py_XDECREF(self->ctx);
4357 if (self->session != NULL) {
4358 SSL_SESSION_free(self->session);
4359 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004360 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004361}
4362
4363static PyObject *
4364PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4365{
4366 int result;
4367
4368 if (left == NULL || right == NULL) {
4369 PyErr_BadInternalCall();
4370 return NULL;
4371 }
4372
4373 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4374 Py_RETURN_NOTIMPLEMENTED;
4375 }
4376
4377 if (left == right) {
4378 result = 0;
4379 } else {
4380 const unsigned char *left_id, *right_id;
4381 unsigned int left_len, right_len;
4382 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4383 &left_len);
4384 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4385 &right_len);
4386 if (left_len == right_len) {
4387 result = memcmp(left_id, right_id, left_len);
4388 } else {
4389 result = 1;
4390 }
4391 }
4392
4393 switch (op) {
4394 case Py_EQ:
4395 if (result == 0) {
4396 Py_RETURN_TRUE;
4397 } else {
4398 Py_RETURN_FALSE;
4399 }
4400 break;
4401 case Py_NE:
4402 if (result != 0) {
4403 Py_RETURN_TRUE;
4404 } else {
4405 Py_RETURN_FALSE;
4406 }
4407 break;
4408 case Py_LT:
4409 case Py_LE:
4410 case Py_GT:
4411 case Py_GE:
4412 Py_RETURN_NOTIMPLEMENTED;
4413 break;
4414 default:
4415 PyErr_BadArgument();
4416 return NULL;
4417 }
4418}
4419
4420static int
4421PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4422{
4423 Py_VISIT(self->ctx);
4424 return 0;
4425}
4426
4427static int
4428PySSLSession_clear(PySSLSession *self)
4429{
4430 Py_CLEAR(self->ctx);
4431 return 0;
4432}
4433
4434
4435static PyObject *
4436PySSLSession_get_time(PySSLSession *self, void *closure) {
4437 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4438}
4439
4440PyDoc_STRVAR(PySSLSession_get_time_doc,
4441"Session creation time (seconds since epoch).");
4442
4443
4444static PyObject *
4445PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4446 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4447}
4448
4449PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4450"Session timeout (delta in seconds).");
4451
4452
4453static PyObject *
4454PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4455 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4456 return PyLong_FromUnsignedLong(hint);
4457}
4458
4459PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4460"Ticket life time hint.");
4461
4462
4463static PyObject *
4464PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4465 const unsigned char *id;
4466 unsigned int len;
4467 id = SSL_SESSION_get_id(self->session, &len);
4468 return PyBytes_FromStringAndSize((const char *)id, len);
4469}
4470
4471PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4472"Session id");
4473
4474
4475static PyObject *
4476PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4477 if (SSL_SESSION_has_ticket(self->session)) {
4478 Py_RETURN_TRUE;
4479 } else {
4480 Py_RETURN_FALSE;
4481 }
4482}
4483
4484PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4485"Does the session contain a ticket?");
4486
4487
4488static PyGetSetDef PySSLSession_getsetlist[] = {
4489 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4490 PySSLSession_get_has_ticket_doc},
4491 {"id", (getter) PySSLSession_get_session_id, NULL,
4492 PySSLSession_get_session_id_doc},
4493 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4494 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4495 {"time", (getter) PySSLSession_get_time, NULL,
4496 PySSLSession_get_time_doc},
4497 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4498 PySSLSession_get_timeout_doc},
4499 {NULL}, /* sentinel */
4500};
4501
4502static PyTypeObject PySSLSession_Type = {
4503 PyVarObject_HEAD_INIT(NULL, 0)
4504 "_ssl.Session", /*tp_name*/
4505 sizeof(PySSLSession), /*tp_basicsize*/
4506 0, /*tp_itemsize*/
4507 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4508 0, /*tp_print*/
4509 0, /*tp_getattr*/
4510 0, /*tp_setattr*/
4511 0, /*tp_reserved*/
4512 0, /*tp_repr*/
4513 0, /*tp_as_number*/
4514 0, /*tp_as_sequence*/
4515 0, /*tp_as_mapping*/
4516 0, /*tp_hash*/
4517 0, /*tp_call*/
4518 0, /*tp_str*/
4519 0, /*tp_getattro*/
4520 0, /*tp_setattro*/
4521 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004522 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004523 0, /*tp_doc*/
4524 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4525 (inquiry)PySSLSession_clear, /*tp_clear*/
4526 PySSLSession_richcompare, /*tp_richcompare*/
4527 0, /*tp_weaklistoffset*/
4528 0, /*tp_iter*/
4529 0, /*tp_iternext*/
4530 0, /*tp_methods*/
4531 0, /*tp_members*/
4532 PySSLSession_getsetlist, /*tp_getset*/
4533};
4534
4535
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004536/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004537/*[clinic input]
4538_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004539 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004540 entropy: double
4541 /
4542
4543Mix string into the OpenSSL PRNG state.
4544
4545entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304546string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004547[clinic start generated code]*/
4548
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004549static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004550_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004551/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004552{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004553 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004554 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004555
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004556 buf = (const char *)view->buf;
4557 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004558 do {
4559 written = Py_MIN(len, INT_MAX);
4560 RAND_add(buf, (int)written, entropy);
4561 buf += written;
4562 len -= written;
4563 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004564 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004565}
4566
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004567static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004568PySSL_RAND(int len, int pseudo)
4569{
4570 int ok;
4571 PyObject *bytes;
4572 unsigned long err;
4573 const char *errstr;
4574 PyObject *v;
4575
Victor Stinner1e81a392013-12-19 16:47:04 +01004576 if (len < 0) {
4577 PyErr_SetString(PyExc_ValueError, "num must be positive");
4578 return NULL;
4579 }
4580
Victor Stinner99c8b162011-05-24 12:05:19 +02004581 bytes = PyBytes_FromStringAndSize(NULL, len);
4582 if (bytes == NULL)
4583 return NULL;
4584 if (pseudo) {
4585 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4586 if (ok == 0 || ok == 1)
4587 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4588 }
4589 else {
4590 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4591 if (ok == 1)
4592 return bytes;
4593 }
4594 Py_DECREF(bytes);
4595
4596 err = ERR_get_error();
4597 errstr = ERR_reason_error_string(err);
4598 v = Py_BuildValue("(ks)", err, errstr);
4599 if (v != NULL) {
4600 PyErr_SetObject(PySSLErrorObject, v);
4601 Py_DECREF(v);
4602 }
4603 return NULL;
4604}
4605
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004606/*[clinic input]
4607_ssl.RAND_bytes
4608 n: int
4609 /
4610
4611Generate n cryptographically strong pseudo-random bytes.
4612[clinic start generated code]*/
4613
Victor Stinner99c8b162011-05-24 12:05:19 +02004614static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004615_ssl_RAND_bytes_impl(PyObject *module, int n)
4616/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004617{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004618 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004619}
4620
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004621/*[clinic input]
4622_ssl.RAND_pseudo_bytes
4623 n: int
4624 /
4625
4626Generate n pseudo-random bytes.
4627
4628Return a pair (bytes, is_cryptographic). is_cryptographic is True
4629if the bytes generated are cryptographically strong.
4630[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004631
4632static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004633_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4634/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004635{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004636 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004637}
4638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004639/*[clinic input]
4640_ssl.RAND_status
4641
4642Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4643
4644It is necessary to seed the PRNG with RAND_add() on some platforms before
4645using the ssl() function.
4646[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004647
4648static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004649_ssl_RAND_status_impl(PyObject *module)
4650/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004651{
Christian Heimes217cfd12007-12-02 14:31:20 +00004652 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004653}
4654
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004655#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004656/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004657/*[clinic input]
4658_ssl.RAND_egd
4659 path: object(converter="PyUnicode_FSConverter")
4660 /
4661
4662Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4663
4664Returns number of bytes read. Raises SSLError if connection to EGD
4665fails or if it does not provide enough data to seed PRNG.
4666[clinic start generated code]*/
4667
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004668static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004669_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4670/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004671{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004672 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004673 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004674 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004675 PyErr_SetString(PySSLErrorObject,
4676 "EGD connection failed or EGD did not return "
4677 "enough data to seed the PRNG");
4678 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004679 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004680 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004681}
Christian Heimesa5d07652016-09-24 10:48:05 +02004682/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004683#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004684
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004685
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004686
4687/*[clinic input]
4688_ssl.get_default_verify_paths
4689
4690Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4691
4692The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4693[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004694
4695static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004696_ssl_get_default_verify_paths_impl(PyObject *module)
4697/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004698{
4699 PyObject *ofile_env = NULL;
4700 PyObject *ofile = NULL;
4701 PyObject *odir_env = NULL;
4702 PyObject *odir = NULL;
4703
Benjamin Petersond113c962015-07-18 10:59:13 -07004704#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004705 const char *tmp = (info); \
4706 target = NULL; \
4707 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4708 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4709 target = PyBytes_FromString(tmp); } \
4710 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004711 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004712
Benjamin Petersond113c962015-07-18 10:59:13 -07004713 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4714 CONVERT(X509_get_default_cert_file(), ofile);
4715 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4716 CONVERT(X509_get_default_cert_dir(), odir);
4717#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004718
Christian Heimes200bb1b2013-06-14 15:14:29 +02004719 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004720
4721 error:
4722 Py_XDECREF(ofile_env);
4723 Py_XDECREF(ofile);
4724 Py_XDECREF(odir_env);
4725 Py_XDECREF(odir);
4726 return NULL;
4727}
4728
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004729static PyObject*
4730asn1obj2py(ASN1_OBJECT *obj)
4731{
4732 int nid;
4733 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004734
4735 nid = OBJ_obj2nid(obj);
4736 if (nid == NID_undef) {
4737 PyErr_Format(PyExc_ValueError, "Unknown object");
4738 return NULL;
4739 }
4740 sn = OBJ_nid2sn(nid);
4741 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004742 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004743}
4744
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004745/*[clinic input]
4746_ssl.txt2obj
4747 txt: str
4748 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004749
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004750Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4751
4752By default objects are looked up by OID. With name=True short and
4753long name are also matched.
4754[clinic start generated code]*/
4755
4756static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004757_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4758/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004759{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004760 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004761 ASN1_OBJECT *obj;
4762
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004763 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4764 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004765 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004766 return NULL;
4767 }
4768 result = asn1obj2py(obj);
4769 ASN1_OBJECT_free(obj);
4770 return result;
4771}
4772
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004773/*[clinic input]
4774_ssl.nid2obj
4775 nid: int
4776 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004778Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4779[clinic start generated code]*/
4780
4781static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004782_ssl_nid2obj_impl(PyObject *module, int nid)
4783/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004784{
4785 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004786 ASN1_OBJECT *obj;
4787
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004788 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004789 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004790 return NULL;
4791 }
4792 obj = OBJ_nid2obj(nid);
4793 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004794 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004795 return NULL;
4796 }
4797 result = asn1obj2py(obj);
4798 ASN1_OBJECT_free(obj);
4799 return result;
4800}
4801
Christian Heimes46bebee2013-06-09 19:03:31 +02004802#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004803
4804static PyObject*
4805certEncodingType(DWORD encodingType)
4806{
4807 static PyObject *x509_asn = NULL;
4808 static PyObject *pkcs_7_asn = NULL;
4809
4810 if (x509_asn == NULL) {
4811 x509_asn = PyUnicode_InternFromString("x509_asn");
4812 if (x509_asn == NULL)
4813 return NULL;
4814 }
4815 if (pkcs_7_asn == NULL) {
4816 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4817 if (pkcs_7_asn == NULL)
4818 return NULL;
4819 }
4820 switch(encodingType) {
4821 case X509_ASN_ENCODING:
4822 Py_INCREF(x509_asn);
4823 return x509_asn;
4824 case PKCS_7_ASN_ENCODING:
4825 Py_INCREF(pkcs_7_asn);
4826 return pkcs_7_asn;
4827 default:
4828 return PyLong_FromLong(encodingType);
4829 }
4830}
4831
4832static PyObject*
4833parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4834{
4835 CERT_ENHKEY_USAGE *usage;
4836 DWORD size, error, i;
4837 PyObject *retval;
4838
4839 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4840 error = GetLastError();
4841 if (error == CRYPT_E_NOT_FOUND) {
4842 Py_RETURN_TRUE;
4843 }
4844 return PyErr_SetFromWindowsErr(error);
4845 }
4846
4847 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4848 if (usage == NULL) {
4849 return PyErr_NoMemory();
4850 }
4851
4852 /* Now get the actual enhanced usage property */
4853 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4854 PyMem_Free(usage);
4855 error = GetLastError();
4856 if (error == CRYPT_E_NOT_FOUND) {
4857 Py_RETURN_TRUE;
4858 }
4859 return PyErr_SetFromWindowsErr(error);
4860 }
4861 retval = PySet_New(NULL);
4862 if (retval == NULL) {
4863 goto error;
4864 }
4865 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4866 if (usage->rgpszUsageIdentifier[i]) {
4867 PyObject *oid;
4868 int err;
4869 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4870 if (oid == NULL) {
4871 Py_CLEAR(retval);
4872 goto error;
4873 }
4874 err = PySet_Add(retval, oid);
4875 Py_DECREF(oid);
4876 if (err == -1) {
4877 Py_CLEAR(retval);
4878 goto error;
4879 }
4880 }
4881 }
4882 error:
4883 PyMem_Free(usage);
4884 return retval;
4885}
4886
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004887/*[clinic input]
4888_ssl.enum_certificates
4889 store_name: str
4890
4891Retrieve certificates from Windows' cert store.
4892
4893store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4894more cert storages, too. The function returns a list of (bytes,
4895encoding_type, trust) tuples. The encoding_type flag can be interpreted
4896with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4897a set of OIDs or the boolean True.
4898[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004899
Christian Heimes46bebee2013-06-09 19:03:31 +02004900static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004901_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4902/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004903{
Christian Heimes46bebee2013-06-09 19:03:31 +02004904 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004905 PCCERT_CONTEXT pCertCtx = NULL;
4906 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004907 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004908
Christian Heimes44109d72013-11-22 01:51:30 +01004909 result = PyList_New(0);
4910 if (result == NULL) {
4911 return NULL;
4912 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004913 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4914 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4915 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004916 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004917 Py_DECREF(result);
4918 return PyErr_SetFromWindowsErr(GetLastError());
4919 }
4920
Christian Heimes44109d72013-11-22 01:51:30 +01004921 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4922 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4923 pCertCtx->cbCertEncoded);
4924 if (!cert) {
4925 Py_CLEAR(result);
4926 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004927 }
Christian Heimes44109d72013-11-22 01:51:30 +01004928 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4929 Py_CLEAR(result);
4930 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004931 }
Christian Heimes44109d72013-11-22 01:51:30 +01004932 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4933 if (keyusage == Py_True) {
4934 Py_DECREF(keyusage);
4935 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004936 }
Christian Heimes44109d72013-11-22 01:51:30 +01004937 if (keyusage == NULL) {
4938 Py_CLEAR(result);
4939 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004940 }
Christian Heimes44109d72013-11-22 01:51:30 +01004941 if ((tup = PyTuple_New(3)) == NULL) {
4942 Py_CLEAR(result);
4943 break;
4944 }
4945 PyTuple_SET_ITEM(tup, 0, cert);
4946 cert = NULL;
4947 PyTuple_SET_ITEM(tup, 1, enc);
4948 enc = NULL;
4949 PyTuple_SET_ITEM(tup, 2, keyusage);
4950 keyusage = NULL;
4951 if (PyList_Append(result, tup) < 0) {
4952 Py_CLEAR(result);
4953 break;
4954 }
4955 Py_CLEAR(tup);
4956 }
4957 if (pCertCtx) {
4958 /* loop ended with an error, need to clean up context manually */
4959 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004960 }
4961
4962 /* In error cases cert, enc and tup may not be NULL */
4963 Py_XDECREF(cert);
4964 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004965 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004966 Py_XDECREF(tup);
4967
4968 if (!CertCloseStore(hStore, 0)) {
4969 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004970 Py_XDECREF(result);
4971 return PyErr_SetFromWindowsErr(GetLastError());
4972 }
4973 return result;
4974}
4975
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004976/*[clinic input]
4977_ssl.enum_crls
4978 store_name: str
4979
4980Retrieve CRLs from Windows' cert store.
4981
4982store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4983more cert storages, too. The function returns a list of (bytes,
4984encoding_type) tuples. The encoding_type flag can be interpreted with
4985X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4986[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004987
4988static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004989_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4990/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004991{
Christian Heimes44109d72013-11-22 01:51:30 +01004992 HCERTSTORE hStore = NULL;
4993 PCCRL_CONTEXT pCrlCtx = NULL;
4994 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4995 PyObject *result = NULL;
4996
Christian Heimes44109d72013-11-22 01:51:30 +01004997 result = PyList_New(0);
4998 if (result == NULL) {
4999 return NULL;
5000 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005001 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5002 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5003 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005004 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005005 Py_DECREF(result);
5006 return PyErr_SetFromWindowsErr(GetLastError());
5007 }
Christian Heimes44109d72013-11-22 01:51:30 +01005008
5009 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5010 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5011 pCrlCtx->cbCrlEncoded);
5012 if (!crl) {
5013 Py_CLEAR(result);
5014 break;
5015 }
5016 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5017 Py_CLEAR(result);
5018 break;
5019 }
5020 if ((tup = PyTuple_New(2)) == NULL) {
5021 Py_CLEAR(result);
5022 break;
5023 }
5024 PyTuple_SET_ITEM(tup, 0, crl);
5025 crl = NULL;
5026 PyTuple_SET_ITEM(tup, 1, enc);
5027 enc = NULL;
5028
5029 if (PyList_Append(result, tup) < 0) {
5030 Py_CLEAR(result);
5031 break;
5032 }
5033 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005034 }
Christian Heimes44109d72013-11-22 01:51:30 +01005035 if (pCrlCtx) {
5036 /* loop ended with an error, need to clean up context manually */
5037 CertFreeCRLContext(pCrlCtx);
5038 }
5039
5040 /* In error cases cert, enc and tup may not be NULL */
5041 Py_XDECREF(crl);
5042 Py_XDECREF(enc);
5043 Py_XDECREF(tup);
5044
5045 if (!CertCloseStore(hStore, 0)) {
5046 /* This error case might shadow another exception.*/
5047 Py_XDECREF(result);
5048 return PyErr_SetFromWindowsErr(GetLastError());
5049 }
5050 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005051}
Christian Heimes44109d72013-11-22 01:51:30 +01005052
5053#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005054
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005055/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005056static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005057 _SSL__TEST_DECODE_CERT_METHODDEF
5058 _SSL_RAND_ADD_METHODDEF
5059 _SSL_RAND_BYTES_METHODDEF
5060 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5061 _SSL_RAND_EGD_METHODDEF
5062 _SSL_RAND_STATUS_METHODDEF
5063 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5064 _SSL_ENUM_CERTIFICATES_METHODDEF
5065 _SSL_ENUM_CRLS_METHODDEF
5066 _SSL_TXT2OBJ_METHODDEF
5067 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005068 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005069};
5070
5071
Christian Heimes598894f2016-09-05 23:19:05 +02005072#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005073
5074/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005075 * of the Python C thread library
5076 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5077 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005078
5079static PyThread_type_lock *_ssl_locks = NULL;
5080
Christian Heimes4d98ca92013-08-19 17:36:29 +02005081#if OPENSSL_VERSION_NUMBER >= 0x10000000
5082/* use new CRYPTO_THREADID API. */
5083static void
5084_ssl_threadid_callback(CRYPTO_THREADID *id)
5085{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005086 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005087}
5088#else
5089/* deprecated CRYPTO_set_id_callback() API. */
5090static unsigned long
5091_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005092 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005093}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005094#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005095
Bill Janssen6e027db2007-11-15 22:23:56 +00005096static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005097 (int mode, int n, const char *file, int line) {
5098 /* this function is needed to perform locking on shared data
5099 structures. (Note that OpenSSL uses a number of global data
5100 structures that will be implicitly shared whenever multiple
5101 threads use OpenSSL.) Multi-threaded applications will
5102 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005103
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005104 locking_function() must be able to handle up to
5105 CRYPTO_num_locks() different mutex locks. It sets the n-th
5106 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005107
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005108 file and line are the file number of the function setting the
5109 lock. They can be useful for debugging.
5110 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005111
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005112 if ((_ssl_locks == NULL) ||
5113 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5114 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005115
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005116 if (mode & CRYPTO_LOCK) {
5117 PyThread_acquire_lock(_ssl_locks[n], 1);
5118 } else {
5119 PyThread_release_lock(_ssl_locks[n]);
5120 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005121}
5122
5123static int _setup_ssl_threads(void) {
5124
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005125 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005126
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005127 if (_ssl_locks == NULL) {
5128 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005129 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5130 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005131 if (_ssl_locks == NULL) {
5132 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005133 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005134 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005135 for (i = 0; i < _ssl_locks_count; i++) {
5136 _ssl_locks[i] = PyThread_allocate_lock();
5137 if (_ssl_locks[i] == NULL) {
5138 unsigned int j;
5139 for (j = 0; j < i; j++) {
5140 PyThread_free_lock(_ssl_locks[j]);
5141 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005142 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005143 return 0;
5144 }
5145 }
5146 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005147#if OPENSSL_VERSION_NUMBER >= 0x10000000
5148 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5149#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005150 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005151#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005152 }
5153 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154}
5155
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005156#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005157
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005158PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005159"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005160for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005161
Martin v. Löwis1a214512008-06-11 05:26:20 +00005162
5163static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005164 PyModuleDef_HEAD_INIT,
5165 "_ssl",
5166 module_doc,
5167 -1,
5168 PySSL_methods,
5169 NULL,
5170 NULL,
5171 NULL,
5172 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005173};
5174
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005175
5176static void
5177parse_openssl_version(unsigned long libver,
5178 unsigned int *major, unsigned int *minor,
5179 unsigned int *fix, unsigned int *patch,
5180 unsigned int *status)
5181{
5182 *status = libver & 0xF;
5183 libver >>= 4;
5184 *patch = libver & 0xFF;
5185 libver >>= 8;
5186 *fix = libver & 0xFF;
5187 libver >>= 8;
5188 *minor = libver & 0xFF;
5189 libver >>= 8;
5190 *major = libver & 0xFF;
5191}
5192
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005193PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005194PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005195{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005196 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005197 unsigned long libver;
5198 unsigned int major, minor, fix, patch, status;
5199 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005200 struct py_ssl_error_code *errcode;
5201 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005202
Antoine Pitrou152efa22010-05-16 18:19:27 +00005203 if (PyType_Ready(&PySSLContext_Type) < 0)
5204 return NULL;
5205 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005206 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005207 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5208 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005209 if (PyType_Ready(&PySSLSession_Type) < 0)
5210 return NULL;
5211
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005213 m = PyModule_Create(&_sslmodule);
5214 if (m == NULL)
5215 return NULL;
5216 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005218 /* Load _socket module and its C API */
5219 socket_api = PySocketModule_ImportModuleAndAPI();
5220 if (!socket_api)
5221 return NULL;
5222 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005223
Christian Heimesc941e622017-09-05 15:47:11 +02005224#ifndef OPENSSL_VERSION_1_1
5225 /* Load all algorithms and initialize cpuid */
5226 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005227 /* Init OpenSSL */
5228 SSL_load_error_strings();
5229 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005230#endif
5231
Christian Heimes598894f2016-09-05 23:19:05 +02005232#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005233 /* note that this will start threading if not already started */
5234 if (!_setup_ssl_threads()) {
5235 return NULL;
5236 }
Christian Heimes598894f2016-09-05 23:19:05 +02005237#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5238 /* OpenSSL 1.1.0 builtin thread support is enabled */
5239 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005240#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005241
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005242 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005243 sslerror_type_slots[0].pfunc = PyExc_OSError;
5244 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005245 if (PySSLErrorObject == NULL)
5246 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005247
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005248 /* ssl.CertificateError used to be a subclass of ValueError */
5249 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5250 if (bases == NULL)
5251 return NULL;
5252 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5253 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5254 bases, NULL);
5255 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005256 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5257 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5258 PySSLErrorObject, NULL);
5259 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5260 "ssl.SSLWantReadError", SSLWantReadError_doc,
5261 PySSLErrorObject, NULL);
5262 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5263 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5264 PySSLErrorObject, NULL);
5265 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5266 "ssl.SSLSyscallError", SSLSyscallError_doc,
5267 PySSLErrorObject, NULL);
5268 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5269 "ssl.SSLEOFError", SSLEOFError_doc,
5270 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005271 if (PySSLCertVerificationErrorObject == NULL
5272 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005273 || PySSLWantReadErrorObject == NULL
5274 || PySSLWantWriteErrorObject == NULL
5275 || PySSLSyscallErrorObject == NULL
5276 || PySSLEOFErrorObject == NULL)
5277 return NULL;
5278 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005279 || PyDict_SetItemString(d, "SSLCertVerificationError",
5280 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005281 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5282 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5283 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5284 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5285 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005286 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005287 if (PyDict_SetItemString(d, "_SSLContext",
5288 (PyObject *)&PySSLContext_Type) != 0)
5289 return NULL;
5290 if (PyDict_SetItemString(d, "_SSLSocket",
5291 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005292 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005293 if (PyDict_SetItemString(d, "MemoryBIO",
5294 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5295 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005296 if (PyDict_SetItemString(d, "SSLSession",
5297 (PyObject *)&PySSLSession_Type) != 0)
5298 return NULL;
5299
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005300 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5301 PY_SSL_ERROR_ZERO_RETURN);
5302 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5303 PY_SSL_ERROR_WANT_READ);
5304 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5305 PY_SSL_ERROR_WANT_WRITE);
5306 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5307 PY_SSL_ERROR_WANT_X509_LOOKUP);
5308 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5309 PY_SSL_ERROR_SYSCALL);
5310 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5311 PY_SSL_ERROR_SSL);
5312 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5313 PY_SSL_ERROR_WANT_CONNECT);
5314 /* non ssl.h errorcodes */
5315 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5316 PY_SSL_ERROR_EOF);
5317 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5318 PY_SSL_ERROR_INVALID_ERROR_CODE);
5319 /* cert requirements */
5320 PyModule_AddIntConstant(m, "CERT_NONE",
5321 PY_SSL_CERT_NONE);
5322 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5323 PY_SSL_CERT_OPTIONAL);
5324 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5325 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005326 /* CRL verification for verification_flags */
5327 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5328 0);
5329 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5330 X509_V_FLAG_CRL_CHECK);
5331 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5332 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5333 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5334 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005335#ifdef X509_V_FLAG_TRUSTED_FIRST
5336 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5337 X509_V_FLAG_TRUSTED_FIRST);
5338#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005339
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005340 /* Alert Descriptions from ssl.h */
5341 /* note RESERVED constants no longer intended for use have been removed */
5342 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5343
5344#define ADD_AD_CONSTANT(s) \
5345 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5346 SSL_AD_##s)
5347
5348 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5349 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5350 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5351 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5352 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5353 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5354 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5355 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5356 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5357 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5358 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5359 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5360 ADD_AD_CONSTANT(UNKNOWN_CA);
5361 ADD_AD_CONSTANT(ACCESS_DENIED);
5362 ADD_AD_CONSTANT(DECODE_ERROR);
5363 ADD_AD_CONSTANT(DECRYPT_ERROR);
5364 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5365 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5366 ADD_AD_CONSTANT(INTERNAL_ERROR);
5367 ADD_AD_CONSTANT(USER_CANCELLED);
5368 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005369 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005370#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5371 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5372#endif
5373#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5374 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5375#endif
5376#ifdef SSL_AD_UNRECOGNIZED_NAME
5377 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5378#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005379#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5380 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5381#endif
5382#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5383 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5384#endif
5385#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5386 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5387#endif
5388
5389#undef ADD_AD_CONSTANT
5390
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005391 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005392#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005393 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5394 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005395#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005396#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005397 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5398 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005399#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005400 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005401 PY_SSL_VERSION_TLS);
5402 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5403 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005404 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5405 PY_SSL_VERSION_TLS_CLIENT);
5406 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5407 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005408 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5409 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005410#if HAVE_TLSv1_2
5411 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5412 PY_SSL_VERSION_TLS1_1);
5413 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5414 PY_SSL_VERSION_TLS1_2);
5415#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005416
Antoine Pitroub5218772010-05-21 09:56:06 +00005417 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005418 PyModule_AddIntConstant(m, "OP_ALL",
5419 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005420 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5421 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5422 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005423#if HAVE_TLSv1_2
5424 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5425 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5426#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005427#ifdef SSL_OP_NO_TLSv1_3
5428 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5429#else
5430 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5431#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005432 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5433 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005434 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005435 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005436#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005437 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005438#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005439#ifdef SSL_OP_NO_COMPRESSION
5440 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5441 SSL_OP_NO_COMPRESSION);
5442#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005443
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005444#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005445 r = Py_True;
5446#else
5447 r = Py_False;
5448#endif
5449 Py_INCREF(r);
5450 PyModule_AddObject(m, "HAS_SNI", r);
5451
Antoine Pitroud6494802011-07-21 01:11:30 +02005452 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005453 Py_INCREF(r);
5454 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5455
Antoine Pitrou501da612011-12-21 09:27:41 +01005456#ifdef OPENSSL_NO_ECDH
5457 r = Py_False;
5458#else
5459 r = Py_True;
5460#endif
5461 Py_INCREF(r);
5462 PyModule_AddObject(m, "HAS_ECDH", r);
5463
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005464#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005465 r = Py_True;
5466#else
5467 r = Py_False;
5468#endif
5469 Py_INCREF(r);
5470 PyModule_AddObject(m, "HAS_NPN", r);
5471
Benjamin Petersoncca27322015-01-23 16:35:37 -05005472#ifdef HAVE_ALPN
5473 r = Py_True;
5474#else
5475 r = Py_False;
5476#endif
5477 Py_INCREF(r);
5478 PyModule_AddObject(m, "HAS_ALPN", r);
5479
Christian Heimescb5b68a2017-09-07 18:07:00 -07005480#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5481 r = Py_True;
5482#else
5483 r = Py_False;
5484#endif
5485 Py_INCREF(r);
5486 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5487
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005488 /* Mappings for error codes */
5489 err_codes_to_names = PyDict_New();
5490 err_names_to_codes = PyDict_New();
5491 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5492 return NULL;
5493 errcode = error_codes;
5494 while (errcode->mnemonic != NULL) {
5495 PyObject *mnemo, *key;
5496 mnemo = PyUnicode_FromString(errcode->mnemonic);
5497 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5498 if (mnemo == NULL || key == NULL)
5499 return NULL;
5500 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5501 return NULL;
5502 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5503 return NULL;
5504 Py_DECREF(key);
5505 Py_DECREF(mnemo);
5506 errcode++;
5507 }
5508 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5509 return NULL;
5510 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5511 return NULL;
5512
5513 lib_codes_to_names = PyDict_New();
5514 if (lib_codes_to_names == NULL)
5515 return NULL;
5516 libcode = library_codes;
5517 while (libcode->library != NULL) {
5518 PyObject *mnemo, *key;
5519 key = PyLong_FromLong(libcode->code);
5520 mnemo = PyUnicode_FromString(libcode->library);
5521 if (key == NULL || mnemo == NULL)
5522 return NULL;
5523 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5524 return NULL;
5525 Py_DECREF(key);
5526 Py_DECREF(mnemo);
5527 libcode++;
5528 }
5529 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5530 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005532 /* OpenSSL version */
5533 /* SSLeay() gives us the version of the library linked against,
5534 which could be different from the headers version.
5535 */
5536 libver = SSLeay();
5537 r = PyLong_FromUnsignedLong(libver);
5538 if (r == NULL)
5539 return NULL;
5540 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5541 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005542 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005543 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5544 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5545 return NULL;
5546 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5547 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5548 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005549
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005550 libver = OPENSSL_VERSION_NUMBER;
5551 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5552 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5553 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5554 return NULL;
5555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005556 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005557}