blob: 5ec31a773654960f147543b9a4e11f6e52d0074a [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) {
Christian Heimes09153602017-09-08 14:47:58 -0700488#ifdef X509_V_ERR_HOSTNAME_MISMATCH
489 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700490 case X509_V_ERR_HOSTNAME_MISMATCH:
491 verify_obj = PyUnicode_FromFormat(
492 "Hostname mismatch, certificate is not valid for '%S'.",
493 sslsock->server_hostname
494 );
495 break;
Christian Heimes09153602017-09-08 14:47:58 -0700496#endif
497#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700498 case X509_V_ERR_IP_ADDRESS_MISMATCH:
499 verify_obj = PyUnicode_FromFormat(
500 "IP address mismatch, certificate is not valid for '%S'.",
501 sslsock->server_hostname
502 );
503 break;
Christian Heimes09153602017-09-08 14:47:58 -0700504#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700505 default:
506 verify_str = X509_verify_cert_error_string(verify_code);
507 if (verify_str != NULL) {
508 verify_obj = PyUnicode_FromString(verify_str);
509 } else {
510 verify_obj = Py_None;
511 Py_INCREF(verify_obj);
512 }
513 break;
514 }
515 if (verify_obj == NULL) {
516 goto fail;
517 }
518 }
519
520 if (verify_obj && reason_obj && lib_obj)
521 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
522 lib_obj, reason_obj, errstr, verify_obj,
523 lineno);
524 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200525 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
526 lib_obj, reason_obj, errstr, lineno);
527 else if (lib_obj)
528 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
529 lib_obj, errstr, lineno);
530 else
531 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200532 if (msg == NULL)
533 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100534
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200535 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100536 if (init_value == NULL)
537 goto fail;
538
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200539 err_value = PyObject_CallObject(type, init_value);
540 Py_DECREF(init_value);
541 if (err_value == NULL)
542 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100543
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200544 if (reason_obj == NULL)
545 reason_obj = Py_None;
546 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
547 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700548
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200549 if (lib_obj == NULL)
550 lib_obj = Py_None;
551 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
552 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700553
554 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
555 /* Only set verify code / message for SSLCertVerificationError */
556 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
557 verify_code_obj))
558 goto fail;
559 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
560 goto fail;
561 }
562
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200563 PyErr_SetObject(type, err_value);
564fail:
565 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700566 Py_XDECREF(verify_code_obj);
567 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200568}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000569
570static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700571PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000572{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200573 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200574 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000575 int err;
576 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200577 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000578
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000579 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200580 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000581
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700582 if (sslsock->ssl != NULL) {
583 err = SSL_get_error(sslsock->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000584
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000585 switch (err) {
586 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200587 errstr = "TLS/SSL connection has been closed (EOF)";
588 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000589 p = PY_SSL_ERROR_ZERO_RETURN;
590 break;
591 case SSL_ERROR_WANT_READ:
592 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200593 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000594 p = PY_SSL_ERROR_WANT_READ;
595 break;
596 case SSL_ERROR_WANT_WRITE:
597 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200598 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 errstr = "The operation did not complete (write)";
600 break;
601 case SSL_ERROR_WANT_X509_LOOKUP:
602 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000603 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000604 break;
605 case SSL_ERROR_WANT_CONNECT:
606 p = PY_SSL_ERROR_WANT_CONNECT;
607 errstr = "The operation did not complete (connect)";
608 break;
609 case SSL_ERROR_SYSCALL:
610 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700612 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000613 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000614 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200615 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000616 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200617 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000618 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000619 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000620 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200621 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000622 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200623 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000625 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200626 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000627 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000628 }
629 } else {
630 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 }
632 break;
633 }
634 case SSL_ERROR_SSL:
635 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000636 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700637 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200638 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000639 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700640 }
641 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
642 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
643 type = PySSLCertVerificationErrorObject;
644 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000645 break;
646 }
647 default:
648 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
649 errstr = "Invalid error code";
650 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000651 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700652 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000653 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000654 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000655}
656
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000657static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200658_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000659
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200660 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000661 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200662 else
663 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700664 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000665 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000667}
668
Antoine Pitrou152efa22010-05-16 18:19:27 +0000669static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100670newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000671 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200672 char *server_hostname,
673 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000674{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000675 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100676 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200677 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000678
Antoine Pitrou152efa22010-05-16 18:19:27 +0000679 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 if (self == NULL)
681 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000682
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000684 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100685 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700686 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200687 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200688 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700689 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200690 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700691 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
692 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200693 if (hostname == NULL) {
694 Py_DECREF(self);
695 return NULL;
696 }
697 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700698 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200699
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000700 /* Make sure the SSL error state is initialized */
701 (void) ERR_get_state();
702 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000703
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000704 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000705 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000706 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200707 SSL_set_app_data(self->ssl, self);
708 if (sock) {
709 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
710 } else {
711 /* BIOs are reference counted and SSL_set_bio borrows our reference.
712 * To prevent a double free in memory_bio_dealloc() we need to take an
713 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200714 BIO_up_ref(inbio->bio);
715 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200716 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
717 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200718 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000719#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200720 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000721#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200722 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000723
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100724#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000725 if (server_hostname != NULL)
726 SSL_set_tlsext_host_name(self->ssl, server_hostname);
727#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000728 /* If the socket is in non-blocking mode or timeout mode, set the BIO
729 * to non-blocking mode (blocking is the default)
730 */
Victor Stinnere2452312015-03-28 03:00:46 +0100731 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000732 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
733 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
734 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 PySSL_BEGIN_ALLOW_THREADS
737 if (socket_type == PY_SSL_CLIENT)
738 SSL_set_connect_state(self->ssl);
739 else
740 SSL_set_accept_state(self->ssl);
741 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000742
Antoine Pitroud6494802011-07-21 01:11:30 +0200743 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200744 if (sock != NULL) {
745 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
746 if (self->Socket == NULL) {
747 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200748 return NULL;
749 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100750 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000751 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000752}
753
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000754/* SSL object methods */
755
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300756/*[clinic input]
757_ssl._SSLSocket.do_handshake
758[clinic start generated code]*/
759
760static PyObject *
761_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
762/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000763{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000764 int ret;
765 int err;
766 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200767 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200768 _PyTime_t timeout, deadline = 0;
769 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000770
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200771 if (sock) {
772 if (((PyObject*)sock) == Py_None) {
773 _setSSLError("Underlying socket connection gone",
774 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
775 return NULL;
776 }
777 Py_INCREF(sock);
778
779 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100780 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200781 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
782 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000784
Victor Stinner14690702015-04-06 22:46:13 +0200785 timeout = GET_SOCKET_TIMEOUT(sock);
786 has_timeout = (timeout > 0);
787 if (has_timeout)
788 deadline = _PyTime_GetMonotonicClock() + timeout;
789
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000790 /* Actually negotiate SSL connection */
791 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000793 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 ret = SSL_do_handshake(self->ssl);
795 err = SSL_get_error(self->ssl, ret);
796 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200797
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000798 if (PyErr_CheckSignals())
799 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200800
Victor Stinner14690702015-04-06 22:46:13 +0200801 if (has_timeout)
802 timeout = deadline - _PyTime_GetMonotonicClock();
803
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200805 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000806 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200807 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 } else {
809 sockstate = SOCKET_OPERATION_OK;
810 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200811
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000812 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000813 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000814 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000815 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
817 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000818 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000819 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000820 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
821 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000822 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000823 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000824 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
825 break;
826 }
827 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200828 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 if (ret < 1)
830 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000831
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200832 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000833
834error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200835 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000836 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000837}
838
Thomas Woutersed03b412007-08-28 21:37:11 +0000839static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300840_asn1obj2py(const ASN1_OBJECT *name, int no_name)
841{
842 char buf[X509_NAME_MAXLEN];
843 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300845 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000846
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300847 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000848 if (buflen < 0) {
849 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300850 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000851 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300852 /* initial buffer is too small for oid + terminating null byte */
853 if (buflen > X509_NAME_MAXLEN - 1) {
854 /* make OBJ_obj2txt() calculate the required buflen */
855 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
856 /* allocate len + 1 for terminating NULL byte */
857 namebuf = PyMem_Malloc(buflen + 1);
858 if (namebuf == NULL) {
859 PyErr_NoMemory();
860 return NULL;
861 }
862 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
863 if (buflen < 0) {
864 _setSSLError(NULL, 0, __FILE__, __LINE__);
865 goto done;
866 }
867 }
868 if (!buflen && no_name) {
869 Py_INCREF(Py_None);
870 name_obj = Py_None;
871 }
872 else {
873 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
874 }
875
876 done:
877 if (buf != namebuf) {
878 PyMem_Free(namebuf);
879 }
880 return name_obj;
881}
882
883static PyObject *
884_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
885{
886 Py_ssize_t buflen;
887 unsigned char *valuebuf = NULL;
888 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000890 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
891 if (buflen < 0) {
892 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300893 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000894 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300895 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000896 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000897 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000898}
899
900static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000901_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000902{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000903 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
904 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
905 PyObject *rdnt;
906 PyObject *attr = NULL; /* tuple to hold an attribute */
907 int entry_count = X509_NAME_entry_count(xname);
908 X509_NAME_ENTRY *entry;
909 ASN1_OBJECT *name;
910 ASN1_STRING *value;
911 int index_counter;
912 int rdn_level = -1;
913 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000914
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000915 dn = PyList_New(0);
916 if (dn == NULL)
917 return NULL;
918 /* now create another tuple to hold the top-level RDN */
919 rdn = PyList_New(0);
920 if (rdn == NULL)
921 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000923 for (index_counter = 0;
924 index_counter < entry_count;
925 index_counter++)
926 {
927 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000929 /* check to see if we've gotten to a new RDN */
930 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200931 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 /* yes, new RDN */
933 /* add old RDN to DN */
934 rdnt = PyList_AsTuple(rdn);
935 Py_DECREF(rdn);
936 if (rdnt == NULL)
937 goto fail0;
938 retcode = PyList_Append(dn, rdnt);
939 Py_DECREF(rdnt);
940 if (retcode < 0)
941 goto fail0;
942 /* create new RDN */
943 rdn = PyList_New(0);
944 if (rdn == NULL)
945 goto fail0;
946 }
947 }
Christian Heimes598894f2016-09-05 23:19:05 +0200948 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 /* now add this attribute to the current RDN */
951 name = X509_NAME_ENTRY_get_object(entry);
952 value = X509_NAME_ENTRY_get_data(entry);
953 attr = _create_tuple_for_attribute(name, value);
954 /*
955 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
956 entry->set,
957 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
958 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
959 */
960 if (attr == NULL)
961 goto fail1;
962 retcode = PyList_Append(rdn, attr);
963 Py_DECREF(attr);
964 if (retcode < 0)
965 goto fail1;
966 }
967 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100968 if (rdn != NULL) {
969 if (PyList_GET_SIZE(rdn) > 0) {
970 rdnt = PyList_AsTuple(rdn);
971 Py_DECREF(rdn);
972 if (rdnt == NULL)
973 goto fail0;
974 retcode = PyList_Append(dn, rdnt);
975 Py_DECREF(rdnt);
976 if (retcode < 0)
977 goto fail0;
978 }
979 else {
980 Py_DECREF(rdn);
981 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 /* convert list to tuple */
985 rdnt = PyList_AsTuple(dn);
986 Py_DECREF(dn);
987 if (rdnt == NULL)
988 return NULL;
989 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000990
991 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000993
994 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 Py_XDECREF(dn);
996 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000997}
998
999static PyObject *
1000_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001001
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001002 /* this code follows the procedure outlined in
1003 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1004 function to extract the STACK_OF(GENERAL_NAME),
1005 then iterates through the stack to add the
1006 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001007
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001008 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001009 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001010 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001011 GENERAL_NAMES *names = NULL;
1012 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001013 BIO *biobuf = NULL;
1014 char buf[2048];
1015 char *vptr;
1016 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 if (certificate == NULL)
1019 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001020
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001021 /* get a memory buffer */
1022 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001023
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001024 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1025 certificate, NID_subject_alt_name, NULL, NULL);
1026 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001027 if (peer_alt_names == Py_None) {
1028 peer_alt_names = PyList_New(0);
1029 if (peer_alt_names == NULL)
1030 goto fail;
1031 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001032
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001034 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001035 int gntype;
1036 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001037
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001038 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001039 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001040 switch (gntype) {
1041 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001042 /* we special-case DirName as a tuple of
1043 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 t = PyTuple_New(2);
1046 if (t == NULL) {
1047 goto fail;
1048 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 v = PyUnicode_FromString("DirName");
1051 if (v == NULL) {
1052 Py_DECREF(t);
1053 goto fail;
1054 }
1055 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001056
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001057 v = _create_tuple_for_X509_NAME (name->d.dirn);
1058 if (v == NULL) {
1059 Py_DECREF(t);
1060 goto fail;
1061 }
1062 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001063 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001064
Christian Heimes824f7f32013-08-17 00:54:47 +02001065 case GEN_EMAIL:
1066 case GEN_DNS:
1067 case GEN_URI:
1068 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1069 correctly, CVE-2013-4238 */
1070 t = PyTuple_New(2);
1071 if (t == NULL)
1072 goto fail;
1073 switch (gntype) {
1074 case GEN_EMAIL:
1075 v = PyUnicode_FromString("email");
1076 as = name->d.rfc822Name;
1077 break;
1078 case GEN_DNS:
1079 v = PyUnicode_FromString("DNS");
1080 as = name->d.dNSName;
1081 break;
1082 case GEN_URI:
1083 v = PyUnicode_FromString("URI");
1084 as = name->d.uniformResourceIdentifier;
1085 break;
1086 }
1087 if (v == NULL) {
1088 Py_DECREF(t);
1089 goto fail;
1090 }
1091 PyTuple_SET_ITEM(t, 0, v);
1092 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1093 ASN1_STRING_length(as));
1094 if (v == NULL) {
1095 Py_DECREF(t);
1096 goto fail;
1097 }
1098 PyTuple_SET_ITEM(t, 1, v);
1099 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001100
Christian Heimes1c03abd2016-09-06 23:25:35 +02001101 case GEN_RID:
1102 t = PyTuple_New(2);
1103 if (t == NULL)
1104 goto fail;
1105
1106 v = PyUnicode_FromString("Registered ID");
1107 if (v == NULL) {
1108 Py_DECREF(t);
1109 goto fail;
1110 }
1111 PyTuple_SET_ITEM(t, 0, v);
1112
1113 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1114 if (len < 0) {
1115 Py_DECREF(t);
1116 _setSSLError(NULL, 0, __FILE__, __LINE__);
1117 goto fail;
1118 } else if (len >= (int)sizeof(buf)) {
1119 v = PyUnicode_FromString("<INVALID>");
1120 } else {
1121 v = PyUnicode_FromStringAndSize(buf, len);
1122 }
1123 if (v == NULL) {
1124 Py_DECREF(t);
1125 goto fail;
1126 }
1127 PyTuple_SET_ITEM(t, 1, v);
1128 break;
1129
Christian Heimes824f7f32013-08-17 00:54:47 +02001130 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001132 switch (gntype) {
1133 /* check for new general name type */
1134 case GEN_OTHERNAME:
1135 case GEN_X400:
1136 case GEN_EDIPARTY:
1137 case GEN_IPADD:
1138 case GEN_RID:
1139 break;
1140 default:
1141 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1142 "Unknown general name type %d",
1143 gntype) == -1) {
1144 goto fail;
1145 }
1146 break;
1147 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001148 (void) BIO_reset(biobuf);
1149 GENERAL_NAME_print(biobuf, name);
1150 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1151 if (len < 0) {
1152 _setSSLError(NULL, 0, __FILE__, __LINE__);
1153 goto fail;
1154 }
1155 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001156 if (vptr == NULL) {
1157 PyErr_Format(PyExc_ValueError,
1158 "Invalid value %.200s",
1159 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001160 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001161 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001162 t = PyTuple_New(2);
1163 if (t == NULL)
1164 goto fail;
1165 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1166 if (v == NULL) {
1167 Py_DECREF(t);
1168 goto fail;
1169 }
1170 PyTuple_SET_ITEM(t, 0, v);
1171 v = PyUnicode_FromStringAndSize((vptr + 1),
1172 (len - (vptr - buf + 1)));
1173 if (v == NULL) {
1174 Py_DECREF(t);
1175 goto fail;
1176 }
1177 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001178 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001179 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001180
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001181 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001182
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001183 if (PyList_Append(peer_alt_names, t) < 0) {
1184 Py_DECREF(t);
1185 goto fail;
1186 }
1187 Py_DECREF(t);
1188 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001189 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001190 }
1191 BIO_free(biobuf);
1192 if (peer_alt_names != Py_None) {
1193 v = PyList_AsTuple(peer_alt_names);
1194 Py_DECREF(peer_alt_names);
1195 return v;
1196 } else {
1197 return peer_alt_names;
1198 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001199
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001200
1201 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001202 if (biobuf != NULL)
1203 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001204
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001205 if (peer_alt_names != Py_None) {
1206 Py_XDECREF(peer_alt_names);
1207 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001208
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001209 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001210}
1211
1212static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001213_get_aia_uri(X509 *certificate, int nid) {
1214 PyObject *lst = NULL, *ostr = NULL;
1215 int i, result;
1216 AUTHORITY_INFO_ACCESS *info;
1217
1218 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001219 if (info == NULL)
1220 return Py_None;
1221 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1222 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001223 return Py_None;
1224 }
1225
1226 if ((lst = PyList_New(0)) == NULL) {
1227 goto fail;
1228 }
1229
1230 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1231 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1232 ASN1_IA5STRING *uri;
1233
1234 if ((OBJ_obj2nid(ad->method) != nid) ||
1235 (ad->location->type != GEN_URI)) {
1236 continue;
1237 }
1238 uri = ad->location->d.uniformResourceIdentifier;
1239 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1240 uri->length);
1241 if (ostr == NULL) {
1242 goto fail;
1243 }
1244 result = PyList_Append(lst, ostr);
1245 Py_DECREF(ostr);
1246 if (result < 0) {
1247 goto fail;
1248 }
1249 }
1250 AUTHORITY_INFO_ACCESS_free(info);
1251
1252 /* convert to tuple or None */
1253 if (PyList_Size(lst) == 0) {
1254 Py_DECREF(lst);
1255 return Py_None;
1256 } else {
1257 PyObject *tup;
1258 tup = PyList_AsTuple(lst);
1259 Py_DECREF(lst);
1260 return tup;
1261 }
1262
1263 fail:
1264 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001265 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001266 return NULL;
1267}
1268
1269static PyObject *
1270_get_crl_dp(X509 *certificate) {
1271 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001272 int i, j;
1273 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001274
Christian Heimes598894f2016-09-05 23:19:05 +02001275 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001276
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001277 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001278 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001279
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001280 lst = PyList_New(0);
1281 if (lst == NULL)
1282 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001283
1284 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1285 DIST_POINT *dp;
1286 STACK_OF(GENERAL_NAME) *gns;
1287
1288 dp = sk_DIST_POINT_value(dps, i);
1289 gns = dp->distpoint->name.fullname;
1290
1291 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1292 GENERAL_NAME *gn;
1293 ASN1_IA5STRING *uri;
1294 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001295 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001296
1297 gn = sk_GENERAL_NAME_value(gns, j);
1298 if (gn->type != GEN_URI) {
1299 continue;
1300 }
1301 uri = gn->d.uniformResourceIdentifier;
1302 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1303 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001304 if (ouri == NULL)
1305 goto done;
1306
1307 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001308 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001309 if (err < 0)
1310 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001311 }
1312 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001313
1314 /* Convert to tuple. */
1315 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1316
1317 done:
1318 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001319 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001320 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001321}
1322
1323static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001324_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001325
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001326 PyObject *retval = NULL;
1327 BIO *biobuf = NULL;
1328 PyObject *peer;
1329 PyObject *peer_alt_names = NULL;
1330 PyObject *issuer;
1331 PyObject *version;
1332 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001333 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 ASN1_INTEGER *serialNumber;
1335 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001336 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001337 ASN1_TIME *notBefore, *notAfter;
1338 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001339
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001340 retval = PyDict_New();
1341 if (retval == NULL)
1342 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001343
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001344 peer = _create_tuple_for_X509_NAME(
1345 X509_get_subject_name(certificate));
1346 if (peer == NULL)
1347 goto fail0;
1348 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1349 Py_DECREF(peer);
1350 goto fail0;
1351 }
1352 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001353
Antoine Pitroufb046912010-11-09 20:21:19 +00001354 issuer = _create_tuple_for_X509_NAME(
1355 X509_get_issuer_name(certificate));
1356 if (issuer == NULL)
1357 goto fail0;
1358 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001359 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001360 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001362 Py_DECREF(issuer);
1363
1364 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001365 if (version == NULL)
1366 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001367 if (PyDict_SetItemString(retval, "version", version) < 0) {
1368 Py_DECREF(version);
1369 goto fail0;
1370 }
1371 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001372
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001373 /* get a memory buffer */
1374 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001375
Antoine Pitroufb046912010-11-09 20:21:19 +00001376 (void) BIO_reset(biobuf);
1377 serialNumber = X509_get_serialNumber(certificate);
1378 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1379 i2a_ASN1_INTEGER(biobuf, serialNumber);
1380 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1381 if (len < 0) {
1382 _setSSLError(NULL, 0, __FILE__, __LINE__);
1383 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001384 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001385 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1386 if (sn_obj == NULL)
1387 goto fail1;
1388 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1389 Py_DECREF(sn_obj);
1390 goto fail1;
1391 }
1392 Py_DECREF(sn_obj);
1393
1394 (void) BIO_reset(biobuf);
1395 notBefore = X509_get_notBefore(certificate);
1396 ASN1_TIME_print(biobuf, notBefore);
1397 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1398 if (len < 0) {
1399 _setSSLError(NULL, 0, __FILE__, __LINE__);
1400 goto fail1;
1401 }
1402 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1403 if (pnotBefore == NULL)
1404 goto fail1;
1405 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1406 Py_DECREF(pnotBefore);
1407 goto fail1;
1408 }
1409 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001410
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001411 (void) BIO_reset(biobuf);
1412 notAfter = X509_get_notAfter(certificate);
1413 ASN1_TIME_print(biobuf, notAfter);
1414 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1415 if (len < 0) {
1416 _setSSLError(NULL, 0, __FILE__, __LINE__);
1417 goto fail1;
1418 }
1419 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1420 if (pnotAfter == NULL)
1421 goto fail1;
1422 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1423 Py_DECREF(pnotAfter);
1424 goto fail1;
1425 }
1426 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001427
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001428 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001429
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001430 peer_alt_names = _get_peer_alt_names(certificate);
1431 if (peer_alt_names == NULL)
1432 goto fail1;
1433 else if (peer_alt_names != Py_None) {
1434 if (PyDict_SetItemString(retval, "subjectAltName",
1435 peer_alt_names) < 0) {
1436 Py_DECREF(peer_alt_names);
1437 goto fail1;
1438 }
1439 Py_DECREF(peer_alt_names);
1440 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001441
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001442 /* Authority Information Access: OCSP URIs */
1443 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1444 if (obj == NULL) {
1445 goto fail1;
1446 } else if (obj != Py_None) {
1447 result = PyDict_SetItemString(retval, "OCSP", obj);
1448 Py_DECREF(obj);
1449 if (result < 0) {
1450 goto fail1;
1451 }
1452 }
1453
1454 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1455 if (obj == NULL) {
1456 goto fail1;
1457 } else if (obj != Py_None) {
1458 result = PyDict_SetItemString(retval, "caIssuers", obj);
1459 Py_DECREF(obj);
1460 if (result < 0) {
1461 goto fail1;
1462 }
1463 }
1464
1465 /* CDP (CRL distribution points) */
1466 obj = _get_crl_dp(certificate);
1467 if (obj == NULL) {
1468 goto fail1;
1469 } else if (obj != Py_None) {
1470 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1471 Py_DECREF(obj);
1472 if (result < 0) {
1473 goto fail1;
1474 }
1475 }
1476
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001477 BIO_free(biobuf);
1478 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001479
1480 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 if (biobuf != NULL)
1482 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001483 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 Py_XDECREF(retval);
1485 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001486}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001487
Christian Heimes9a5395a2013-06-17 15:44:12 +02001488static PyObject *
1489_certificate_to_der(X509 *certificate)
1490{
1491 unsigned char *bytes_buf = NULL;
1492 int len;
1493 PyObject *retval;
1494
1495 bytes_buf = NULL;
1496 len = i2d_X509(certificate, &bytes_buf);
1497 if (len < 0) {
1498 _setSSLError(NULL, 0, __FILE__, __LINE__);
1499 return NULL;
1500 }
1501 /* this is actually an immutable bytes sequence */
1502 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1503 OPENSSL_free(bytes_buf);
1504 return retval;
1505}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001507/*[clinic input]
1508_ssl._test_decode_cert
1509 path: object(converter="PyUnicode_FSConverter")
1510 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001511
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001512[clinic start generated code]*/
1513
1514static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001515_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1516/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001517{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 X509 *x=NULL;
1520 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001521
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1523 PyErr_SetString(PySSLErrorObject,
1524 "Can't malloc memory to read file");
1525 goto fail0;
1526 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001527
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001528 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001529 PyErr_SetString(PySSLErrorObject,
1530 "Can't open file");
1531 goto fail0;
1532 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001534 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1535 if (x == NULL) {
1536 PyErr_SetString(PySSLErrorObject,
1537 "Error decoding PEM-encoded file");
1538 goto fail0;
1539 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540
Antoine Pitroufb046912010-11-09 20:21:19 +00001541 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001542 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001543
1544 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001545 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 if (cert != NULL) BIO_free(cert);
1547 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001548}
1549
1550
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001551/*[clinic input]
1552_ssl._SSLSocket.peer_certificate
1553 der as binary_mode: bool = False
1554 /
1555
1556Returns the certificate for the peer.
1557
1558If no certificate was provided, returns None. If a certificate was
1559provided, but not validated, returns an empty dictionary. Otherwise
1560returns a dict containing information about the peer certificate.
1561
1562If the optional argument is True, returns a DER-encoded copy of the
1563peer certificate, or None if no certificate was provided. This will
1564return the certificate even if it wasn't validated.
1565[clinic start generated code]*/
1566
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001568_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1569/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001572 X509 *peer_cert;
1573 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574
Christian Heimes66dc33b2017-05-23 16:02:02 -07001575 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001576 PyErr_SetString(PyExc_ValueError,
1577 "handshake not done yet");
1578 return NULL;
1579 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001580 peer_cert = SSL_get_peer_certificate(self->ssl);
1581 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001582 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001583
Antoine Pitrou721738f2012-08-15 23:20:39 +02001584 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001585 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001586 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001588 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001589 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001590 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001591 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001592 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001593 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001594 X509_free(peer_cert);
1595 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001596}
1597
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001598static PyObject *
1599cipher_to_tuple(const SSL_CIPHER *cipher)
1600{
1601 const char *cipher_name, *cipher_protocol;
1602 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001603 if (retval == NULL)
1604 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001605
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001606 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001607 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001608 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001609 PyTuple_SET_ITEM(retval, 0, Py_None);
1610 } else {
1611 v = PyUnicode_FromString(cipher_name);
1612 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001613 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001614 PyTuple_SET_ITEM(retval, 0, v);
1615 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001616
1617 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001618 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001619 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001620 PyTuple_SET_ITEM(retval, 1, Py_None);
1621 } else {
1622 v = PyUnicode_FromString(cipher_protocol);
1623 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001624 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 PyTuple_SET_ITEM(retval, 1, v);
1626 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001627
1628 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001629 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001630 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001631 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001632
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001633 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001634
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001635 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001636 Py_DECREF(retval);
1637 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001638}
1639
Christian Heimes25bfcd52016-09-06 00:04:45 +02001640#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1641static PyObject *
1642cipher_to_dict(const SSL_CIPHER *cipher)
1643{
1644 const char *cipher_name, *cipher_protocol;
1645
1646 unsigned long cipher_id;
1647 int alg_bits, strength_bits, len;
1648 char buf[512] = {0};
1649#if OPENSSL_VERSION_1_1
1650 int aead, nid;
1651 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1652#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001653
1654 /* can be NULL */
1655 cipher_name = SSL_CIPHER_get_name(cipher);
1656 cipher_protocol = SSL_CIPHER_get_version(cipher);
1657 cipher_id = SSL_CIPHER_get_id(cipher);
1658 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001659 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1660 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001661 if (len > 1 && buf[len-1] == '\n')
1662 buf[len-1] = '\0';
1663 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1664
1665#if OPENSSL_VERSION_1_1
1666 aead = SSL_CIPHER_is_aead(cipher);
1667 nid = SSL_CIPHER_get_cipher_nid(cipher);
1668 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1669 nid = SSL_CIPHER_get_digest_nid(cipher);
1670 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1671 nid = SSL_CIPHER_get_kx_nid(cipher);
1672 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1673 nid = SSL_CIPHER_get_auth_nid(cipher);
1674 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1675#endif
1676
Victor Stinner410b9882016-09-12 12:00:23 +02001677 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001678 "{sksssssssisi"
1679#if OPENSSL_VERSION_1_1
1680 "sOssssssss"
1681#endif
1682 "}",
1683 "id", cipher_id,
1684 "name", cipher_name,
1685 "protocol", cipher_protocol,
1686 "description", buf,
1687 "strength_bits", strength_bits,
1688 "alg_bits", alg_bits
1689#if OPENSSL_VERSION_1_1
1690 ,"aead", aead ? Py_True : Py_False,
1691 "symmetric", skcipher,
1692 "digest", digest,
1693 "kea", kx,
1694 "auth", auth
1695#endif
1696 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001697}
1698#endif
1699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001700/*[clinic input]
1701_ssl._SSLSocket.shared_ciphers
1702[clinic start generated code]*/
1703
1704static PyObject *
1705_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1706/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001707{
1708 STACK_OF(SSL_CIPHER) *ciphers;
1709 int i;
1710 PyObject *res;
1711
Christian Heimes598894f2016-09-05 23:19:05 +02001712 ciphers = SSL_get_ciphers(self->ssl);
1713 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001714 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001715 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1716 if (!res)
1717 return NULL;
1718 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1719 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1720 if (!tup) {
1721 Py_DECREF(res);
1722 return NULL;
1723 }
1724 PyList_SET_ITEM(res, i, tup);
1725 }
1726 return res;
1727}
1728
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001729/*[clinic input]
1730_ssl._SSLSocket.cipher
1731[clinic start generated code]*/
1732
1733static PyObject *
1734_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1735/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001736{
1737 const SSL_CIPHER *current;
1738
1739 if (self->ssl == NULL)
1740 Py_RETURN_NONE;
1741 current = SSL_get_current_cipher(self->ssl);
1742 if (current == NULL)
1743 Py_RETURN_NONE;
1744 return cipher_to_tuple(current);
1745}
1746
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001747/*[clinic input]
1748_ssl._SSLSocket.version
1749[clinic start generated code]*/
1750
1751static PyObject *
1752_ssl__SSLSocket_version_impl(PySSLSocket *self)
1753/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001754{
1755 const char *version;
1756
1757 if (self->ssl == NULL)
1758 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001759 if (!SSL_is_init_finished(self->ssl)) {
1760 /* handshake not finished */
1761 Py_RETURN_NONE;
1762 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001763 version = SSL_get_version(self->ssl);
1764 if (!strcmp(version, "unknown"))
1765 Py_RETURN_NONE;
1766 return PyUnicode_FromString(version);
1767}
1768
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001769#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001770/*[clinic input]
1771_ssl._SSLSocket.selected_npn_protocol
1772[clinic start generated code]*/
1773
1774static PyObject *
1775_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1776/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1777{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001778 const unsigned char *out;
1779 unsigned int outlen;
1780
Victor Stinner4569cd52013-06-23 14:58:43 +02001781 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001782 &out, &outlen);
1783
1784 if (out == NULL)
1785 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001786 return PyUnicode_FromStringAndSize((char *)out, outlen);
1787}
1788#endif
1789
1790#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001791/*[clinic input]
1792_ssl._SSLSocket.selected_alpn_protocol
1793[clinic start generated code]*/
1794
1795static PyObject *
1796_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1797/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1798{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001799 const unsigned char *out;
1800 unsigned int outlen;
1801
1802 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1803
1804 if (out == NULL)
1805 Py_RETURN_NONE;
1806 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001807}
1808#endif
1809
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001810/*[clinic input]
1811_ssl._SSLSocket.compression
1812[clinic start generated code]*/
1813
1814static PyObject *
1815_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1816/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1817{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001818#ifdef OPENSSL_NO_COMP
1819 Py_RETURN_NONE;
1820#else
1821 const COMP_METHOD *comp_method;
1822 const char *short_name;
1823
1824 if (self->ssl == NULL)
1825 Py_RETURN_NONE;
1826 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001827 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001828 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001829 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001830 if (short_name == NULL)
1831 Py_RETURN_NONE;
1832 return PyUnicode_DecodeFSDefault(short_name);
1833#endif
1834}
1835
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001836static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1837 Py_INCREF(self->ctx);
1838 return self->ctx;
1839}
1840
1841static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1842 void *closure) {
1843
1844 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001845#if !HAVE_SNI
1846 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1847 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001848 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001849#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001850 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001851 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001852 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001853#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001854 } else {
1855 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1856 return -1;
1857 }
1858
1859 return 0;
1860}
1861
1862PyDoc_STRVAR(PySSL_set_context_doc,
1863"_setter_context(ctx)\n\
1864\
1865This changes the context associated with the SSLSocket. This is typically\n\
1866used from within a callback function set by the set_servername_callback\n\
1867on the SSLContext to change the certificate information associated with the\n\
1868SSLSocket before the cryptographic exchange handshake messages\n");
1869
1870
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001871static PyObject *
1872PySSL_get_server_side(PySSLSocket *self, void *c)
1873{
1874 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1875}
1876
1877PyDoc_STRVAR(PySSL_get_server_side_doc,
1878"Whether this is a server-side socket.");
1879
1880static PyObject *
1881PySSL_get_server_hostname(PySSLSocket *self, void *c)
1882{
1883 if (self->server_hostname == NULL)
1884 Py_RETURN_NONE;
1885 Py_INCREF(self->server_hostname);
1886 return self->server_hostname;
1887}
1888
1889PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1890"The currently set server hostname (for SNI).");
1891
1892static PyObject *
1893PySSL_get_owner(PySSLSocket *self, void *c)
1894{
1895 PyObject *owner;
1896
1897 if (self->owner == NULL)
1898 Py_RETURN_NONE;
1899
1900 owner = PyWeakref_GetObject(self->owner);
1901 Py_INCREF(owner);
1902 return owner;
1903}
1904
1905static int
1906PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1907{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001908 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001909 if (self->owner == NULL)
1910 return -1;
1911 return 0;
1912}
1913
1914PyDoc_STRVAR(PySSL_get_owner_doc,
1915"The Python-level owner of this object.\
1916Passed as \"self\" in servername callback.");
1917
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001918
Antoine Pitrou152efa22010-05-16 18:19:27 +00001919static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001920{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 if (self->ssl)
1922 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001924 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001925 Py_XDECREF(self->server_hostname);
1926 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001928}
1929
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001930/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001931 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001932 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001933 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001934
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001935static int
Victor Stinner14690702015-04-06 22:46:13 +02001936PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001937{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001938 int rc;
1939#ifdef HAVE_POLL
1940 struct pollfd pollfd;
1941 _PyTime_t ms;
1942#else
1943 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001944 fd_set fds;
1945 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001946#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001947
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001948 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001949 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001950 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001951 else if (timeout < 0) {
1952 if (s->sock_timeout > 0)
1953 return SOCKET_HAS_TIMED_OUT;
1954 else
1955 return SOCKET_IS_BLOCKING;
1956 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001957
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001958 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001959 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001961
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 /* Prefer poll, if available, since you can poll() any fd
1963 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001964#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001965 pollfd.fd = s->sock_fd;
1966 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001967
Victor Stinner14690702015-04-06 22:46:13 +02001968 /* timeout is in seconds, poll() uses milliseconds */
1969 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001970 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001971
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001972 PySSL_BEGIN_ALLOW_THREADS
1973 rc = poll(&pollfd, 1, (int)ms);
1974 PySSL_END_ALLOW_THREADS
1975#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001976 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001977 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001979
Victor Stinner14690702015-04-06 22:46:13 +02001980 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 FD_ZERO(&fds);
1983 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001984
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001985 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001986 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001987 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001988 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001989 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001990 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001991 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001992 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001993#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001995 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1996 (when we are able to write or when there's something to read) */
1997 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001998}
1999
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002000/*[clinic input]
2001_ssl._SSLSocket.write
2002 b: Py_buffer
2003 /
2004
2005Writes the bytes-like object b into the SSL object.
2006
2007Returns the number of bytes written.
2008[clinic start generated code]*/
2009
2010static PyObject *
2011_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2012/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002013{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002014 int len;
2015 int sockstate;
2016 int err;
2017 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002018 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002019 _PyTime_t timeout, deadline = 0;
2020 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002021
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002022 if (sock != NULL) {
2023 if (((PyObject*)sock) == Py_None) {
2024 _setSSLError("Underlying socket connection gone",
2025 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2026 return NULL;
2027 }
2028 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 }
2030
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002031 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002032 PyErr_Format(PyExc_OverflowError,
2033 "string longer than %d bytes", INT_MAX);
2034 goto error;
2035 }
2036
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002037 if (sock != NULL) {
2038 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002039 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002040 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2041 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2042 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002043
Victor Stinner14690702015-04-06 22:46:13 +02002044 timeout = GET_SOCKET_TIMEOUT(sock);
2045 has_timeout = (timeout > 0);
2046 if (has_timeout)
2047 deadline = _PyTime_GetMonotonicClock() + timeout;
2048
2049 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002050 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002051 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 "The write operation timed out");
2053 goto error;
2054 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2055 PyErr_SetString(PySSLErrorObject,
2056 "Underlying socket has been closed.");
2057 goto error;
2058 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2059 PyErr_SetString(PySSLErrorObject,
2060 "Underlying socket too large for select().");
2061 goto error;
2062 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002065 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002066 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002067 err = SSL_get_error(self->ssl, len);
2068 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002069
2070 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002071 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002072
Victor Stinner14690702015-04-06 22:46:13 +02002073 if (has_timeout)
2074 timeout = deadline - _PyTime_GetMonotonicClock();
2075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002077 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002079 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 } else {
2081 sockstate = SOCKET_OPERATION_OK;
2082 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002085 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086 "The write operation timed out");
2087 goto error;
2088 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2089 PyErr_SetString(PySSLErrorObject,
2090 "Underlying socket has been closed.");
2091 goto error;
2092 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2093 break;
2094 }
2095 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002096
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002097 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 if (len > 0)
2099 return PyLong_FromLong(len);
2100 else
2101 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002102
2103error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002104 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002105 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002106}
2107
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002108/*[clinic input]
2109_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002110
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002111Returns the number of already decrypted bytes available for read, pending on the connection.
2112[clinic start generated code]*/
2113
2114static PyObject *
2115_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2116/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002117{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002118 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002119
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002120 PySSL_BEGIN_ALLOW_THREADS
2121 count = SSL_pending(self->ssl);
2122 PySSL_END_ALLOW_THREADS
2123 if (count < 0)
2124 return PySSL_SetError(self, count, __FILE__, __LINE__);
2125 else
2126 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002127}
2128
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002129/*[clinic input]
2130_ssl._SSLSocket.read
2131 size as len: int
2132 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002133 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002134 ]
2135 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002137Read up to size bytes from the SSL socket.
2138[clinic start generated code]*/
2139
2140static PyObject *
2141_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2142 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002143/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002144{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002145 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002146 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002147 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002148 int sockstate;
2149 int err;
2150 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002151 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002152 _PyTime_t timeout, deadline = 0;
2153 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002154
Martin Panter5503d472016-03-27 05:35:19 +00002155 if (!group_right_1 && len < 0) {
2156 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2157 return NULL;
2158 }
2159
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002160 if (sock != NULL) {
2161 if (((PyObject*)sock) == Py_None) {
2162 _setSSLError("Underlying socket connection gone",
2163 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2164 return NULL;
2165 }
2166 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 }
2168
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002169 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002170 dest = PyBytes_FromStringAndSize(NULL, len);
2171 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002172 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002173 if (len == 0) {
2174 Py_XDECREF(sock);
2175 return dest;
2176 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002177 mem = PyBytes_AS_STRING(dest);
2178 }
2179 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002180 mem = buffer->buf;
2181 if (len <= 0 || len > buffer->len) {
2182 len = (int) buffer->len;
2183 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002184 PyErr_SetString(PyExc_OverflowError,
2185 "maximum length can't fit in a C 'int'");
2186 goto error;
2187 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002188 if (len == 0) {
2189 count = 0;
2190 goto done;
2191 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002192 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002193 }
2194
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002195 if (sock != NULL) {
2196 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002197 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002198 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2199 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2200 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002201
Victor Stinner14690702015-04-06 22:46:13 +02002202 timeout = GET_SOCKET_TIMEOUT(sock);
2203 has_timeout = (timeout > 0);
2204 if (has_timeout)
2205 deadline = _PyTime_GetMonotonicClock() + timeout;
2206
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002208 PySSL_BEGIN_ALLOW_THREADS
2209 count = SSL_read(self->ssl, mem, len);
2210 err = SSL_get_error(self->ssl, count);
2211 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002212
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002213 if (PyErr_CheckSignals())
2214 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002215
Victor Stinner14690702015-04-06 22:46:13 +02002216 if (has_timeout)
2217 timeout = deadline - _PyTime_GetMonotonicClock();
2218
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002219 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002220 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002222 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002223 } else if (err == SSL_ERROR_ZERO_RETURN &&
2224 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225 {
2226 count = 0;
2227 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002228 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002229 else
2230 sockstate = SOCKET_OPERATION_OK;
2231
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002233 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002234 "The read operation timed out");
2235 goto error;
2236 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2237 break;
2238 }
2239 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002241 if (count <= 0) {
2242 PySSL_SetError(self, count, __FILE__, __LINE__);
2243 goto error;
2244 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002245
2246done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002247 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002248 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002249 _PyBytes_Resize(&dest, count);
2250 return dest;
2251 }
2252 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002253 return PyLong_FromLong(count);
2254 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002255
2256error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002257 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002258 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002259 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002260 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002261}
2262
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002263/*[clinic input]
2264_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002265
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002266Does the SSL shutdown handshake with the remote end.
2267
2268Returns the underlying socket object.
2269[clinic start generated code]*/
2270
2271static PyObject *
2272_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2273/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002274{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002275 int err, ssl_err, sockstate, nonblocking;
2276 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002277 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002278 _PyTime_t timeout, deadline = 0;
2279 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002280
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002281 if (sock != NULL) {
2282 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002283 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002284 _setSSLError("Underlying socket connection gone",
2285 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2286 return NULL;
2287 }
2288 Py_INCREF(sock);
2289
2290 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002291 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002292 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2293 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295
Victor Stinner14690702015-04-06 22:46:13 +02002296 timeout = GET_SOCKET_TIMEOUT(sock);
2297 has_timeout = (timeout > 0);
2298 if (has_timeout)
2299 deadline = _PyTime_GetMonotonicClock() + timeout;
2300
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 while (1) {
2302 PySSL_BEGIN_ALLOW_THREADS
2303 /* Disable read-ahead so that unwrap can work correctly.
2304 * Otherwise OpenSSL might read in too much data,
2305 * eating clear text data that happens to be
2306 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002307 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002308 * function is used and the shutdown_seen_zero != 0
2309 * condition is met.
2310 */
2311 if (self->shutdown_seen_zero)
2312 SSL_set_read_ahead(self->ssl, 0);
2313 err = SSL_shutdown(self->ssl);
2314 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002315
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002316 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2317 if (err > 0)
2318 break;
2319 if (err == 0) {
2320 /* Don't loop endlessly; instead preserve legacy
2321 behaviour of trying SSL_shutdown() only twice.
2322 This looks necessary for OpenSSL < 0.9.8m */
2323 if (++zeros > 1)
2324 break;
2325 /* Shutdown was sent, now try receiving */
2326 self->shutdown_seen_zero = 1;
2327 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002328 }
2329
Victor Stinner14690702015-04-06 22:46:13 +02002330 if (has_timeout)
2331 timeout = deadline - _PyTime_GetMonotonicClock();
2332
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002333 /* Possibly retry shutdown until timeout or failure */
2334 ssl_err = SSL_get_error(self->ssl, err);
2335 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002336 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002337 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002338 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339 else
2340 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002342 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2343 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002344 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 "The read operation timed out");
2346 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002347 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002348 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002349 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002350 }
2351 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2352 PyErr_SetString(PySSLErrorObject,
2353 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002354 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002355 }
2356 else if (sockstate != SOCKET_OPERATION_OK)
2357 /* Retain the SSL error code */
2358 break;
2359 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002360
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002361 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002362 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002363 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002364 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002365 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002366 /* It's already INCREF'ed */
2367 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002368 else
2369 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002370
2371error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002372 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002373 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002374}
2375
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002376/*[clinic input]
2377_ssl._SSLSocket.tls_unique_cb
2378
2379Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2380
2381If the TLS handshake is not yet complete, None is returned.
2382[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002383
Antoine Pitroud6494802011-07-21 01:11:30 +02002384static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002385_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2386/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002387{
2388 PyObject *retval = NULL;
2389 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002390 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002391
2392 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2393 /* if session is resumed XOR we are the client */
2394 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2395 }
2396 else {
2397 /* if a new session XOR we are the server */
2398 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2399 }
2400
2401 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002402 if (len == 0)
2403 Py_RETURN_NONE;
2404
2405 retval = PyBytes_FromStringAndSize(buf, len);
2406
2407 return retval;
2408}
2409
Christian Heimes99a65702016-09-10 23:44:53 +02002410#ifdef OPENSSL_VERSION_1_1
2411
2412static SSL_SESSION*
2413_ssl_session_dup(SSL_SESSION *session) {
2414 SSL_SESSION *newsession = NULL;
2415 int slen;
2416 unsigned char *senc = NULL, *p;
2417 const unsigned char *const_p;
2418
2419 if (session == NULL) {
2420 PyErr_SetString(PyExc_ValueError, "Invalid session");
2421 goto error;
2422 }
2423
2424 /* get length */
2425 slen = i2d_SSL_SESSION(session, NULL);
2426 if (slen == 0 || slen > 0xFF00) {
2427 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2428 goto error;
2429 }
2430 if ((senc = PyMem_Malloc(slen)) == NULL) {
2431 PyErr_NoMemory();
2432 goto error;
2433 }
2434 p = senc;
2435 if (!i2d_SSL_SESSION(session, &p)) {
2436 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2437 goto error;
2438 }
2439 const_p = senc;
2440 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2441 if (session == NULL) {
2442 goto error;
2443 }
2444 PyMem_Free(senc);
2445 return newsession;
2446 error:
2447 if (senc != NULL) {
2448 PyMem_Free(senc);
2449 }
2450 return NULL;
2451}
2452#endif
2453
2454static PyObject *
2455PySSL_get_session(PySSLSocket *self, void *closure) {
2456 /* get_session can return sessions from a server-side connection,
2457 * it does not check for handshake done or client socket. */
2458 PySSLSession *pysess;
2459 SSL_SESSION *session;
2460
2461#ifdef OPENSSL_VERSION_1_1
2462 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2463 * https://github.com/openssl/openssl/issues/1550 */
2464 session = SSL_get0_session(self->ssl); /* borrowed reference */
2465 if (session == NULL) {
2466 Py_RETURN_NONE;
2467 }
2468 if ((session = _ssl_session_dup(session)) == NULL) {
2469 return NULL;
2470 }
2471#else
2472 session = SSL_get1_session(self->ssl);
2473 if (session == NULL) {
2474 Py_RETURN_NONE;
2475 }
2476#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002477 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002478 if (pysess == NULL) {
2479 SSL_SESSION_free(session);
2480 return NULL;
2481 }
2482
2483 assert(self->ctx);
2484 pysess->ctx = self->ctx;
2485 Py_INCREF(pysess->ctx);
2486 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002487 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002488 return (PyObject *)pysess;
2489}
2490
2491static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2492 void *closure)
2493 {
2494 PySSLSession *pysess;
2495#ifdef OPENSSL_VERSION_1_1
2496 SSL_SESSION *session;
2497#endif
2498 int result;
2499
2500 if (!PySSLSession_Check(value)) {
2501 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2502 return -1;
2503 }
2504 pysess = (PySSLSession *)value;
2505
2506 if (self->ctx->ctx != pysess->ctx->ctx) {
2507 PyErr_SetString(PyExc_ValueError,
2508 "Session refers to a different SSLContext.");
2509 return -1;
2510 }
2511 if (self->socket_type != PY_SSL_CLIENT) {
2512 PyErr_SetString(PyExc_ValueError,
2513 "Cannot set session for server-side SSLSocket.");
2514 return -1;
2515 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002516 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002517 PyErr_SetString(PyExc_ValueError,
2518 "Cannot set session after handshake.");
2519 return -1;
2520 }
2521#ifdef OPENSSL_VERSION_1_1
2522 /* duplicate session */
2523 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2524 return -1;
2525 }
2526 result = SSL_set_session(self->ssl, session);
2527 /* free duplicate, SSL_set_session() bumps ref count */
2528 SSL_SESSION_free(session);
2529#else
2530 result = SSL_set_session(self->ssl, pysess->session);
2531#endif
2532 if (result == 0) {
2533 _setSSLError(NULL, 0, __FILE__, __LINE__);
2534 return -1;
2535 }
2536 return 0;
2537}
2538
2539PyDoc_STRVAR(PySSL_set_session_doc,
2540"_setter_session(session)\n\
2541\
2542Get / set SSLSession.");
2543
2544static PyObject *
2545PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2546 if (SSL_session_reused(self->ssl)) {
2547 Py_RETURN_TRUE;
2548 } else {
2549 Py_RETURN_FALSE;
2550 }
2551}
2552
2553PyDoc_STRVAR(PySSL_get_session_reused_doc,
2554"Was the client session reused during handshake?");
2555
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002556static PyGetSetDef ssl_getsetlist[] = {
2557 {"context", (getter) PySSL_get_context,
2558 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002559 {"server_side", (getter) PySSL_get_server_side, NULL,
2560 PySSL_get_server_side_doc},
2561 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2562 PySSL_get_server_hostname_doc},
2563 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2564 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002565 {"session", (getter) PySSL_get_session,
2566 (setter) PySSL_set_session, PySSL_set_session_doc},
2567 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2568 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002569 {NULL}, /* sentinel */
2570};
2571
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002572static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002573 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2574 _SSL__SSLSOCKET_WRITE_METHODDEF
2575 _SSL__SSLSOCKET_READ_METHODDEF
2576 _SSL__SSLSOCKET_PENDING_METHODDEF
2577 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2578 _SSL__SSLSOCKET_CIPHER_METHODDEF
2579 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2580 _SSL__SSLSOCKET_VERSION_METHODDEF
2581 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2582 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2583 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2584 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2585 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002586 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002587};
2588
Antoine Pitrou152efa22010-05-16 18:19:27 +00002589static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002590 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002591 "_ssl._SSLSocket", /*tp_name*/
2592 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002593 0, /*tp_itemsize*/
2594 /* methods */
2595 (destructor)PySSL_dealloc, /*tp_dealloc*/
2596 0, /*tp_print*/
2597 0, /*tp_getattr*/
2598 0, /*tp_setattr*/
2599 0, /*tp_reserved*/
2600 0, /*tp_repr*/
2601 0, /*tp_as_number*/
2602 0, /*tp_as_sequence*/
2603 0, /*tp_as_mapping*/
2604 0, /*tp_hash*/
2605 0, /*tp_call*/
2606 0, /*tp_str*/
2607 0, /*tp_getattro*/
2608 0, /*tp_setattro*/
2609 0, /*tp_as_buffer*/
2610 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2611 0, /*tp_doc*/
2612 0, /*tp_traverse*/
2613 0, /*tp_clear*/
2614 0, /*tp_richcompare*/
2615 0, /*tp_weaklistoffset*/
2616 0, /*tp_iter*/
2617 0, /*tp_iternext*/
2618 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002619 0, /*tp_members*/
2620 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002621};
2622
Antoine Pitrou152efa22010-05-16 18:19:27 +00002623
2624/*
2625 * _SSLContext objects
2626 */
2627
Christian Heimes5fe668c2016-09-12 00:01:11 +02002628static int
2629_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2630{
2631 int mode;
2632 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2633
2634 switch(n) {
2635 case PY_SSL_CERT_NONE:
2636 mode = SSL_VERIFY_NONE;
2637 break;
2638 case PY_SSL_CERT_OPTIONAL:
2639 mode = SSL_VERIFY_PEER;
2640 break;
2641 case PY_SSL_CERT_REQUIRED:
2642 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2643 break;
2644 default:
2645 PyErr_SetString(PyExc_ValueError,
2646 "invalid value for verify_mode");
2647 return -1;
2648 }
2649 /* keep current verify cb */
2650 verify_cb = SSL_CTX_get_verify_callback(ctx);
2651 SSL_CTX_set_verify(ctx, mode, verify_cb);
2652 return 0;
2653}
2654
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002655/*[clinic input]
2656@classmethod
2657_ssl._SSLContext.__new__
2658 protocol as proto_version: int
2659 /
2660[clinic start generated code]*/
2661
Antoine Pitrou152efa22010-05-16 18:19:27 +00002662static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002663_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2664/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002665{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002666 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002667 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002668 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002669 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002670#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002671 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002672#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002673
Antoine Pitrou152efa22010-05-16 18:19:27 +00002674 PySSL_BEGIN_ALLOW_THREADS
2675 if (proto_version == PY_SSL_VERSION_TLS1)
2676 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002677#if HAVE_TLSv1_2
2678 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2679 ctx = SSL_CTX_new(TLSv1_1_method());
2680 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2681 ctx = SSL_CTX_new(TLSv1_2_method());
2682#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002683#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002684 else if (proto_version == PY_SSL_VERSION_SSL3)
2685 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002686#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002687#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002688 else if (proto_version == PY_SSL_VERSION_SSL2)
2689 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002690#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002691 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002692 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002693 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2694 ctx = SSL_CTX_new(TLS_client_method());
2695 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2696 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002697 else
2698 proto_version = -1;
2699 PySSL_END_ALLOW_THREADS
2700
2701 if (proto_version == -1) {
2702 PyErr_SetString(PyExc_ValueError,
2703 "invalid protocol version");
2704 return NULL;
2705 }
2706 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002707 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002708 return NULL;
2709 }
2710
2711 assert(type != NULL && type->tp_alloc != NULL);
2712 self = (PySSLContext *) type->tp_alloc(type, 0);
2713 if (self == NULL) {
2714 SSL_CTX_free(ctx);
2715 return NULL;
2716 }
2717 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002718#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002719 self->npn_protocols = NULL;
2720#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002721#ifdef HAVE_ALPN
2722 self->alpn_protocols = NULL;
2723#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002724#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002725 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002726#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002727 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002728 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2729 self->check_hostname = 1;
2730 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2731 Py_DECREF(self);
2732 return NULL;
2733 }
2734 } else {
2735 self->check_hostname = 0;
2736 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2737 Py_DECREF(self);
2738 return NULL;
2739 }
2740 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002741 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002742 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2743 if (proto_version != PY_SSL_VERSION_SSL2)
2744 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002745 if (proto_version != PY_SSL_VERSION_SSL3)
2746 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002747 /* Minimal security flags for server and client side context.
2748 * Client sockets ignore server-side parameters. */
2749#ifdef SSL_OP_NO_COMPRESSION
2750 options |= SSL_OP_NO_COMPRESSION;
2751#endif
2752#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2753 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2754#endif
2755#ifdef SSL_OP_SINGLE_DH_USE
2756 options |= SSL_OP_SINGLE_DH_USE;
2757#endif
2758#ifdef SSL_OP_SINGLE_ECDH_USE
2759 options |= SSL_OP_SINGLE_ECDH_USE;
2760#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002761 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002762
Christian Heimes358cfd42016-09-10 22:43:48 +02002763 /* A bare minimum cipher list without completly broken cipher suites.
2764 * It's far from perfect but gives users a better head start. */
2765 if (proto_version != PY_SSL_VERSION_SSL2) {
2766 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2767 } else {
2768 /* SSLv2 needs MD5 */
2769 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2770 }
2771 if (result == 0) {
2772 Py_DECREF(self);
2773 ERR_clear_error();
2774 PyErr_SetString(PySSLErrorObject,
2775 "No cipher can be selected.");
2776 return NULL;
2777 }
2778
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002779#if defined(SSL_MODE_RELEASE_BUFFERS)
2780 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2781 usage for no cost at all. However, don't do this for OpenSSL versions
2782 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2783 2014-0198. I can't find exactly which beta fixed this CVE, so be
2784 conservative and assume it wasn't fixed until release. We do this check
2785 at runtime to avoid problems from the dynamic linker.
2786 See #25672 for more on this. */
2787 libver = SSLeay();
2788 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2789 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2790 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2791 }
2792#endif
2793
2794
Donald Stufft8ae264c2017-03-02 11:45:29 -05002795#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002796 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2797 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002798 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2799 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002800#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002801 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2802#else
2803 {
2804 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2805 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2806 EC_KEY_free(key);
2807 }
2808#endif
2809#endif
2810
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002811#define SID_CTX "Python"
2812 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2813 sizeof(SID_CTX));
2814#undef SID_CTX
2815
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002816#ifdef X509_V_FLAG_TRUSTED_FIRST
2817 {
2818 /* Improve trust chain building when cross-signed intermediate
2819 certificates are present. See https://bugs.python.org/issue23476. */
2820 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2821 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2822 }
2823#endif
2824
Antoine Pitrou152efa22010-05-16 18:19:27 +00002825 return (PyObject *)self;
2826}
2827
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002828static int
2829context_traverse(PySSLContext *self, visitproc visit, void *arg)
2830{
2831#ifndef OPENSSL_NO_TLSEXT
2832 Py_VISIT(self->set_hostname);
2833#endif
2834 return 0;
2835}
2836
2837static int
2838context_clear(PySSLContext *self)
2839{
2840#ifndef OPENSSL_NO_TLSEXT
2841 Py_CLEAR(self->set_hostname);
2842#endif
2843 return 0;
2844}
2845
Antoine Pitrou152efa22010-05-16 18:19:27 +00002846static void
2847context_dealloc(PySSLContext *self)
2848{
INADA Naokia6296d32017-08-24 14:55:17 +09002849 /* bpo-31095: UnTrack is needed before calling any callbacks */
2850 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002851 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002852 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002853#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002854 PyMem_FREE(self->npn_protocols);
2855#endif
2856#ifdef HAVE_ALPN
2857 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002858#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002859 Py_TYPE(self)->tp_free(self);
2860}
2861
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002862/*[clinic input]
2863_ssl._SSLContext.set_ciphers
2864 cipherlist: str
2865 /
2866[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002867
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002868static PyObject *
2869_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2870/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2871{
2872 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002873 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002874 /* Clearing the error queue is necessary on some OpenSSL versions,
2875 otherwise the error will be reported again when another SSL call
2876 is done. */
2877 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002878 PyErr_SetString(PySSLErrorObject,
2879 "No cipher can be selected.");
2880 return NULL;
2881 }
2882 Py_RETURN_NONE;
2883}
2884
Christian Heimes25bfcd52016-09-06 00:04:45 +02002885#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2886/*[clinic input]
2887_ssl._SSLContext.get_ciphers
2888[clinic start generated code]*/
2889
2890static PyObject *
2891_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2892/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2893{
2894 SSL *ssl = NULL;
2895 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002896 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002897 int i=0;
2898 PyObject *result = NULL, *dct;
2899
2900 ssl = SSL_new(self->ctx);
2901 if (ssl == NULL) {
2902 _setSSLError(NULL, 0, __FILE__, __LINE__);
2903 goto exit;
2904 }
2905 sk = SSL_get_ciphers(ssl);
2906
2907 result = PyList_New(sk_SSL_CIPHER_num(sk));
2908 if (result == NULL) {
2909 goto exit;
2910 }
2911
2912 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2913 cipher = sk_SSL_CIPHER_value(sk, i);
2914 dct = cipher_to_dict(cipher);
2915 if (dct == NULL) {
2916 Py_CLEAR(result);
2917 goto exit;
2918 }
2919 PyList_SET_ITEM(result, i, dct);
2920 }
2921
2922 exit:
2923 if (ssl != NULL)
2924 SSL_free(ssl);
2925 return result;
2926
2927}
2928#endif
2929
2930
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002931#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002932static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002933do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2934 const unsigned char *server_protocols, unsigned int server_protocols_len,
2935 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002936{
Benjamin Peterson88615022015-01-23 17:30:26 -05002937 int ret;
2938 if (client_protocols == NULL) {
2939 client_protocols = (unsigned char *)"";
2940 client_protocols_len = 0;
2941 }
2942 if (server_protocols == NULL) {
2943 server_protocols = (unsigned char *)"";
2944 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002945 }
2946
Benjamin Peterson88615022015-01-23 17:30:26 -05002947 ret = SSL_select_next_proto(out, outlen,
2948 server_protocols, server_protocols_len,
2949 client_protocols, client_protocols_len);
2950 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2951 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002952
2953 return SSL_TLSEXT_ERR_OK;
2954}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002955#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002956
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002957#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002958/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2959static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002960_advertiseNPN_cb(SSL *s,
2961 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002962 void *args)
2963{
2964 PySSLContext *ssl_ctx = (PySSLContext *) args;
2965
2966 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002967 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002968 *len = 0;
2969 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002970 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002971 *len = ssl_ctx->npn_protocols_len;
2972 }
2973
2974 return SSL_TLSEXT_ERR_OK;
2975}
2976/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2977static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002978_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002979 unsigned char **out, unsigned char *outlen,
2980 const unsigned char *server, unsigned int server_len,
2981 void *args)
2982{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002983 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002984 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002985 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002986}
2987#endif
2988
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002989/*[clinic input]
2990_ssl._SSLContext._set_npn_protocols
2991 protos: Py_buffer
2992 /
2993[clinic start generated code]*/
2994
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002995static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002996_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2997 Py_buffer *protos)
2998/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002999{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003000#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003001 PyMem_Free(self->npn_protocols);
3002 self->npn_protocols = PyMem_Malloc(protos->len);
3003 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003004 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003005 memcpy(self->npn_protocols, protos->buf, protos->len);
3006 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003007
3008 /* set both server and client callbacks, because the context can
3009 * be used to create both types of sockets */
3010 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3011 _advertiseNPN_cb,
3012 self);
3013 SSL_CTX_set_next_proto_select_cb(self->ctx,
3014 _selectNPN_cb,
3015 self);
3016
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003017 Py_RETURN_NONE;
3018#else
3019 PyErr_SetString(PyExc_NotImplementedError,
3020 "The NPN extension requires OpenSSL 1.0.1 or later.");
3021 return NULL;
3022#endif
3023}
3024
Benjamin Petersoncca27322015-01-23 16:35:37 -05003025#ifdef HAVE_ALPN
3026static int
3027_selectALPN_cb(SSL *s,
3028 const unsigned char **out, unsigned char *outlen,
3029 const unsigned char *client_protocols, unsigned int client_protocols_len,
3030 void *args)
3031{
3032 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003033 return do_protocol_selection(1, (unsigned char **)out, outlen,
3034 ctx->alpn_protocols, ctx->alpn_protocols_len,
3035 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003036}
3037#endif
3038
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003039/*[clinic input]
3040_ssl._SSLContext._set_alpn_protocols
3041 protos: Py_buffer
3042 /
3043[clinic start generated code]*/
3044
Benjamin Petersoncca27322015-01-23 16:35:37 -05003045static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003046_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3047 Py_buffer *protos)
3048/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003049{
3050#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03003051 if (protos->len > UINT_MAX) {
3052 PyErr_Format(PyExc_OverflowError,
3053 "protocols longer than %d bytes", UINT_MAX);
3054 return NULL;
3055 }
3056
Benjamin Petersoncca27322015-01-23 16:35:37 -05003057 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003058 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003059 if (!self->alpn_protocols)
3060 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003061 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003062 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003063
3064 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3065 return PyErr_NoMemory();
3066 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3067
Benjamin Petersoncca27322015-01-23 16:35:37 -05003068 Py_RETURN_NONE;
3069#else
3070 PyErr_SetString(PyExc_NotImplementedError,
3071 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3072 return NULL;
3073#endif
3074}
3075
Antoine Pitrou152efa22010-05-16 18:19:27 +00003076static PyObject *
3077get_verify_mode(PySSLContext *self, void *c)
3078{
3079 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3080 case SSL_VERIFY_NONE:
3081 return PyLong_FromLong(PY_SSL_CERT_NONE);
3082 case SSL_VERIFY_PEER:
3083 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3084 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3085 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3086 }
3087 PyErr_SetString(PySSLErrorObject,
3088 "invalid return value from SSL_CTX_get_verify_mode");
3089 return NULL;
3090}
3091
3092static int
3093set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3094{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003095 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003096 if (!PyArg_Parse(arg, "i", &n))
3097 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003098 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003099 PyErr_SetString(PyExc_ValueError,
3100 "Cannot set verify_mode to CERT_NONE when "
3101 "check_hostname is enabled.");
3102 return -1;
3103 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003104 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003105}
3106
3107static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003108get_verify_flags(PySSLContext *self, void *c)
3109{
3110 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003111 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003112 unsigned long flags;
3113
3114 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003115 param = X509_STORE_get0_param(store);
3116 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003117 return PyLong_FromUnsignedLong(flags);
3118}
3119
3120static int
3121set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3122{
3123 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003124 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003125 unsigned long new_flags, flags, set, clear;
3126
3127 if (!PyArg_Parse(arg, "k", &new_flags))
3128 return -1;
3129 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003130 param = X509_STORE_get0_param(store);
3131 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003132 clear = flags & ~new_flags;
3133 set = ~flags & new_flags;
3134 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003135 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003136 _setSSLError(NULL, 0, __FILE__, __LINE__);
3137 return -1;
3138 }
3139 }
3140 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003141 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003142 _setSSLError(NULL, 0, __FILE__, __LINE__);
3143 return -1;
3144 }
3145 }
3146 return 0;
3147}
3148
3149static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003150get_options(PySSLContext *self, void *c)
3151{
3152 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3153}
3154
3155static int
3156set_options(PySSLContext *self, PyObject *arg, void *c)
3157{
3158 long new_opts, opts, set, clear;
3159 if (!PyArg_Parse(arg, "l", &new_opts))
3160 return -1;
3161 opts = SSL_CTX_get_options(self->ctx);
3162 clear = opts & ~new_opts;
3163 set = ~opts & new_opts;
3164 if (clear) {
3165#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3166 SSL_CTX_clear_options(self->ctx, clear);
3167#else
3168 PyErr_SetString(PyExc_ValueError,
3169 "can't clear options before OpenSSL 0.9.8m");
3170 return -1;
3171#endif
3172 }
3173 if (set)
3174 SSL_CTX_set_options(self->ctx, set);
3175 return 0;
3176}
3177
Christian Heimes1aa9a752013-12-02 02:41:19 +01003178static PyObject *
3179get_check_hostname(PySSLContext *self, void *c)
3180{
3181 return PyBool_FromLong(self->check_hostname);
3182}
3183
3184static int
3185set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3186{
3187 int check_hostname;
3188 if (!PyArg_Parse(arg, "p", &check_hostname))
3189 return -1;
3190 if (check_hostname &&
3191 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3192 PyErr_SetString(PyExc_ValueError,
3193 "check_hostname needs a SSL context with either "
3194 "CERT_OPTIONAL or CERT_REQUIRED");
3195 return -1;
3196 }
3197 self->check_hostname = check_hostname;
3198 return 0;
3199}
3200
3201
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003202typedef struct {
3203 PyThreadState *thread_state;
3204 PyObject *callable;
3205 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003206 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003207 int error;
3208} _PySSLPasswordInfo;
3209
3210static int
3211_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3212 const char *bad_type_error)
3213{
3214 /* Set the password and size fields of a _PySSLPasswordInfo struct
3215 from a unicode, bytes, or byte array object.
3216 The password field will be dynamically allocated and must be freed
3217 by the caller */
3218 PyObject *password_bytes = NULL;
3219 const char *data = NULL;
3220 Py_ssize_t size;
3221
3222 if (PyUnicode_Check(password)) {
3223 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3224 if (!password_bytes) {
3225 goto error;
3226 }
3227 data = PyBytes_AS_STRING(password_bytes);
3228 size = PyBytes_GET_SIZE(password_bytes);
3229 } else if (PyBytes_Check(password)) {
3230 data = PyBytes_AS_STRING(password);
3231 size = PyBytes_GET_SIZE(password);
3232 } else if (PyByteArray_Check(password)) {
3233 data = PyByteArray_AS_STRING(password);
3234 size = PyByteArray_GET_SIZE(password);
3235 } else {
3236 PyErr_SetString(PyExc_TypeError, bad_type_error);
3237 goto error;
3238 }
3239
Victor Stinner9ee02032013-06-23 15:08:23 +02003240 if (size > (Py_ssize_t)INT_MAX) {
3241 PyErr_Format(PyExc_ValueError,
3242 "password cannot be longer than %d bytes", INT_MAX);
3243 goto error;
3244 }
3245
Victor Stinner11ebff22013-07-07 17:07:52 +02003246 PyMem_Free(pw_info->password);
3247 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003248 if (!pw_info->password) {
3249 PyErr_SetString(PyExc_MemoryError,
3250 "unable to allocate password buffer");
3251 goto error;
3252 }
3253 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003254 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003255
3256 Py_XDECREF(password_bytes);
3257 return 1;
3258
3259error:
3260 Py_XDECREF(password_bytes);
3261 return 0;
3262}
3263
3264static int
3265_password_callback(char *buf, int size, int rwflag, void *userdata)
3266{
3267 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3268 PyObject *fn_ret = NULL;
3269
3270 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3271
3272 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003273 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003274 if (!fn_ret) {
3275 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3276 core python API, so we could use it to add a frame here */
3277 goto error;
3278 }
3279
3280 if (!_pwinfo_set(pw_info, fn_ret,
3281 "password callback must return a string")) {
3282 goto error;
3283 }
3284 Py_CLEAR(fn_ret);
3285 }
3286
3287 if (pw_info->size > size) {
3288 PyErr_Format(PyExc_ValueError,
3289 "password cannot be longer than %d bytes", size);
3290 goto error;
3291 }
3292
3293 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3294 memcpy(buf, pw_info->password, pw_info->size);
3295 return pw_info->size;
3296
3297error:
3298 Py_XDECREF(fn_ret);
3299 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3300 pw_info->error = 1;
3301 return -1;
3302}
3303
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003304/*[clinic input]
3305_ssl._SSLContext.load_cert_chain
3306 certfile: object
3307 keyfile: object = NULL
3308 password: object = NULL
3309
3310[clinic start generated code]*/
3311
Antoine Pitroub5218772010-05-21 09:56:06 +00003312static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003313_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3314 PyObject *keyfile, PyObject *password)
3315/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003316{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003318 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3319 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003320 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003321 int r;
3322
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003323 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003324 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003325 if (keyfile == Py_None)
3326 keyfile = NULL;
3327 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3328 PyErr_SetString(PyExc_TypeError,
3329 "certfile should be a valid filesystem path");
3330 return NULL;
3331 }
3332 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3333 PyErr_SetString(PyExc_TypeError,
3334 "keyfile should be a valid filesystem path");
3335 goto error;
3336 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003337 if (password && password != Py_None) {
3338 if (PyCallable_Check(password)) {
3339 pw_info.callable = password;
3340 } else if (!_pwinfo_set(&pw_info, password,
3341 "password should be a string or callable")) {
3342 goto error;
3343 }
3344 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3345 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3346 }
3347 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003348 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3349 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003350 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003351 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003352 if (pw_info.error) {
3353 ERR_clear_error();
3354 /* the password callback has already set the error information */
3355 }
3356 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003357 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003358 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003359 }
3360 else {
3361 _setSSLError(NULL, 0, __FILE__, __LINE__);
3362 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003363 goto error;
3364 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003365 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003366 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003367 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3368 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003369 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3370 Py_CLEAR(keyfile_bytes);
3371 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003372 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003373 if (pw_info.error) {
3374 ERR_clear_error();
3375 /* the password callback has already set the error information */
3376 }
3377 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003378 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003379 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003380 }
3381 else {
3382 _setSSLError(NULL, 0, __FILE__, __LINE__);
3383 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003384 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003385 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003386 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003387 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003388 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003389 if (r != 1) {
3390 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003391 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003392 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003393 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3394 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003395 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003396 Py_RETURN_NONE;
3397
3398error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003399 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3400 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003401 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003402 Py_XDECREF(keyfile_bytes);
3403 Py_XDECREF(certfile_bytes);
3404 return NULL;
3405}
3406
Christian Heimesefff7062013-11-21 03:35:02 +01003407/* internal helper function, returns -1 on error
3408 */
3409static int
3410_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3411 int filetype)
3412{
3413 BIO *biobuf = NULL;
3414 X509_STORE *store;
3415 int retval = 0, err, loaded = 0;
3416
3417 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3418
3419 if (len <= 0) {
3420 PyErr_SetString(PyExc_ValueError,
3421 "Empty certificate data");
3422 return -1;
3423 } else if (len > INT_MAX) {
3424 PyErr_SetString(PyExc_OverflowError,
3425 "Certificate data is too long.");
3426 return -1;
3427 }
3428
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003429 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003430 if (biobuf == NULL) {
3431 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3432 return -1;
3433 }
3434
3435 store = SSL_CTX_get_cert_store(self->ctx);
3436 assert(store != NULL);
3437
3438 while (1) {
3439 X509 *cert = NULL;
3440 int r;
3441
3442 if (filetype == SSL_FILETYPE_ASN1) {
3443 cert = d2i_X509_bio(biobuf, NULL);
3444 } else {
3445 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003446 SSL_CTX_get_default_passwd_cb(self->ctx),
3447 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3448 );
Christian Heimesefff7062013-11-21 03:35:02 +01003449 }
3450 if (cert == NULL) {
3451 break;
3452 }
3453 r = X509_STORE_add_cert(store, cert);
3454 X509_free(cert);
3455 if (!r) {
3456 err = ERR_peek_last_error();
3457 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3458 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3459 /* cert already in hash table, not an error */
3460 ERR_clear_error();
3461 } else {
3462 break;
3463 }
3464 }
3465 loaded++;
3466 }
3467
3468 err = ERR_peek_last_error();
3469 if ((filetype == SSL_FILETYPE_ASN1) &&
3470 (loaded > 0) &&
3471 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3472 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3473 /* EOF ASN1 file, not an error */
3474 ERR_clear_error();
3475 retval = 0;
3476 } else if ((filetype == SSL_FILETYPE_PEM) &&
3477 (loaded > 0) &&
3478 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3479 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3480 /* EOF PEM file, not an error */
3481 ERR_clear_error();
3482 retval = 0;
3483 } else {
3484 _setSSLError(NULL, 0, __FILE__, __LINE__);
3485 retval = -1;
3486 }
3487
3488 BIO_free(biobuf);
3489 return retval;
3490}
3491
3492
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003493/*[clinic input]
3494_ssl._SSLContext.load_verify_locations
3495 cafile: object = NULL
3496 capath: object = NULL
3497 cadata: object = NULL
3498
3499[clinic start generated code]*/
3500
Antoine Pitrou152efa22010-05-16 18:19:27 +00003501static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003502_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3503 PyObject *cafile,
3504 PyObject *capath,
3505 PyObject *cadata)
3506/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003507{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003508 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3509 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003510 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003511
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003512 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003513 if (cafile == Py_None)
3514 cafile = NULL;
3515 if (capath == Py_None)
3516 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003517 if (cadata == Py_None)
3518 cadata = NULL;
3519
3520 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003521 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003522 "cafile, capath and cadata cannot be all omitted");
3523 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003524 }
3525 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3526 PyErr_SetString(PyExc_TypeError,
3527 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003528 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003529 }
3530 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003531 PyErr_SetString(PyExc_TypeError,
3532 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003533 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003534 }
Christian Heimesefff7062013-11-21 03:35:02 +01003535
3536 /* validata cadata type and load cadata */
3537 if (cadata) {
3538 Py_buffer buf;
3539 PyObject *cadata_ascii = NULL;
3540
3541 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3542 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3543 PyBuffer_Release(&buf);
3544 PyErr_SetString(PyExc_TypeError,
3545 "cadata should be a contiguous buffer with "
3546 "a single dimension");
3547 goto error;
3548 }
3549 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3550 PyBuffer_Release(&buf);
3551 if (r == -1) {
3552 goto error;
3553 }
3554 } else {
3555 PyErr_Clear();
3556 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3557 if (cadata_ascii == NULL) {
3558 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003559 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003560 "bytes-like object");
3561 goto error;
3562 }
3563 r = _add_ca_certs(self,
3564 PyBytes_AS_STRING(cadata_ascii),
3565 PyBytes_GET_SIZE(cadata_ascii),
3566 SSL_FILETYPE_PEM);
3567 Py_DECREF(cadata_ascii);
3568 if (r == -1) {
3569 goto error;
3570 }
3571 }
3572 }
3573
3574 /* load cafile or capath */
3575 if (cafile || capath) {
3576 if (cafile)
3577 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3578 if (capath)
3579 capath_buf = PyBytes_AS_STRING(capath_bytes);
3580 PySSL_BEGIN_ALLOW_THREADS
3581 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3582 PySSL_END_ALLOW_THREADS
3583 if (r != 1) {
3584 ok = 0;
3585 if (errno != 0) {
3586 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003587 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003588 }
3589 else {
3590 _setSSLError(NULL, 0, __FILE__, __LINE__);
3591 }
3592 goto error;
3593 }
3594 }
3595 goto end;
3596
3597 error:
3598 ok = 0;
3599 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003600 Py_XDECREF(cafile_bytes);
3601 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003602 if (ok) {
3603 Py_RETURN_NONE;
3604 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003605 return NULL;
3606 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003607}
3608
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003609/*[clinic input]
3610_ssl._SSLContext.load_dh_params
3611 path as filepath: object
3612 /
3613
3614[clinic start generated code]*/
3615
Antoine Pitrou152efa22010-05-16 18:19:27 +00003616static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003617_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3618/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003619{
3620 FILE *f;
3621 DH *dh;
3622
Victor Stinnerdaf45552013-08-28 00:53:59 +02003623 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003624 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003625 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003626
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003627 errno = 0;
3628 PySSL_BEGIN_ALLOW_THREADS
3629 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003630 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003631 PySSL_END_ALLOW_THREADS
3632 if (dh == NULL) {
3633 if (errno != 0) {
3634 ERR_clear_error();
3635 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3636 }
3637 else {
3638 _setSSLError(NULL, 0, __FILE__, __LINE__);
3639 }
3640 return NULL;
3641 }
3642 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3643 _setSSLError(NULL, 0, __FILE__, __LINE__);
3644 DH_free(dh);
3645 Py_RETURN_NONE;
3646}
3647
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003648/*[clinic input]
3649_ssl._SSLContext._wrap_socket
3650 sock: object(subclass_of="PySocketModule.Sock_Type")
3651 server_side: int
3652 server_hostname as hostname_obj: object = None
3653
3654[clinic start generated code]*/
3655
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003656static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003657_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3658 int server_side, PyObject *hostname_obj)
3659/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003660{
Antoine Pitroud5323212010-10-22 18:19:07 +00003661 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003662 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003663
Antoine Pitroud5323212010-10-22 18:19:07 +00003664 /* server_hostname is either None (or absent), or to be encoded
3665 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003666 if (hostname_obj != Py_None) {
3667 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003668 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003669 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003670
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003671 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3672 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003673 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003674 if (hostname != NULL)
3675 PyMem_Free(hostname);
3676 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003677}
3678
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003679/*[clinic input]
3680_ssl._SSLContext._wrap_bio
3681 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3682 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3683 server_side: int
3684 server_hostname as hostname_obj: object = None
3685
3686[clinic start generated code]*/
3687
Antoine Pitroub0182c82010-10-12 20:09:02 +00003688static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003689_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3690 PySSLMemoryBIO *outgoing, int server_side,
3691 PyObject *hostname_obj)
3692/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003693{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003694 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003695 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003696
3697 /* server_hostname is either None (or absent), or to be encoded
3698 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003699 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003700 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3701 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003702 }
3703
3704 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3705 incoming, outgoing);
3706
3707 PyMem_Free(hostname);
3708 return res;
3709}
3710
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003711/*[clinic input]
3712_ssl._SSLContext.session_stats
3713[clinic start generated code]*/
3714
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003715static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003716_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3717/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003718{
3719 int r;
3720 PyObject *value, *stats = PyDict_New();
3721 if (!stats)
3722 return NULL;
3723
3724#define ADD_STATS(SSL_NAME, KEY_NAME) \
3725 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3726 if (value == NULL) \
3727 goto error; \
3728 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3729 Py_DECREF(value); \
3730 if (r < 0) \
3731 goto error;
3732
3733 ADD_STATS(number, "number");
3734 ADD_STATS(connect, "connect");
3735 ADD_STATS(connect_good, "connect_good");
3736 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3737 ADD_STATS(accept, "accept");
3738 ADD_STATS(accept_good, "accept_good");
3739 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3740 ADD_STATS(accept, "accept");
3741 ADD_STATS(hits, "hits");
3742 ADD_STATS(misses, "misses");
3743 ADD_STATS(timeouts, "timeouts");
3744 ADD_STATS(cache_full, "cache_full");
3745
3746#undef ADD_STATS
3747
3748 return stats;
3749
3750error:
3751 Py_DECREF(stats);
3752 return NULL;
3753}
3754
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003755/*[clinic input]
3756_ssl._SSLContext.set_default_verify_paths
3757[clinic start generated code]*/
3758
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003759static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003760_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3761/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003762{
3763 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3764 _setSSLError(NULL, 0, __FILE__, __LINE__);
3765 return NULL;
3766 }
3767 Py_RETURN_NONE;
3768}
3769
Antoine Pitrou501da612011-12-21 09:27:41 +01003770#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003771/*[clinic input]
3772_ssl._SSLContext.set_ecdh_curve
3773 name: object
3774 /
3775
3776[clinic start generated code]*/
3777
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003778static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003779_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3780/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003781{
3782 PyObject *name_bytes;
3783 int nid;
3784 EC_KEY *key;
3785
3786 if (!PyUnicode_FSConverter(name, &name_bytes))
3787 return NULL;
3788 assert(PyBytes_Check(name_bytes));
3789 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3790 Py_DECREF(name_bytes);
3791 if (nid == 0) {
3792 PyErr_Format(PyExc_ValueError,
3793 "unknown elliptic curve name %R", name);
3794 return NULL;
3795 }
3796 key = EC_KEY_new_by_curve_name(nid);
3797 if (key == NULL) {
3798 _setSSLError(NULL, 0, __FILE__, __LINE__);
3799 return NULL;
3800 }
3801 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3802 EC_KEY_free(key);
3803 Py_RETURN_NONE;
3804}
Antoine Pitrou501da612011-12-21 09:27:41 +01003805#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003806
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003807#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003808static int
3809_servername_callback(SSL *s, int *al, void *args)
3810{
3811 int ret;
3812 PySSLContext *ssl_ctx = (PySSLContext *) args;
3813 PySSLSocket *ssl;
3814 PyObject *servername_o;
3815 PyObject *servername_idna;
3816 PyObject *result;
3817 /* The high-level ssl.SSLSocket object */
3818 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003819 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003820 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003821
3822 if (ssl_ctx->set_hostname == NULL) {
3823 /* remove race condition in this the call back while if removing the
3824 * callback is in progress */
3825 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003826 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003827 }
3828
3829 ssl = SSL_get_app_data(s);
3830 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003831
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003832 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003833 * SSL connection and that has a .context attribute that can be changed to
3834 * identify the requested hostname. Since the official API is the Python
3835 * level API we want to pass the callback a Python level object rather than
3836 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3837 * SSLObject) that will be passed. Otherwise if there's a socket then that
3838 * will be passed. If both do not exist only then the C-level object is
3839 * passed. */
3840 if (ssl->owner)
3841 ssl_socket = PyWeakref_GetObject(ssl->owner);
3842 else if (ssl->Socket)
3843 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3844 else
3845 ssl_socket = (PyObject *) ssl;
3846
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003847 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003848 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003849 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003850
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003851 if (servername == NULL) {
3852 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3853 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003854 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003855 else {
3856 servername_o = PyBytes_FromString(servername);
3857 if (servername_o == NULL) {
3858 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3859 goto error;
3860 }
3861 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3862 if (servername_idna == NULL) {
3863 PyErr_WriteUnraisable(servername_o);
3864 Py_DECREF(servername_o);
3865 goto error;
3866 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003867 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003868 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3869 servername_idna, ssl_ctx, NULL);
3870 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003871 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003872 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003873
3874 if (result == NULL) {
3875 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3876 *al = SSL_AD_HANDSHAKE_FAILURE;
3877 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3878 }
3879 else {
3880 if (result != Py_None) {
3881 *al = (int) PyLong_AsLong(result);
3882 if (PyErr_Occurred()) {
3883 PyErr_WriteUnraisable(result);
3884 *al = SSL_AD_INTERNAL_ERROR;
3885 }
3886 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3887 }
3888 else {
3889 ret = SSL_TLSEXT_ERR_OK;
3890 }
3891 Py_DECREF(result);
3892 }
3893
3894 PyGILState_Release(gstate);
3895 return ret;
3896
3897error:
3898 Py_DECREF(ssl_socket);
3899 *al = SSL_AD_INTERNAL_ERROR;
3900 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3901 PyGILState_Release(gstate);
3902 return ret;
3903}
Antoine Pitroua5963382013-03-30 16:39:00 +01003904#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003905
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003906/*[clinic input]
3907_ssl._SSLContext.set_servername_callback
3908 method as cb: object
3909 /
3910
3911Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3912
3913If the argument is None then the callback is disabled. The method is called
3914with the SSLSocket, the server name as a string, and the SSLContext object.
3915See RFC 6066 for details of the SNI extension.
3916[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003917
3918static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003919_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3920/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003921{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003922#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003923 Py_CLEAR(self->set_hostname);
3924 if (cb == Py_None) {
3925 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3926 }
3927 else {
3928 if (!PyCallable_Check(cb)) {
3929 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3930 PyErr_SetString(PyExc_TypeError,
3931 "not a callable object");
3932 return NULL;
3933 }
3934 Py_INCREF(cb);
3935 self->set_hostname = cb;
3936 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3937 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3938 }
3939 Py_RETURN_NONE;
3940#else
3941 PyErr_SetString(PyExc_NotImplementedError,
3942 "The TLS extension servername callback, "
3943 "SSL_CTX_set_tlsext_servername_callback, "
3944 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003945 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003946#endif
3947}
3948
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003949/*[clinic input]
3950_ssl._SSLContext.cert_store_stats
3951
3952Returns quantities of loaded X.509 certificates.
3953
3954X.509 certificates with a CA extension and certificate revocation lists
3955inside the context's cert store.
3956
3957NOTE: Certificates in a capath directory aren't loaded unless they have
3958been used at least once.
3959[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003960
3961static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003962_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3963/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003964{
3965 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003966 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003967 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003968 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003969
3970 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003971 objs = X509_STORE_get0_objects(store);
3972 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3973 obj = sk_X509_OBJECT_value(objs, i);
3974 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003975 case X509_LU_X509:
3976 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003977 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003978 ca++;
3979 }
3980 break;
3981 case X509_LU_CRL:
3982 crl++;
3983 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003984 default:
3985 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3986 * As far as I can tell they are internal states and never
3987 * stored in a cert store */
3988 break;
3989 }
3990 }
3991 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3992 "x509_ca", ca);
3993}
3994
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003995/*[clinic input]
3996_ssl._SSLContext.get_ca_certs
3997 binary_form: bool = False
3998
3999Returns a list of dicts with information of loaded CA certs.
4000
4001If the optional argument is True, returns a DER-encoded copy of the CA
4002certificate.
4003
4004NOTE: Certificates in a capath directory aren't loaded unless they have
4005been used at least once.
4006[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004007
4008static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004009_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4010/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004011{
4012 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004013 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004014 PyObject *ci = NULL, *rlist = NULL;
4015 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004016
4017 if ((rlist = PyList_New(0)) == NULL) {
4018 return NULL;
4019 }
4020
4021 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004022 objs = X509_STORE_get0_objects(store);
4023 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004024 X509_OBJECT *obj;
4025 X509 *cert;
4026
Christian Heimes598894f2016-09-05 23:19:05 +02004027 obj = sk_X509_OBJECT_value(objs, i);
4028 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004029 /* not a x509 cert */
4030 continue;
4031 }
4032 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004033 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004034 if (!X509_check_ca(cert)) {
4035 continue;
4036 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004037 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004038 ci = _certificate_to_der(cert);
4039 } else {
4040 ci = _decode_certificate(cert);
4041 }
4042 if (ci == NULL) {
4043 goto error;
4044 }
4045 if (PyList_Append(rlist, ci) == -1) {
4046 goto error;
4047 }
4048 Py_CLEAR(ci);
4049 }
4050 return rlist;
4051
4052 error:
4053 Py_XDECREF(ci);
4054 Py_XDECREF(rlist);
4055 return NULL;
4056}
4057
4058
Antoine Pitrou152efa22010-05-16 18:19:27 +00004059static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004060 {"check_hostname", (getter) get_check_hostname,
4061 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004062 {"options", (getter) get_options,
4063 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004064 {"verify_flags", (getter) get_verify_flags,
4065 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004066 {"verify_mode", (getter) get_verify_mode,
4067 (setter) set_verify_mode, NULL},
4068 {NULL}, /* sentinel */
4069};
4070
4071static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004072 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4073 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4074 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4075 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4076 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4077 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4078 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4079 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4080 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4081 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4082 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4083 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4084 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4085 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004086 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004087 {NULL, NULL} /* sentinel */
4088};
4089
4090static PyTypeObject PySSLContext_Type = {
4091 PyVarObject_HEAD_INIT(NULL, 0)
4092 "_ssl._SSLContext", /*tp_name*/
4093 sizeof(PySSLContext), /*tp_basicsize*/
4094 0, /*tp_itemsize*/
4095 (destructor)context_dealloc, /*tp_dealloc*/
4096 0, /*tp_print*/
4097 0, /*tp_getattr*/
4098 0, /*tp_setattr*/
4099 0, /*tp_reserved*/
4100 0, /*tp_repr*/
4101 0, /*tp_as_number*/
4102 0, /*tp_as_sequence*/
4103 0, /*tp_as_mapping*/
4104 0, /*tp_hash*/
4105 0, /*tp_call*/
4106 0, /*tp_str*/
4107 0, /*tp_getattro*/
4108 0, /*tp_setattro*/
4109 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004110 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004111 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004112 (traverseproc) context_traverse, /*tp_traverse*/
4113 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004114 0, /*tp_richcompare*/
4115 0, /*tp_weaklistoffset*/
4116 0, /*tp_iter*/
4117 0, /*tp_iternext*/
4118 context_methods, /*tp_methods*/
4119 0, /*tp_members*/
4120 context_getsetlist, /*tp_getset*/
4121 0, /*tp_base*/
4122 0, /*tp_dict*/
4123 0, /*tp_descr_get*/
4124 0, /*tp_descr_set*/
4125 0, /*tp_dictoffset*/
4126 0, /*tp_init*/
4127 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004128 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004129};
4130
4131
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004132/*
4133 * MemoryBIO objects
4134 */
4135
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004136/*[clinic input]
4137@classmethod
4138_ssl.MemoryBIO.__new__
4139
4140[clinic start generated code]*/
4141
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004142static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004143_ssl_MemoryBIO_impl(PyTypeObject *type)
4144/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004145{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004146 BIO *bio;
4147 PySSLMemoryBIO *self;
4148
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004149 bio = BIO_new(BIO_s_mem());
4150 if (bio == NULL) {
4151 PyErr_SetString(PySSLErrorObject,
4152 "failed to allocate BIO");
4153 return NULL;
4154 }
4155 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4156 * just that no data is currently available. The SSL routines should retry
4157 * the read, which we can achieve by calling BIO_set_retry_read(). */
4158 BIO_set_retry_read(bio);
4159 BIO_set_mem_eof_return(bio, -1);
4160
4161 assert(type != NULL && type->tp_alloc != NULL);
4162 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4163 if (self == NULL) {
4164 BIO_free(bio);
4165 return NULL;
4166 }
4167 self->bio = bio;
4168 self->eof_written = 0;
4169
4170 return (PyObject *) self;
4171}
4172
4173static void
4174memory_bio_dealloc(PySSLMemoryBIO *self)
4175{
4176 BIO_free(self->bio);
4177 Py_TYPE(self)->tp_free(self);
4178}
4179
4180static PyObject *
4181memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4182{
Segev Finer5cff6372017-07-27 01:19:17 +03004183 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184}
4185
4186PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4187"The number of bytes pending in the memory BIO.");
4188
4189static PyObject *
4190memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4191{
4192 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4193 && self->eof_written);
4194}
4195
4196PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4197"Whether the memory BIO is at EOF.");
4198
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004199/*[clinic input]
4200_ssl.MemoryBIO.read
4201 size as len: int = -1
4202 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004203
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004204Read up to size bytes from the memory BIO.
4205
4206If size is not specified, read the entire buffer.
4207If the return value is an empty bytes instance, this means either
4208EOF or that no data is available. Use the "eof" property to
4209distinguish between the two.
4210[clinic start generated code]*/
4211
4212static PyObject *
4213_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4214/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4215{
4216 int avail, nbytes;
4217 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004218
Segev Finer5cff6372017-07-27 01:19:17 +03004219 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004220 if ((len < 0) || (len > avail))
4221 len = avail;
4222
4223 result = PyBytes_FromStringAndSize(NULL, len);
4224 if ((result == NULL) || (len == 0))
4225 return result;
4226
4227 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4228 /* There should never be any short reads but check anyway. */
4229 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4230 Py_DECREF(result);
4231 return NULL;
4232 }
4233
4234 return result;
4235}
4236
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004237/*[clinic input]
4238_ssl.MemoryBIO.write
4239 b: Py_buffer
4240 /
4241
4242Writes the bytes b into the memory BIO.
4243
4244Returns the number of bytes written.
4245[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004246
4247static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004248_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4249/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004250{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004251 int nbytes;
4252
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004253 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004254 PyErr_Format(PyExc_OverflowError,
4255 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004256 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004257 }
4258
4259 if (self->eof_written) {
4260 PyErr_SetString(PySSLErrorObject,
4261 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004262 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004263 }
4264
Segev Finer5cff6372017-07-27 01:19:17 +03004265 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004266 if (nbytes < 0) {
4267 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004268 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004269 }
4270
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004271 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004272}
4273
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004274/*[clinic input]
4275_ssl.MemoryBIO.write_eof
4276
4277Write an EOF marker to the memory BIO.
4278
4279When all data has been read, the "eof" property will be True.
4280[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004281
4282static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004283_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4284/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004285{
4286 self->eof_written = 1;
4287 /* After an EOF is written, a zero return from read() should be a real EOF
4288 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4289 BIO_clear_retry_flags(self->bio);
4290 BIO_set_mem_eof_return(self->bio, 0);
4291
4292 Py_RETURN_NONE;
4293}
4294
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004295static PyGetSetDef memory_bio_getsetlist[] = {
4296 {"pending", (getter) memory_bio_get_pending, NULL,
4297 PySSL_memory_bio_pending_doc},
4298 {"eof", (getter) memory_bio_get_eof, NULL,
4299 PySSL_memory_bio_eof_doc},
4300 {NULL}, /* sentinel */
4301};
4302
4303static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004304 _SSL_MEMORYBIO_READ_METHODDEF
4305 _SSL_MEMORYBIO_WRITE_METHODDEF
4306 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004307 {NULL, NULL} /* sentinel */
4308};
4309
4310static PyTypeObject PySSLMemoryBIO_Type = {
4311 PyVarObject_HEAD_INIT(NULL, 0)
4312 "_ssl.MemoryBIO", /*tp_name*/
4313 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4314 0, /*tp_itemsize*/
4315 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4316 0, /*tp_print*/
4317 0, /*tp_getattr*/
4318 0, /*tp_setattr*/
4319 0, /*tp_reserved*/
4320 0, /*tp_repr*/
4321 0, /*tp_as_number*/
4322 0, /*tp_as_sequence*/
4323 0, /*tp_as_mapping*/
4324 0, /*tp_hash*/
4325 0, /*tp_call*/
4326 0, /*tp_str*/
4327 0, /*tp_getattro*/
4328 0, /*tp_setattro*/
4329 0, /*tp_as_buffer*/
4330 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4331 0, /*tp_doc*/
4332 0, /*tp_traverse*/
4333 0, /*tp_clear*/
4334 0, /*tp_richcompare*/
4335 0, /*tp_weaklistoffset*/
4336 0, /*tp_iter*/
4337 0, /*tp_iternext*/
4338 memory_bio_methods, /*tp_methods*/
4339 0, /*tp_members*/
4340 memory_bio_getsetlist, /*tp_getset*/
4341 0, /*tp_base*/
4342 0, /*tp_dict*/
4343 0, /*tp_descr_get*/
4344 0, /*tp_descr_set*/
4345 0, /*tp_dictoffset*/
4346 0, /*tp_init*/
4347 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004348 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004349};
4350
Antoine Pitrou152efa22010-05-16 18:19:27 +00004351
Christian Heimes99a65702016-09-10 23:44:53 +02004352/*
4353 * SSL Session object
4354 */
4355
4356static void
4357PySSLSession_dealloc(PySSLSession *self)
4358{
INADA Naokia6296d32017-08-24 14:55:17 +09004359 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004360 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004361 Py_XDECREF(self->ctx);
4362 if (self->session != NULL) {
4363 SSL_SESSION_free(self->session);
4364 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004365 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004366}
4367
4368static PyObject *
4369PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4370{
4371 int result;
4372
4373 if (left == NULL || right == NULL) {
4374 PyErr_BadInternalCall();
4375 return NULL;
4376 }
4377
4378 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4379 Py_RETURN_NOTIMPLEMENTED;
4380 }
4381
4382 if (left == right) {
4383 result = 0;
4384 } else {
4385 const unsigned char *left_id, *right_id;
4386 unsigned int left_len, right_len;
4387 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4388 &left_len);
4389 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4390 &right_len);
4391 if (left_len == right_len) {
4392 result = memcmp(left_id, right_id, left_len);
4393 } else {
4394 result = 1;
4395 }
4396 }
4397
4398 switch (op) {
4399 case Py_EQ:
4400 if (result == 0) {
4401 Py_RETURN_TRUE;
4402 } else {
4403 Py_RETURN_FALSE;
4404 }
4405 break;
4406 case Py_NE:
4407 if (result != 0) {
4408 Py_RETURN_TRUE;
4409 } else {
4410 Py_RETURN_FALSE;
4411 }
4412 break;
4413 case Py_LT:
4414 case Py_LE:
4415 case Py_GT:
4416 case Py_GE:
4417 Py_RETURN_NOTIMPLEMENTED;
4418 break;
4419 default:
4420 PyErr_BadArgument();
4421 return NULL;
4422 }
4423}
4424
4425static int
4426PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4427{
4428 Py_VISIT(self->ctx);
4429 return 0;
4430}
4431
4432static int
4433PySSLSession_clear(PySSLSession *self)
4434{
4435 Py_CLEAR(self->ctx);
4436 return 0;
4437}
4438
4439
4440static PyObject *
4441PySSLSession_get_time(PySSLSession *self, void *closure) {
4442 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4443}
4444
4445PyDoc_STRVAR(PySSLSession_get_time_doc,
4446"Session creation time (seconds since epoch).");
4447
4448
4449static PyObject *
4450PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4451 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4452}
4453
4454PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4455"Session timeout (delta in seconds).");
4456
4457
4458static PyObject *
4459PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4460 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4461 return PyLong_FromUnsignedLong(hint);
4462}
4463
4464PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4465"Ticket life time hint.");
4466
4467
4468static PyObject *
4469PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4470 const unsigned char *id;
4471 unsigned int len;
4472 id = SSL_SESSION_get_id(self->session, &len);
4473 return PyBytes_FromStringAndSize((const char *)id, len);
4474}
4475
4476PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4477"Session id");
4478
4479
4480static PyObject *
4481PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4482 if (SSL_SESSION_has_ticket(self->session)) {
4483 Py_RETURN_TRUE;
4484 } else {
4485 Py_RETURN_FALSE;
4486 }
4487}
4488
4489PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4490"Does the session contain a ticket?");
4491
4492
4493static PyGetSetDef PySSLSession_getsetlist[] = {
4494 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4495 PySSLSession_get_has_ticket_doc},
4496 {"id", (getter) PySSLSession_get_session_id, NULL,
4497 PySSLSession_get_session_id_doc},
4498 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4499 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4500 {"time", (getter) PySSLSession_get_time, NULL,
4501 PySSLSession_get_time_doc},
4502 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4503 PySSLSession_get_timeout_doc},
4504 {NULL}, /* sentinel */
4505};
4506
4507static PyTypeObject PySSLSession_Type = {
4508 PyVarObject_HEAD_INIT(NULL, 0)
4509 "_ssl.Session", /*tp_name*/
4510 sizeof(PySSLSession), /*tp_basicsize*/
4511 0, /*tp_itemsize*/
4512 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4513 0, /*tp_print*/
4514 0, /*tp_getattr*/
4515 0, /*tp_setattr*/
4516 0, /*tp_reserved*/
4517 0, /*tp_repr*/
4518 0, /*tp_as_number*/
4519 0, /*tp_as_sequence*/
4520 0, /*tp_as_mapping*/
4521 0, /*tp_hash*/
4522 0, /*tp_call*/
4523 0, /*tp_str*/
4524 0, /*tp_getattro*/
4525 0, /*tp_setattro*/
4526 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004527 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004528 0, /*tp_doc*/
4529 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4530 (inquiry)PySSLSession_clear, /*tp_clear*/
4531 PySSLSession_richcompare, /*tp_richcompare*/
4532 0, /*tp_weaklistoffset*/
4533 0, /*tp_iter*/
4534 0, /*tp_iternext*/
4535 0, /*tp_methods*/
4536 0, /*tp_members*/
4537 PySSLSession_getsetlist, /*tp_getset*/
4538};
4539
4540
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004541/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004542/*[clinic input]
4543_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004544 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004545 entropy: double
4546 /
4547
4548Mix string into the OpenSSL PRNG state.
4549
4550entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304551string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004552[clinic start generated code]*/
4553
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004555_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004556/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004557{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004558 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004559 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004560
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561 buf = (const char *)view->buf;
4562 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004563 do {
4564 written = Py_MIN(len, INT_MAX);
4565 RAND_add(buf, (int)written, entropy);
4566 buf += written;
4567 len -= written;
4568 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004569 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004570}
4571
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004572static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004573PySSL_RAND(int len, int pseudo)
4574{
4575 int ok;
4576 PyObject *bytes;
4577 unsigned long err;
4578 const char *errstr;
4579 PyObject *v;
4580
Victor Stinner1e81a392013-12-19 16:47:04 +01004581 if (len < 0) {
4582 PyErr_SetString(PyExc_ValueError, "num must be positive");
4583 return NULL;
4584 }
4585
Victor Stinner99c8b162011-05-24 12:05:19 +02004586 bytes = PyBytes_FromStringAndSize(NULL, len);
4587 if (bytes == NULL)
4588 return NULL;
4589 if (pseudo) {
4590 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4591 if (ok == 0 || ok == 1)
4592 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4593 }
4594 else {
4595 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4596 if (ok == 1)
4597 return bytes;
4598 }
4599 Py_DECREF(bytes);
4600
4601 err = ERR_get_error();
4602 errstr = ERR_reason_error_string(err);
4603 v = Py_BuildValue("(ks)", err, errstr);
4604 if (v != NULL) {
4605 PyErr_SetObject(PySSLErrorObject, v);
4606 Py_DECREF(v);
4607 }
4608 return NULL;
4609}
4610
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004611/*[clinic input]
4612_ssl.RAND_bytes
4613 n: int
4614 /
4615
4616Generate n cryptographically strong pseudo-random bytes.
4617[clinic start generated code]*/
4618
Victor Stinner99c8b162011-05-24 12:05:19 +02004619static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004620_ssl_RAND_bytes_impl(PyObject *module, int n)
4621/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004622{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004624}
4625
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004626/*[clinic input]
4627_ssl.RAND_pseudo_bytes
4628 n: int
4629 /
4630
4631Generate n pseudo-random bytes.
4632
4633Return a pair (bytes, is_cryptographic). is_cryptographic is True
4634if the bytes generated are cryptographically strong.
4635[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004636
4637static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004638_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4639/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004640{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004641 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004642}
4643
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004644/*[clinic input]
4645_ssl.RAND_status
4646
4647Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4648
4649It is necessary to seed the PRNG with RAND_add() on some platforms before
4650using the ssl() function.
4651[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004652
4653static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004654_ssl_RAND_status_impl(PyObject *module)
4655/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004656{
Christian Heimes217cfd12007-12-02 14:31:20 +00004657 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004658}
4659
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004660#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004661/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004662/*[clinic input]
4663_ssl.RAND_egd
4664 path: object(converter="PyUnicode_FSConverter")
4665 /
4666
4667Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4668
4669Returns number of bytes read. Raises SSLError if connection to EGD
4670fails or if it does not provide enough data to seed PRNG.
4671[clinic start generated code]*/
4672
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004673static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004674_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4675/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004676{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004677 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004678 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004679 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004680 PyErr_SetString(PySSLErrorObject,
4681 "EGD connection failed or EGD did not return "
4682 "enough data to seed the PRNG");
4683 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004684 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004685 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004686}
Christian Heimesa5d07652016-09-24 10:48:05 +02004687/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004688#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004689
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004690
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004691
4692/*[clinic input]
4693_ssl.get_default_verify_paths
4694
4695Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4696
4697The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4698[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004699
4700static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004701_ssl_get_default_verify_paths_impl(PyObject *module)
4702/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004703{
4704 PyObject *ofile_env = NULL;
4705 PyObject *ofile = NULL;
4706 PyObject *odir_env = NULL;
4707 PyObject *odir = NULL;
4708
Benjamin Petersond113c962015-07-18 10:59:13 -07004709#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004710 const char *tmp = (info); \
4711 target = NULL; \
4712 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4713 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4714 target = PyBytes_FromString(tmp); } \
4715 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004716 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004717
Benjamin Petersond113c962015-07-18 10:59:13 -07004718 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4719 CONVERT(X509_get_default_cert_file(), ofile);
4720 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4721 CONVERT(X509_get_default_cert_dir(), odir);
4722#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004723
Christian Heimes200bb1b2013-06-14 15:14:29 +02004724 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004725
4726 error:
4727 Py_XDECREF(ofile_env);
4728 Py_XDECREF(ofile);
4729 Py_XDECREF(odir_env);
4730 Py_XDECREF(odir);
4731 return NULL;
4732}
4733
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004734static PyObject*
4735asn1obj2py(ASN1_OBJECT *obj)
4736{
4737 int nid;
4738 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004739
4740 nid = OBJ_obj2nid(obj);
4741 if (nid == NID_undef) {
4742 PyErr_Format(PyExc_ValueError, "Unknown object");
4743 return NULL;
4744 }
4745 sn = OBJ_nid2sn(nid);
4746 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004747 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004748}
4749
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004750/*[clinic input]
4751_ssl.txt2obj
4752 txt: str
4753 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004754
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004755Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4756
4757By default objects are looked up by OID. With name=True short and
4758long name are also matched.
4759[clinic start generated code]*/
4760
4761static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004762_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4763/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004764{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004765 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004766 ASN1_OBJECT *obj;
4767
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004768 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4769 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004770 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004771 return NULL;
4772 }
4773 result = asn1obj2py(obj);
4774 ASN1_OBJECT_free(obj);
4775 return result;
4776}
4777
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004778/*[clinic input]
4779_ssl.nid2obj
4780 nid: int
4781 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004782
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004783Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4784[clinic start generated code]*/
4785
4786static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004787_ssl_nid2obj_impl(PyObject *module, int nid)
4788/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004789{
4790 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004791 ASN1_OBJECT *obj;
4792
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004793 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004794 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004795 return NULL;
4796 }
4797 obj = OBJ_nid2obj(nid);
4798 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004799 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004800 return NULL;
4801 }
4802 result = asn1obj2py(obj);
4803 ASN1_OBJECT_free(obj);
4804 return result;
4805}
4806
Christian Heimes46bebee2013-06-09 19:03:31 +02004807#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004808
4809static PyObject*
4810certEncodingType(DWORD encodingType)
4811{
4812 static PyObject *x509_asn = NULL;
4813 static PyObject *pkcs_7_asn = NULL;
4814
4815 if (x509_asn == NULL) {
4816 x509_asn = PyUnicode_InternFromString("x509_asn");
4817 if (x509_asn == NULL)
4818 return NULL;
4819 }
4820 if (pkcs_7_asn == NULL) {
4821 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4822 if (pkcs_7_asn == NULL)
4823 return NULL;
4824 }
4825 switch(encodingType) {
4826 case X509_ASN_ENCODING:
4827 Py_INCREF(x509_asn);
4828 return x509_asn;
4829 case PKCS_7_ASN_ENCODING:
4830 Py_INCREF(pkcs_7_asn);
4831 return pkcs_7_asn;
4832 default:
4833 return PyLong_FromLong(encodingType);
4834 }
4835}
4836
4837static PyObject*
4838parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4839{
4840 CERT_ENHKEY_USAGE *usage;
4841 DWORD size, error, i;
4842 PyObject *retval;
4843
4844 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4845 error = GetLastError();
4846 if (error == CRYPT_E_NOT_FOUND) {
4847 Py_RETURN_TRUE;
4848 }
4849 return PyErr_SetFromWindowsErr(error);
4850 }
4851
4852 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4853 if (usage == NULL) {
4854 return PyErr_NoMemory();
4855 }
4856
4857 /* Now get the actual enhanced usage property */
4858 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4859 PyMem_Free(usage);
4860 error = GetLastError();
4861 if (error == CRYPT_E_NOT_FOUND) {
4862 Py_RETURN_TRUE;
4863 }
4864 return PyErr_SetFromWindowsErr(error);
4865 }
4866 retval = PySet_New(NULL);
4867 if (retval == NULL) {
4868 goto error;
4869 }
4870 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4871 if (usage->rgpszUsageIdentifier[i]) {
4872 PyObject *oid;
4873 int err;
4874 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4875 if (oid == NULL) {
4876 Py_CLEAR(retval);
4877 goto error;
4878 }
4879 err = PySet_Add(retval, oid);
4880 Py_DECREF(oid);
4881 if (err == -1) {
4882 Py_CLEAR(retval);
4883 goto error;
4884 }
4885 }
4886 }
4887 error:
4888 PyMem_Free(usage);
4889 return retval;
4890}
4891
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004892/*[clinic input]
4893_ssl.enum_certificates
4894 store_name: str
4895
4896Retrieve certificates from Windows' cert store.
4897
4898store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4899more cert storages, too. The function returns a list of (bytes,
4900encoding_type, trust) tuples. The encoding_type flag can be interpreted
4901with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4902a set of OIDs or the boolean True.
4903[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004904
Christian Heimes46bebee2013-06-09 19:03:31 +02004905static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004906_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4907/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004908{
Christian Heimes46bebee2013-06-09 19:03:31 +02004909 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004910 PCCERT_CONTEXT pCertCtx = NULL;
4911 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004912 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004913
Christian Heimes44109d72013-11-22 01:51:30 +01004914 result = PyList_New(0);
4915 if (result == NULL) {
4916 return NULL;
4917 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004918 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4919 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4920 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004921 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004922 Py_DECREF(result);
4923 return PyErr_SetFromWindowsErr(GetLastError());
4924 }
4925
Christian Heimes44109d72013-11-22 01:51:30 +01004926 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4927 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4928 pCertCtx->cbCertEncoded);
4929 if (!cert) {
4930 Py_CLEAR(result);
4931 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004932 }
Christian Heimes44109d72013-11-22 01:51:30 +01004933 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4934 Py_CLEAR(result);
4935 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004936 }
Christian Heimes44109d72013-11-22 01:51:30 +01004937 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4938 if (keyusage == Py_True) {
4939 Py_DECREF(keyusage);
4940 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004941 }
Christian Heimes44109d72013-11-22 01:51:30 +01004942 if (keyusage == NULL) {
4943 Py_CLEAR(result);
4944 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004945 }
Christian Heimes44109d72013-11-22 01:51:30 +01004946 if ((tup = PyTuple_New(3)) == NULL) {
4947 Py_CLEAR(result);
4948 break;
4949 }
4950 PyTuple_SET_ITEM(tup, 0, cert);
4951 cert = NULL;
4952 PyTuple_SET_ITEM(tup, 1, enc);
4953 enc = NULL;
4954 PyTuple_SET_ITEM(tup, 2, keyusage);
4955 keyusage = NULL;
4956 if (PyList_Append(result, tup) < 0) {
4957 Py_CLEAR(result);
4958 break;
4959 }
4960 Py_CLEAR(tup);
4961 }
4962 if (pCertCtx) {
4963 /* loop ended with an error, need to clean up context manually */
4964 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004965 }
4966
4967 /* In error cases cert, enc and tup may not be NULL */
4968 Py_XDECREF(cert);
4969 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004970 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004971 Py_XDECREF(tup);
4972
4973 if (!CertCloseStore(hStore, 0)) {
4974 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004975 Py_XDECREF(result);
4976 return PyErr_SetFromWindowsErr(GetLastError());
4977 }
4978 return result;
4979}
4980
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004981/*[clinic input]
4982_ssl.enum_crls
4983 store_name: str
4984
4985Retrieve CRLs from Windows' cert store.
4986
4987store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4988more cert storages, too. The function returns a list of (bytes,
4989encoding_type) tuples. The encoding_type flag can be interpreted with
4990X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4991[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004992
4993static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004994_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4995/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004996{
Christian Heimes44109d72013-11-22 01:51:30 +01004997 HCERTSTORE hStore = NULL;
4998 PCCRL_CONTEXT pCrlCtx = NULL;
4999 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5000 PyObject *result = NULL;
5001
Christian Heimes44109d72013-11-22 01:51:30 +01005002 result = PyList_New(0);
5003 if (result == NULL) {
5004 return NULL;
5005 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005006 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5007 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5008 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005009 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005010 Py_DECREF(result);
5011 return PyErr_SetFromWindowsErr(GetLastError());
5012 }
Christian Heimes44109d72013-11-22 01:51:30 +01005013
5014 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5015 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5016 pCrlCtx->cbCrlEncoded);
5017 if (!crl) {
5018 Py_CLEAR(result);
5019 break;
5020 }
5021 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5022 Py_CLEAR(result);
5023 break;
5024 }
5025 if ((tup = PyTuple_New(2)) == NULL) {
5026 Py_CLEAR(result);
5027 break;
5028 }
5029 PyTuple_SET_ITEM(tup, 0, crl);
5030 crl = NULL;
5031 PyTuple_SET_ITEM(tup, 1, enc);
5032 enc = NULL;
5033
5034 if (PyList_Append(result, tup) < 0) {
5035 Py_CLEAR(result);
5036 break;
5037 }
5038 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005039 }
Christian Heimes44109d72013-11-22 01:51:30 +01005040 if (pCrlCtx) {
5041 /* loop ended with an error, need to clean up context manually */
5042 CertFreeCRLContext(pCrlCtx);
5043 }
5044
5045 /* In error cases cert, enc and tup may not be NULL */
5046 Py_XDECREF(crl);
5047 Py_XDECREF(enc);
5048 Py_XDECREF(tup);
5049
5050 if (!CertCloseStore(hStore, 0)) {
5051 /* This error case might shadow another exception.*/
5052 Py_XDECREF(result);
5053 return PyErr_SetFromWindowsErr(GetLastError());
5054 }
5055 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005056}
Christian Heimes44109d72013-11-22 01:51:30 +01005057
5058#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005059
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005060/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005061static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005062 _SSL__TEST_DECODE_CERT_METHODDEF
5063 _SSL_RAND_ADD_METHODDEF
5064 _SSL_RAND_BYTES_METHODDEF
5065 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5066 _SSL_RAND_EGD_METHODDEF
5067 _SSL_RAND_STATUS_METHODDEF
5068 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5069 _SSL_ENUM_CERTIFICATES_METHODDEF
5070 _SSL_ENUM_CRLS_METHODDEF
5071 _SSL_TXT2OBJ_METHODDEF
5072 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005073 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005074};
5075
5076
Christian Heimes598894f2016-09-05 23:19:05 +02005077#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005078
5079/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005080 * of the Python C thread library
5081 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5082 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005083
5084static PyThread_type_lock *_ssl_locks = NULL;
5085
Christian Heimes4d98ca92013-08-19 17:36:29 +02005086#if OPENSSL_VERSION_NUMBER >= 0x10000000
5087/* use new CRYPTO_THREADID API. */
5088static void
5089_ssl_threadid_callback(CRYPTO_THREADID *id)
5090{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005091 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005092}
5093#else
5094/* deprecated CRYPTO_set_id_callback() API. */
5095static unsigned long
5096_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005097 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005098}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005099#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005100
Bill Janssen6e027db2007-11-15 22:23:56 +00005101static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005102 (int mode, int n, const char *file, int line) {
5103 /* this function is needed to perform locking on shared data
5104 structures. (Note that OpenSSL uses a number of global data
5105 structures that will be implicitly shared whenever multiple
5106 threads use OpenSSL.) Multi-threaded applications will
5107 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005108
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005109 locking_function() must be able to handle up to
5110 CRYPTO_num_locks() different mutex locks. It sets the n-th
5111 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005113 file and line are the file number of the function setting the
5114 lock. They can be useful for debugging.
5115 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005116
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005117 if ((_ssl_locks == NULL) ||
5118 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5119 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005120
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005121 if (mode & CRYPTO_LOCK) {
5122 PyThread_acquire_lock(_ssl_locks[n], 1);
5123 } else {
5124 PyThread_release_lock(_ssl_locks[n]);
5125 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005126}
5127
5128static int _setup_ssl_threads(void) {
5129
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005130 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005131
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005132 if (_ssl_locks == NULL) {
5133 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005134 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5135 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005136 if (_ssl_locks == NULL) {
5137 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005138 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005139 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005140 for (i = 0; i < _ssl_locks_count; i++) {
5141 _ssl_locks[i] = PyThread_allocate_lock();
5142 if (_ssl_locks[i] == NULL) {
5143 unsigned int j;
5144 for (j = 0; j < i; j++) {
5145 PyThread_free_lock(_ssl_locks[j]);
5146 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005147 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005148 return 0;
5149 }
5150 }
5151 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005152#if OPENSSL_VERSION_NUMBER >= 0x10000000
5153 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5154#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005155 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005156#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005157 }
5158 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005159}
5160
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005161#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005162
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005163PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005164"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005165for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005166
Martin v. Löwis1a214512008-06-11 05:26:20 +00005167
5168static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005169 PyModuleDef_HEAD_INIT,
5170 "_ssl",
5171 module_doc,
5172 -1,
5173 PySSL_methods,
5174 NULL,
5175 NULL,
5176 NULL,
5177 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005178};
5179
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005180
5181static void
5182parse_openssl_version(unsigned long libver,
5183 unsigned int *major, unsigned int *minor,
5184 unsigned int *fix, unsigned int *patch,
5185 unsigned int *status)
5186{
5187 *status = libver & 0xF;
5188 libver >>= 4;
5189 *patch = libver & 0xFF;
5190 libver >>= 8;
5191 *fix = libver & 0xFF;
5192 libver >>= 8;
5193 *minor = libver & 0xFF;
5194 libver >>= 8;
5195 *major = libver & 0xFF;
5196}
5197
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005198PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005199PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005200{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005201 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005202 unsigned long libver;
5203 unsigned int major, minor, fix, patch, status;
5204 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005205 struct py_ssl_error_code *errcode;
5206 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005207
Antoine Pitrou152efa22010-05-16 18:19:27 +00005208 if (PyType_Ready(&PySSLContext_Type) < 0)
5209 return NULL;
5210 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005211 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005212 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5213 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005214 if (PyType_Ready(&PySSLSession_Type) < 0)
5215 return NULL;
5216
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005217
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005218 m = PyModule_Create(&_sslmodule);
5219 if (m == NULL)
5220 return NULL;
5221 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005222
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005223 /* Load _socket module and its C API */
5224 socket_api = PySocketModule_ImportModuleAndAPI();
5225 if (!socket_api)
5226 return NULL;
5227 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005228
Christian Heimesc941e622017-09-05 15:47:11 +02005229#ifndef OPENSSL_VERSION_1_1
5230 /* Load all algorithms and initialize cpuid */
5231 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005232 /* Init OpenSSL */
5233 SSL_load_error_strings();
5234 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005235#endif
5236
Christian Heimes598894f2016-09-05 23:19:05 +02005237#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005238 /* note that this will start threading if not already started */
5239 if (!_setup_ssl_threads()) {
5240 return NULL;
5241 }
Christian Heimes598894f2016-09-05 23:19:05 +02005242#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5243 /* OpenSSL 1.1.0 builtin thread support is enabled */
5244 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005245#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005247 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005248 sslerror_type_slots[0].pfunc = PyExc_OSError;
5249 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005250 if (PySSLErrorObject == NULL)
5251 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005252
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005253 /* ssl.CertificateError used to be a subclass of ValueError */
5254 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5255 if (bases == NULL)
5256 return NULL;
5257 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5258 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5259 bases, NULL);
5260 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005261 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5262 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5263 PySSLErrorObject, NULL);
5264 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5265 "ssl.SSLWantReadError", SSLWantReadError_doc,
5266 PySSLErrorObject, NULL);
5267 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5268 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5269 PySSLErrorObject, NULL);
5270 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5271 "ssl.SSLSyscallError", SSLSyscallError_doc,
5272 PySSLErrorObject, NULL);
5273 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5274 "ssl.SSLEOFError", SSLEOFError_doc,
5275 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005276 if (PySSLCertVerificationErrorObject == NULL
5277 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005278 || PySSLWantReadErrorObject == NULL
5279 || PySSLWantWriteErrorObject == NULL
5280 || PySSLSyscallErrorObject == NULL
5281 || PySSLEOFErrorObject == NULL)
5282 return NULL;
5283 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005284 || PyDict_SetItemString(d, "SSLCertVerificationError",
5285 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005286 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5287 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5288 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5289 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5290 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005291 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005292 if (PyDict_SetItemString(d, "_SSLContext",
5293 (PyObject *)&PySSLContext_Type) != 0)
5294 return NULL;
5295 if (PyDict_SetItemString(d, "_SSLSocket",
5296 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005297 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005298 if (PyDict_SetItemString(d, "MemoryBIO",
5299 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5300 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005301 if (PyDict_SetItemString(d, "SSLSession",
5302 (PyObject *)&PySSLSession_Type) != 0)
5303 return NULL;
5304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005305 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5306 PY_SSL_ERROR_ZERO_RETURN);
5307 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5308 PY_SSL_ERROR_WANT_READ);
5309 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5310 PY_SSL_ERROR_WANT_WRITE);
5311 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5312 PY_SSL_ERROR_WANT_X509_LOOKUP);
5313 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5314 PY_SSL_ERROR_SYSCALL);
5315 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5316 PY_SSL_ERROR_SSL);
5317 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5318 PY_SSL_ERROR_WANT_CONNECT);
5319 /* non ssl.h errorcodes */
5320 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5321 PY_SSL_ERROR_EOF);
5322 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5323 PY_SSL_ERROR_INVALID_ERROR_CODE);
5324 /* cert requirements */
5325 PyModule_AddIntConstant(m, "CERT_NONE",
5326 PY_SSL_CERT_NONE);
5327 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5328 PY_SSL_CERT_OPTIONAL);
5329 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5330 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005331 /* CRL verification for verification_flags */
5332 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5333 0);
5334 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5335 X509_V_FLAG_CRL_CHECK);
5336 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5337 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5338 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5339 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005340#ifdef X509_V_FLAG_TRUSTED_FIRST
5341 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5342 X509_V_FLAG_TRUSTED_FIRST);
5343#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005344
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005345 /* Alert Descriptions from ssl.h */
5346 /* note RESERVED constants no longer intended for use have been removed */
5347 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5348
5349#define ADD_AD_CONSTANT(s) \
5350 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5351 SSL_AD_##s)
5352
5353 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5354 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5355 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5356 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5357 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5358 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5359 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5360 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5361 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5362 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5363 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5364 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5365 ADD_AD_CONSTANT(UNKNOWN_CA);
5366 ADD_AD_CONSTANT(ACCESS_DENIED);
5367 ADD_AD_CONSTANT(DECODE_ERROR);
5368 ADD_AD_CONSTANT(DECRYPT_ERROR);
5369 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5370 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5371 ADD_AD_CONSTANT(INTERNAL_ERROR);
5372 ADD_AD_CONSTANT(USER_CANCELLED);
5373 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005374 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005375#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5376 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5377#endif
5378#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5379 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5380#endif
5381#ifdef SSL_AD_UNRECOGNIZED_NAME
5382 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5383#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005384#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5385 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5386#endif
5387#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5388 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5389#endif
5390#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5391 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5392#endif
5393
5394#undef ADD_AD_CONSTANT
5395
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005396 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005397#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005398 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5399 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005400#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005401#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005402 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5403 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005404#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005405 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005406 PY_SSL_VERSION_TLS);
5407 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5408 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005409 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5410 PY_SSL_VERSION_TLS_CLIENT);
5411 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5412 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005413 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5414 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005415#if HAVE_TLSv1_2
5416 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5417 PY_SSL_VERSION_TLS1_1);
5418 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5419 PY_SSL_VERSION_TLS1_2);
5420#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005421
Antoine Pitroub5218772010-05-21 09:56:06 +00005422 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005423 PyModule_AddIntConstant(m, "OP_ALL",
5424 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005425 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5426 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5427 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005428#if HAVE_TLSv1_2
5429 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5430 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5431#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005432#ifdef SSL_OP_NO_TLSv1_3
5433 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5434#else
5435 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5436#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005437 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5438 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005439 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005440 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005441#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005442 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005443#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005444#ifdef SSL_OP_NO_COMPRESSION
5445 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5446 SSL_OP_NO_COMPRESSION);
5447#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005448
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005449#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005450 r = Py_True;
5451#else
5452 r = Py_False;
5453#endif
5454 Py_INCREF(r);
5455 PyModule_AddObject(m, "HAS_SNI", r);
5456
Antoine Pitroud6494802011-07-21 01:11:30 +02005457 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005458 Py_INCREF(r);
5459 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5460
Antoine Pitrou501da612011-12-21 09:27:41 +01005461#ifdef OPENSSL_NO_ECDH
5462 r = Py_False;
5463#else
5464 r = Py_True;
5465#endif
5466 Py_INCREF(r);
5467 PyModule_AddObject(m, "HAS_ECDH", r);
5468
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005469#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005470 r = Py_True;
5471#else
5472 r = Py_False;
5473#endif
5474 Py_INCREF(r);
5475 PyModule_AddObject(m, "HAS_NPN", r);
5476
Benjamin Petersoncca27322015-01-23 16:35:37 -05005477#ifdef HAVE_ALPN
5478 r = Py_True;
5479#else
5480 r = Py_False;
5481#endif
5482 Py_INCREF(r);
5483 PyModule_AddObject(m, "HAS_ALPN", r);
5484
Christian Heimescb5b68a2017-09-07 18:07:00 -07005485#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5486 r = Py_True;
5487#else
5488 r = Py_False;
5489#endif
5490 Py_INCREF(r);
5491 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5492
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005493 /* Mappings for error codes */
5494 err_codes_to_names = PyDict_New();
5495 err_names_to_codes = PyDict_New();
5496 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5497 return NULL;
5498 errcode = error_codes;
5499 while (errcode->mnemonic != NULL) {
5500 PyObject *mnemo, *key;
5501 mnemo = PyUnicode_FromString(errcode->mnemonic);
5502 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5503 if (mnemo == NULL || key == NULL)
5504 return NULL;
5505 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5506 return NULL;
5507 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5508 return NULL;
5509 Py_DECREF(key);
5510 Py_DECREF(mnemo);
5511 errcode++;
5512 }
5513 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5514 return NULL;
5515 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5516 return NULL;
5517
5518 lib_codes_to_names = PyDict_New();
5519 if (lib_codes_to_names == NULL)
5520 return NULL;
5521 libcode = library_codes;
5522 while (libcode->library != NULL) {
5523 PyObject *mnemo, *key;
5524 key = PyLong_FromLong(libcode->code);
5525 mnemo = PyUnicode_FromString(libcode->library);
5526 if (key == NULL || mnemo == NULL)
5527 return NULL;
5528 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5529 return NULL;
5530 Py_DECREF(key);
5531 Py_DECREF(mnemo);
5532 libcode++;
5533 }
5534 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5535 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005536
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005537 /* OpenSSL version */
5538 /* SSLeay() gives us the version of the library linked against,
5539 which could be different from the headers version.
5540 */
5541 libver = SSLeay();
5542 r = PyLong_FromUnsignedLong(libver);
5543 if (r == NULL)
5544 return NULL;
5545 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5546 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005547 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005548 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5549 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5550 return NULL;
5551 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5552 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5553 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005554
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005555 libver = OPENSSL_VERSION_NUMBER;
5556 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5557 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5558 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5559 return NULL;
5560
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005561 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005562}