blob: b001bca99d9e1f951e54838a10542abf420e1d83 [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#ifdef WITH_THREAD
22#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020023
Steve Dower68d663c2017-07-17 11:15:48 +020024/* Redefined below for Windows debug builds after important #includes */
25#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020026
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020027#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
28 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
29#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020030 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000031#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000032 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020033 PySSL_BEGIN_ALLOW_THREADS_S(_save);
34#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
35#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
36#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000037
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000038#else /* no WITH_THREAD */
Thomas Wouters1b7f8912007-09-19 03:06:30 +000039
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020040#define PySSL_BEGIN_ALLOW_THREADS_S(save)
41#define PySSL_END_ALLOW_THREADS_S(save)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000042#define PySSL_BEGIN_ALLOW_THREADS
43#define PySSL_BLOCK_THREADS
44#define PySSL_UNBLOCK_THREADS
45#define PySSL_END_ALLOW_THREADS
46
47#endif
48
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010049/* Include symbols from _socket module */
50#include "socketmodule.h"
51
52static PySocketModule_APIObject PySocketModule;
53
54#if defined(HAVE_POLL_H)
55#include <poll.h>
56#elif defined(HAVE_SYS_POLL_H)
57#include <sys/poll.h>
58#endif
59
Christian Heimes598894f2016-09-05 23:19:05 +020060/* Don't warn about deprecated functions */
61#ifdef __GNUC__
62#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
63#endif
64#ifdef __clang__
65#pragma clang diagnostic ignored "-Wdeprecated-declarations"
66#endif
67
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010068/* Include OpenSSL header files */
69#include "openssl/rsa.h"
70#include "openssl/crypto.h"
71#include "openssl/x509.h"
72#include "openssl/x509v3.h"
73#include "openssl/pem.h"
74#include "openssl/ssl.h"
75#include "openssl/err.h"
76#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020077#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010078
79/* SSL error object */
80static PyObject *PySSLErrorObject;
81static PyObject *PySSLZeroReturnErrorObject;
82static PyObject *PySSLWantReadErrorObject;
83static PyObject *PySSLWantWriteErrorObject;
84static PyObject *PySSLSyscallErrorObject;
85static PyObject *PySSLEOFErrorObject;
86
87/* Error mappings */
88static PyObject *err_codes_to_names;
89static PyObject *err_names_to_codes;
90static PyObject *lib_codes_to_names;
91
92struct py_ssl_error_code {
93 const char *mnemonic;
94 int library, reason;
95};
96struct py_ssl_library_code {
97 const char *library;
98 int code;
99};
100
Steve Dower68d663c2017-07-17 11:15:48 +0200101#if defined(MS_WINDOWS) && defined(Py_DEBUG)
102/* Debug builds on Windows rely on getting errno directly from OpenSSL.
103 * However, because it uses a different CRT, we need to transfer the
104 * value of errno from OpenSSL into our debug CRT.
105 *
106 * Don't be fooled - this is horribly ugly code. The only reasonable
107 * alternative is to do both debug and release builds of OpenSSL, which
108 * requires much uglier code to transform their automatically generated
109 * makefile. This is the lesser of all the evils.
110 */
111
112static void _PySSLFixErrno(void) {
113 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
114 if (!ucrtbase) {
115 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
116 * have a catastrophic failure, but this function is not the
117 * place to raise it. */
118 return;
119 }
120
121 typedef int *(__stdcall *errno_func)(void);
122 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
123 if (ssl_errno) {
124 errno = *ssl_errno();
125 *ssl_errno() = 0;
126 } else {
127 errno = ENOTRECOVERABLE;
128 }
129}
130
131#undef _PySSL_FIX_ERRNO
132#define _PySSL_FIX_ERRNO _PySSLFixErrno()
133#endif
134
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100135/* Include generated data (error codes) */
136#include "_ssl_data.h"
137
Christian Heimes598894f2016-09-05 23:19:05 +0200138#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
139# define OPENSSL_VERSION_1_1 1
140#endif
141
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100142/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
143 http://www.openssl.org/news/changelog.html
144 */
145#if OPENSSL_VERSION_NUMBER >= 0x10001000L
146# define HAVE_TLSv1_2 1
147#else
148# define HAVE_TLSv1_2 0
149#endif
150
Christian Heimes470fba12013-11-28 15:12:15 +0100151/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100152 * This includes the SSL_set_SSL_CTX() function.
153 */
154#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
155# define HAVE_SNI 1
156#else
157# define HAVE_SNI 0
158#endif
159
Benjamin Petersond3308222015-09-27 00:09:02 -0700160#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500161# define HAVE_ALPN
162#endif
163
Victor Stinner524714e2016-07-22 17:43:59 +0200164#ifndef INVALID_SOCKET /* MS defines this */
165#define INVALID_SOCKET (-1)
166#endif
167
Christian Heimes598894f2016-09-05 23:19:05 +0200168#ifdef OPENSSL_VERSION_1_1
169/* OpenSSL 1.1.0+ */
170#ifndef OPENSSL_NO_SSL2
171#define OPENSSL_NO_SSL2
172#endif
173#else /* OpenSSL < 1.1.0 */
174#if defined(WITH_THREAD)
175#define HAVE_OPENSSL_CRYPTO_LOCK
176#endif
177
178#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200179#define TLS_client_method SSLv23_client_method
180#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200181
182static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
183{
184 return ne->set;
185}
186
187#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200188/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200189static int COMP_get_type(const COMP_METHOD *meth)
190{
191 return meth->type;
192}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200193/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200194#endif
195
196static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
197{
198 return ctx->default_passwd_callback;
199}
200
201static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
202{
203 return ctx->default_passwd_callback_userdata;
204}
205
206static int X509_OBJECT_get_type(X509_OBJECT *x)
207{
208 return x->type;
209}
210
211static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
212{
213 return x->data.x509;
214}
215
216static int BIO_up_ref(BIO *b)
217{
218 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
219 return 1;
220}
221
222static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
223 return store->objs;
224}
225
226static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
227{
228 return store->param;
229}
Christian Heimes99a65702016-09-10 23:44:53 +0200230
231static int
232SSL_SESSION_has_ticket(const SSL_SESSION *s)
233{
234 return (s->tlsext_ticklen > 0) ? 1 : 0;
235}
236
237static unsigned long
238SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
239{
240 return s->tlsext_tick_lifetime_hint;
241}
242
Christian Heimes598894f2016-09-05 23:19:05 +0200243#endif /* OpenSSL < 1.1.0 or LibreSSL */
244
245
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000246enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000247 /* these mirror ssl.h */
248 PY_SSL_ERROR_NONE,
249 PY_SSL_ERROR_SSL,
250 PY_SSL_ERROR_WANT_READ,
251 PY_SSL_ERROR_WANT_WRITE,
252 PY_SSL_ERROR_WANT_X509_LOOKUP,
253 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
254 PY_SSL_ERROR_ZERO_RETURN,
255 PY_SSL_ERROR_WANT_CONNECT,
256 /* start of non ssl.h errorcodes */
257 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
258 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
259 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000260};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000261
Thomas Woutersed03b412007-08-28 21:37:11 +0000262enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000263 PY_SSL_CLIENT,
264 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000265};
266
267enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000268 PY_SSL_CERT_NONE,
269 PY_SSL_CERT_OPTIONAL,
270 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000271};
272
273enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000274 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200275 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200276 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100277#if HAVE_TLSv1_2
278 PY_SSL_VERSION_TLS1,
279 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200280 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100281#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200282 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000283#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200284 PY_SSL_VERSION_TLS_CLIENT=0x10,
285 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100286};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200287
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000288#ifdef WITH_THREAD
289
290/* serves as a flag to see whether we've initialized the SSL thread support. */
291/* 0 means no, greater than 0 means yes */
292
293static unsigned int _ssl_locks_count = 0;
294
295#endif /* def WITH_THREAD */
296
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000297/* SSL socket object */
298
299#define X509_NAME_MAXLEN 256
300
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000301/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
302 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
303 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
304#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000305# define HAVE_SSL_CTX_CLEAR_OPTIONS
306#else
307# undef HAVE_SSL_CTX_CLEAR_OPTIONS
308#endif
309
Antoine Pitroud6494802011-07-21 01:11:30 +0200310/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
311 * older SSL, but let's be safe */
312#define PySSL_CB_MAXLEN 128
313
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100314
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000315typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000316 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000317 SSL_CTX *ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +0200318#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500319 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100320 int npn_protocols_len;
321#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500322#ifdef HAVE_ALPN
323 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300324 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500325#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100326#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200327 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100328#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100329 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000330} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000331
Antoine Pitrou152efa22010-05-16 18:19:27 +0000332typedef struct {
333 PyObject_HEAD
334 PyObject *Socket; /* weakref to socket on which we're layered */
335 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100336 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200337 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200338 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200339 PyObject *owner; /* Python level "owner" passed to servername callback */
340 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000341} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000342
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200343typedef struct {
344 PyObject_HEAD
345 BIO *bio;
346 int eof_written;
347} PySSLMemoryBIO;
348
Christian Heimes99a65702016-09-10 23:44:53 +0200349typedef struct {
350 PyObject_HEAD
351 SSL_SESSION *session;
352 PySSLContext *ctx;
353} PySSLSession;
354
Antoine Pitrou152efa22010-05-16 18:19:27 +0000355static PyTypeObject PySSLContext_Type;
356static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200357static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200358static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000359
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300360/*[clinic input]
361module _ssl
362class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
363class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
364class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200365class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300366[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200367/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300368
369#include "clinic/_ssl.c.h"
370
Victor Stinner14690702015-04-06 22:46:13 +0200371static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000372
Christian Heimes99a65702016-09-10 23:44:53 +0200373
Antoine Pitrou152efa22010-05-16 18:19:27 +0000374#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
375#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200376#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200377#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000378
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000379typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000380 SOCKET_IS_NONBLOCKING,
381 SOCKET_IS_BLOCKING,
382 SOCKET_HAS_TIMED_OUT,
383 SOCKET_HAS_BEEN_CLOSED,
384 SOCKET_TOO_LARGE_FOR_SELECT,
385 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000386} timeout_state;
387
Thomas Woutersed03b412007-08-28 21:37:11 +0000388/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000389#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200390#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000391
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200392/* Get the socket from a PySSLSocket, if it has one */
393#define GET_SOCKET(obj) ((obj)->Socket ? \
394 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200395
Victor Stinner14690702015-04-06 22:46:13 +0200396/* If sock is NULL, use a timeout of 0 second */
397#define GET_SOCKET_TIMEOUT(sock) \
398 ((sock != NULL) ? (sock)->sock_timeout : 0)
399
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200400/*
401 * SSL errors.
402 */
403
404PyDoc_STRVAR(SSLError_doc,
405"An error occurred in the SSL implementation.");
406
407PyDoc_STRVAR(SSLZeroReturnError_doc,
408"SSL/TLS session closed cleanly.");
409
410PyDoc_STRVAR(SSLWantReadError_doc,
411"Non-blocking SSL socket needs to read more data\n"
412"before the requested operation can be completed.");
413
414PyDoc_STRVAR(SSLWantWriteError_doc,
415"Non-blocking SSL socket needs to write more data\n"
416"before the requested operation can be completed.");
417
418PyDoc_STRVAR(SSLSyscallError_doc,
419"System error when attempting SSL operation.");
420
421PyDoc_STRVAR(SSLEOFError_doc,
422"SSL/TLS connection terminated abruptly.");
423
424static PyObject *
425SSLError_str(PyOSErrorObject *self)
426{
427 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
428 Py_INCREF(self->strerror);
429 return self->strerror;
430 }
431 else
432 return PyObject_Str(self->args);
433}
434
435static PyType_Slot sslerror_type_slots[] = {
436 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
437 {Py_tp_doc, SSLError_doc},
438 {Py_tp_str, SSLError_str},
439 {0, 0},
440};
441
442static PyType_Spec sslerror_type_spec = {
443 "ssl.SSLError",
444 sizeof(PyOSErrorObject),
445 0,
446 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
447 sslerror_type_slots
448};
449
450static void
451fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
452 int lineno, unsigned long errcode)
453{
454 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
455 PyObject *init_value, *msg, *key;
456 _Py_IDENTIFIER(reason);
457 _Py_IDENTIFIER(library);
458
459 if (errcode != 0) {
460 int lib, reason;
461
462 lib = ERR_GET_LIB(errcode);
463 reason = ERR_GET_REASON(errcode);
464 key = Py_BuildValue("ii", lib, reason);
465 if (key == NULL)
466 goto fail;
467 reason_obj = PyDict_GetItem(err_codes_to_names, key);
468 Py_DECREF(key);
469 if (reason_obj == NULL) {
470 /* XXX if reason < 100, it might reflect a library number (!!) */
471 PyErr_Clear();
472 }
473 key = PyLong_FromLong(lib);
474 if (key == NULL)
475 goto fail;
476 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
477 Py_DECREF(key);
478 if (lib_obj == NULL) {
479 PyErr_Clear();
480 }
481 if (errstr == NULL)
482 errstr = ERR_reason_error_string(errcode);
483 }
484 if (errstr == NULL)
485 errstr = "unknown error";
486
487 if (reason_obj && lib_obj)
488 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
489 lib_obj, reason_obj, errstr, lineno);
490 else if (lib_obj)
491 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
492 lib_obj, errstr, lineno);
493 else
494 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200495 if (msg == NULL)
496 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100497
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200498 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100499 if (init_value == NULL)
500 goto fail;
501
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200502 err_value = PyObject_CallObject(type, init_value);
503 Py_DECREF(init_value);
504 if (err_value == NULL)
505 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100506
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200507 if (reason_obj == NULL)
508 reason_obj = Py_None;
509 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
510 goto fail;
511 if (lib_obj == NULL)
512 lib_obj = Py_None;
513 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
514 goto fail;
515 PyErr_SetObject(type, err_value);
516fail:
517 Py_XDECREF(err_value);
518}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000519
520static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200521PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000522{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200523 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200524 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000525 int err;
526 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200527 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000528
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000529 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200530 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000531
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000532 if (obj->ssl != NULL) {
533 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000534
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000535 switch (err) {
536 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200537 errstr = "TLS/SSL connection has been closed (EOF)";
538 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000539 p = PY_SSL_ERROR_ZERO_RETURN;
540 break;
541 case SSL_ERROR_WANT_READ:
542 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200543 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000544 p = PY_SSL_ERROR_WANT_READ;
545 break;
546 case SSL_ERROR_WANT_WRITE:
547 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200548 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000549 errstr = "The operation did not complete (write)";
550 break;
551 case SSL_ERROR_WANT_X509_LOOKUP:
552 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000553 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000554 break;
555 case SSL_ERROR_WANT_CONNECT:
556 p = PY_SSL_ERROR_WANT_CONNECT;
557 errstr = "The operation did not complete (connect)";
558 break;
559 case SSL_ERROR_SYSCALL:
560 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000561 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200562 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000564 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200565 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000566 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200567 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000568 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000569 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000570 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000572 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200573 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000574 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000575 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200576 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000577 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000578 }
579 } else {
580 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 }
582 break;
583 }
584 case SSL_ERROR_SSL:
585 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000586 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200587 if (e == 0)
588 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000589 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000590 break;
591 }
592 default:
593 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
594 errstr = "Invalid error code";
595 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000596 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000598 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000600}
601
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000602static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200603_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000604
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200605 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200607 else
608 errcode = 0;
609 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000610 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000612}
613
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200614/*
615 * SSL objects
616 */
617
Antoine Pitrou152efa22010-05-16 18:19:27 +0000618static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100619newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000620 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200621 char *server_hostname,
622 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000623{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000624 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100625 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200626 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000627
Antoine Pitrou152efa22010-05-16 18:19:27 +0000628 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000629 if (self == NULL)
630 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000631
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000632 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100634 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700635 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200636 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200637 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700638 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200639 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700640 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
641 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200642 if (hostname == NULL) {
643 Py_DECREF(self);
644 return NULL;
645 }
646 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700647 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200648
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000649 /* Make sure the SSL error state is initialized */
650 (void) ERR_get_state();
651 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000652
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000653 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000654 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000655 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200656 SSL_set_app_data(self->ssl, self);
657 if (sock) {
658 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
659 } else {
660 /* BIOs are reference counted and SSL_set_bio borrows our reference.
661 * To prevent a double free in memory_bio_dealloc() we need to take an
662 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200663 BIO_up_ref(inbio->bio);
664 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200665 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
666 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200667 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000668#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200669 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000670#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200671 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000672
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100673#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000674 if (server_hostname != NULL)
675 SSL_set_tlsext_host_name(self->ssl, server_hostname);
676#endif
677
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000678 /* If the socket is in non-blocking mode or timeout mode, set the BIO
679 * to non-blocking mode (blocking is the default)
680 */
Victor Stinnere2452312015-03-28 03:00:46 +0100681 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
683 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
684 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000685
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 PySSL_BEGIN_ALLOW_THREADS
687 if (socket_type == PY_SSL_CLIENT)
688 SSL_set_connect_state(self->ssl);
689 else
690 SSL_set_accept_state(self->ssl);
691 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000692
Antoine Pitroud6494802011-07-21 01:11:30 +0200693 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200694 if (sock != NULL) {
695 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
696 if (self->Socket == NULL) {
697 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200698 return NULL;
699 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100700 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000702}
703
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000704/* SSL object methods */
705
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300706/*[clinic input]
707_ssl._SSLSocket.do_handshake
708[clinic start generated code]*/
709
710static PyObject *
711_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
712/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000713{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000714 int ret;
715 int err;
716 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200717 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200718 _PyTime_t timeout, deadline = 0;
719 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000720
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200721 if (sock) {
722 if (((PyObject*)sock) == Py_None) {
723 _setSSLError("Underlying socket connection gone",
724 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
725 return NULL;
726 }
727 Py_INCREF(sock);
728
729 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100730 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200731 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
732 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000734
Victor Stinner14690702015-04-06 22:46:13 +0200735 timeout = GET_SOCKET_TIMEOUT(sock);
736 has_timeout = (timeout > 0);
737 if (has_timeout)
738 deadline = _PyTime_GetMonotonicClock() + timeout;
739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 /* Actually negotiate SSL connection */
741 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000742 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000743 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 ret = SSL_do_handshake(self->ssl);
745 err = SSL_get_error(self->ssl, ret);
746 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200747
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000748 if (PyErr_CheckSignals())
749 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200750
Victor Stinner14690702015-04-06 22:46:13 +0200751 if (has_timeout)
752 timeout = deadline - _PyTime_GetMonotonicClock();
753
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000754 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200755 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200757 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000758 } else {
759 sockstate = SOCKET_OPERATION_OK;
760 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200761
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000762 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000763 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000764 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000765 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000766 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
767 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000768 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000769 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000770 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
771 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000772 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000773 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000774 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
775 break;
776 }
777 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200778 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000779 if (ret < 1)
780 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000781
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200782 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000783
784error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200785 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000786 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000787}
788
Thomas Woutersed03b412007-08-28 21:37:11 +0000789static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300790_asn1obj2py(const ASN1_OBJECT *name, int no_name)
791{
792 char buf[X509_NAME_MAXLEN];
793 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000794 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300795 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000796
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300797 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000798 if (buflen < 0) {
799 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300800 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000801 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300802 /* initial buffer is too small for oid + terminating null byte */
803 if (buflen > X509_NAME_MAXLEN - 1) {
804 /* make OBJ_obj2txt() calculate the required buflen */
805 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
806 /* allocate len + 1 for terminating NULL byte */
807 namebuf = PyMem_Malloc(buflen + 1);
808 if (namebuf == NULL) {
809 PyErr_NoMemory();
810 return NULL;
811 }
812 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
813 if (buflen < 0) {
814 _setSSLError(NULL, 0, __FILE__, __LINE__);
815 goto done;
816 }
817 }
818 if (!buflen && no_name) {
819 Py_INCREF(Py_None);
820 name_obj = Py_None;
821 }
822 else {
823 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
824 }
825
826 done:
827 if (buf != namebuf) {
828 PyMem_Free(namebuf);
829 }
830 return name_obj;
831}
832
833static PyObject *
834_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
835{
836 Py_ssize_t buflen;
837 unsigned char *valuebuf = NULL;
838 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000839
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
841 if (buflen < 0) {
842 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300843 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000844 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300845 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000848}
849
850static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000851_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000852{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000853 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
854 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
855 PyObject *rdnt;
856 PyObject *attr = NULL; /* tuple to hold an attribute */
857 int entry_count = X509_NAME_entry_count(xname);
858 X509_NAME_ENTRY *entry;
859 ASN1_OBJECT *name;
860 ASN1_STRING *value;
861 int index_counter;
862 int rdn_level = -1;
863 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000864
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 dn = PyList_New(0);
866 if (dn == NULL)
867 return NULL;
868 /* now create another tuple to hold the top-level RDN */
869 rdn = PyList_New(0);
870 if (rdn == NULL)
871 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000872
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000873 for (index_counter = 0;
874 index_counter < entry_count;
875 index_counter++)
876 {
877 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000879 /* check to see if we've gotten to a new RDN */
880 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200881 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 /* yes, new RDN */
883 /* add old RDN to DN */
884 rdnt = PyList_AsTuple(rdn);
885 Py_DECREF(rdn);
886 if (rdnt == NULL)
887 goto fail0;
888 retcode = PyList_Append(dn, rdnt);
889 Py_DECREF(rdnt);
890 if (retcode < 0)
891 goto fail0;
892 /* create new RDN */
893 rdn = PyList_New(0);
894 if (rdn == NULL)
895 goto fail0;
896 }
897 }
Christian Heimes598894f2016-09-05 23:19:05 +0200898 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000899
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000900 /* now add this attribute to the current RDN */
901 name = X509_NAME_ENTRY_get_object(entry);
902 value = X509_NAME_ENTRY_get_data(entry);
903 attr = _create_tuple_for_attribute(name, value);
904 /*
905 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
906 entry->set,
907 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
908 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
909 */
910 if (attr == NULL)
911 goto fail1;
912 retcode = PyList_Append(rdn, attr);
913 Py_DECREF(attr);
914 if (retcode < 0)
915 goto fail1;
916 }
917 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100918 if (rdn != NULL) {
919 if (PyList_GET_SIZE(rdn) > 0) {
920 rdnt = PyList_AsTuple(rdn);
921 Py_DECREF(rdn);
922 if (rdnt == NULL)
923 goto fail0;
924 retcode = PyList_Append(dn, rdnt);
925 Py_DECREF(rdnt);
926 if (retcode < 0)
927 goto fail0;
928 }
929 else {
930 Py_DECREF(rdn);
931 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000932 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* convert list to tuple */
935 rdnt = PyList_AsTuple(dn);
936 Py_DECREF(dn);
937 if (rdnt == NULL)
938 return NULL;
939 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000940
941 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000942 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000943
944 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 Py_XDECREF(dn);
946 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000947}
948
949static PyObject *
950_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000951
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000952 /* this code follows the procedure outlined in
953 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
954 function to extract the STACK_OF(GENERAL_NAME),
955 then iterates through the stack to add the
956 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000957
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400958 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200960 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000961 GENERAL_NAMES *names = NULL;
962 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 BIO *biobuf = NULL;
964 char buf[2048];
965 char *vptr;
966 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 if (certificate == NULL)
969 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000970
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000971 /* get a memory buffer */
972 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000973
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400974 names = (GENERAL_NAMES *)X509_get_ext_d2i(
975 certificate, NID_subject_alt_name, NULL, NULL);
976 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 if (peer_alt_names == Py_None) {
978 peer_alt_names = PyList_New(0);
979 if (peer_alt_names == NULL)
980 goto fail;
981 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000982
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000983 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200985 int gntype;
986 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000987
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000988 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200989 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200990 switch (gntype) {
991 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 /* we special-case DirName as a tuple of
993 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000995 t = PyTuple_New(2);
996 if (t == NULL) {
997 goto fail;
998 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000999
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001000 v = PyUnicode_FromString("DirName");
1001 if (v == NULL) {
1002 Py_DECREF(t);
1003 goto fail;
1004 }
1005 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001007 v = _create_tuple_for_X509_NAME (name->d.dirn);
1008 if (v == NULL) {
1009 Py_DECREF(t);
1010 goto fail;
1011 }
1012 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001013 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001014
Christian Heimes824f7f32013-08-17 00:54:47 +02001015 case GEN_EMAIL:
1016 case GEN_DNS:
1017 case GEN_URI:
1018 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1019 correctly, CVE-2013-4238 */
1020 t = PyTuple_New(2);
1021 if (t == NULL)
1022 goto fail;
1023 switch (gntype) {
1024 case GEN_EMAIL:
1025 v = PyUnicode_FromString("email");
1026 as = name->d.rfc822Name;
1027 break;
1028 case GEN_DNS:
1029 v = PyUnicode_FromString("DNS");
1030 as = name->d.dNSName;
1031 break;
1032 case GEN_URI:
1033 v = PyUnicode_FromString("URI");
1034 as = name->d.uniformResourceIdentifier;
1035 break;
1036 }
1037 if (v == NULL) {
1038 Py_DECREF(t);
1039 goto fail;
1040 }
1041 PyTuple_SET_ITEM(t, 0, v);
1042 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1043 ASN1_STRING_length(as));
1044 if (v == NULL) {
1045 Py_DECREF(t);
1046 goto fail;
1047 }
1048 PyTuple_SET_ITEM(t, 1, v);
1049 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001050
Christian Heimes1c03abd2016-09-06 23:25:35 +02001051 case GEN_RID:
1052 t = PyTuple_New(2);
1053 if (t == NULL)
1054 goto fail;
1055
1056 v = PyUnicode_FromString("Registered ID");
1057 if (v == NULL) {
1058 Py_DECREF(t);
1059 goto fail;
1060 }
1061 PyTuple_SET_ITEM(t, 0, v);
1062
1063 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1064 if (len < 0) {
1065 Py_DECREF(t);
1066 _setSSLError(NULL, 0, __FILE__, __LINE__);
1067 goto fail;
1068 } else if (len >= (int)sizeof(buf)) {
1069 v = PyUnicode_FromString("<INVALID>");
1070 } else {
1071 v = PyUnicode_FromStringAndSize(buf, len);
1072 }
1073 if (v == NULL) {
1074 Py_DECREF(t);
1075 goto fail;
1076 }
1077 PyTuple_SET_ITEM(t, 1, v);
1078 break;
1079
Christian Heimes824f7f32013-08-17 00:54:47 +02001080 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001081 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001082 switch (gntype) {
1083 /* check for new general name type */
1084 case GEN_OTHERNAME:
1085 case GEN_X400:
1086 case GEN_EDIPARTY:
1087 case GEN_IPADD:
1088 case GEN_RID:
1089 break;
1090 default:
1091 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1092 "Unknown general name type %d",
1093 gntype) == -1) {
1094 goto fail;
1095 }
1096 break;
1097 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 (void) BIO_reset(biobuf);
1099 GENERAL_NAME_print(biobuf, name);
1100 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1101 if (len < 0) {
1102 _setSSLError(NULL, 0, __FILE__, __LINE__);
1103 goto fail;
1104 }
1105 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001106 if (vptr == NULL) {
1107 PyErr_Format(PyExc_ValueError,
1108 "Invalid value %.200s",
1109 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001110 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001111 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001112 t = PyTuple_New(2);
1113 if (t == NULL)
1114 goto fail;
1115 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1116 if (v == NULL) {
1117 Py_DECREF(t);
1118 goto fail;
1119 }
1120 PyTuple_SET_ITEM(t, 0, v);
1121 v = PyUnicode_FromStringAndSize((vptr + 1),
1122 (len - (vptr - buf + 1)));
1123 if (v == NULL) {
1124 Py_DECREF(t);
1125 goto fail;
1126 }
1127 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001128 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001129 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001130
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001131 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001133 if (PyList_Append(peer_alt_names, t) < 0) {
1134 Py_DECREF(t);
1135 goto fail;
1136 }
1137 Py_DECREF(t);
1138 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001139 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 }
1141 BIO_free(biobuf);
1142 if (peer_alt_names != Py_None) {
1143 v = PyList_AsTuple(peer_alt_names);
1144 Py_DECREF(peer_alt_names);
1145 return v;
1146 } else {
1147 return peer_alt_names;
1148 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001149
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001150
1151 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001152 if (biobuf != NULL)
1153 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001155 if (peer_alt_names != Py_None) {
1156 Py_XDECREF(peer_alt_names);
1157 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001159 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001160}
1161
1162static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001163_get_aia_uri(X509 *certificate, int nid) {
1164 PyObject *lst = NULL, *ostr = NULL;
1165 int i, result;
1166 AUTHORITY_INFO_ACCESS *info;
1167
1168 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001169 if (info == NULL)
1170 return Py_None;
1171 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1172 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001173 return Py_None;
1174 }
1175
1176 if ((lst = PyList_New(0)) == NULL) {
1177 goto fail;
1178 }
1179
1180 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1181 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1182 ASN1_IA5STRING *uri;
1183
1184 if ((OBJ_obj2nid(ad->method) != nid) ||
1185 (ad->location->type != GEN_URI)) {
1186 continue;
1187 }
1188 uri = ad->location->d.uniformResourceIdentifier;
1189 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1190 uri->length);
1191 if (ostr == NULL) {
1192 goto fail;
1193 }
1194 result = PyList_Append(lst, ostr);
1195 Py_DECREF(ostr);
1196 if (result < 0) {
1197 goto fail;
1198 }
1199 }
1200 AUTHORITY_INFO_ACCESS_free(info);
1201
1202 /* convert to tuple or None */
1203 if (PyList_Size(lst) == 0) {
1204 Py_DECREF(lst);
1205 return Py_None;
1206 } else {
1207 PyObject *tup;
1208 tup = PyList_AsTuple(lst);
1209 Py_DECREF(lst);
1210 return tup;
1211 }
1212
1213 fail:
1214 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001215 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001216 return NULL;
1217}
1218
1219static PyObject *
1220_get_crl_dp(X509 *certificate) {
1221 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001222 int i, j;
1223 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001224
Christian Heimes598894f2016-09-05 23:19:05 +02001225 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001226
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001227 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001228 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001229
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001230 lst = PyList_New(0);
1231 if (lst == NULL)
1232 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001233
1234 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1235 DIST_POINT *dp;
1236 STACK_OF(GENERAL_NAME) *gns;
1237
1238 dp = sk_DIST_POINT_value(dps, i);
1239 gns = dp->distpoint->name.fullname;
1240
1241 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1242 GENERAL_NAME *gn;
1243 ASN1_IA5STRING *uri;
1244 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001245 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001246
1247 gn = sk_GENERAL_NAME_value(gns, j);
1248 if (gn->type != GEN_URI) {
1249 continue;
1250 }
1251 uri = gn->d.uniformResourceIdentifier;
1252 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1253 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001254 if (ouri == NULL)
1255 goto done;
1256
1257 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001258 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001259 if (err < 0)
1260 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001261 }
1262 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001263
1264 /* Convert to tuple. */
1265 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1266
1267 done:
1268 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001269 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001270 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001271}
1272
1273static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001274_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 PyObject *retval = NULL;
1277 BIO *biobuf = NULL;
1278 PyObject *peer;
1279 PyObject *peer_alt_names = NULL;
1280 PyObject *issuer;
1281 PyObject *version;
1282 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001283 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001284 ASN1_INTEGER *serialNumber;
1285 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001286 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001287 ASN1_TIME *notBefore, *notAfter;
1288 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001289
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001290 retval = PyDict_New();
1291 if (retval == NULL)
1292 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001293
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 peer = _create_tuple_for_X509_NAME(
1295 X509_get_subject_name(certificate));
1296 if (peer == NULL)
1297 goto fail0;
1298 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1299 Py_DECREF(peer);
1300 goto fail0;
1301 }
1302 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001303
Antoine Pitroufb046912010-11-09 20:21:19 +00001304 issuer = _create_tuple_for_X509_NAME(
1305 X509_get_issuer_name(certificate));
1306 if (issuer == NULL)
1307 goto fail0;
1308 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001309 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001310 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001311 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001312 Py_DECREF(issuer);
1313
1314 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001315 if (version == NULL)
1316 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001317 if (PyDict_SetItemString(retval, "version", version) < 0) {
1318 Py_DECREF(version);
1319 goto fail0;
1320 }
1321 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001322
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001323 /* get a memory buffer */
1324 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001325
Antoine Pitroufb046912010-11-09 20:21:19 +00001326 (void) BIO_reset(biobuf);
1327 serialNumber = X509_get_serialNumber(certificate);
1328 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1329 i2a_ASN1_INTEGER(biobuf, serialNumber);
1330 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1331 if (len < 0) {
1332 _setSSLError(NULL, 0, __FILE__, __LINE__);
1333 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001334 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001335 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1336 if (sn_obj == NULL)
1337 goto fail1;
1338 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1339 Py_DECREF(sn_obj);
1340 goto fail1;
1341 }
1342 Py_DECREF(sn_obj);
1343
1344 (void) BIO_reset(biobuf);
1345 notBefore = X509_get_notBefore(certificate);
1346 ASN1_TIME_print(biobuf, notBefore);
1347 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1348 if (len < 0) {
1349 _setSSLError(NULL, 0, __FILE__, __LINE__);
1350 goto fail1;
1351 }
1352 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1353 if (pnotBefore == NULL)
1354 goto fail1;
1355 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1356 Py_DECREF(pnotBefore);
1357 goto fail1;
1358 }
1359 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001361 (void) BIO_reset(biobuf);
1362 notAfter = X509_get_notAfter(certificate);
1363 ASN1_TIME_print(biobuf, notAfter);
1364 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1365 if (len < 0) {
1366 _setSSLError(NULL, 0, __FILE__, __LINE__);
1367 goto fail1;
1368 }
1369 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1370 if (pnotAfter == NULL)
1371 goto fail1;
1372 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1373 Py_DECREF(pnotAfter);
1374 goto fail1;
1375 }
1376 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001380 peer_alt_names = _get_peer_alt_names(certificate);
1381 if (peer_alt_names == NULL)
1382 goto fail1;
1383 else if (peer_alt_names != Py_None) {
1384 if (PyDict_SetItemString(retval, "subjectAltName",
1385 peer_alt_names) < 0) {
1386 Py_DECREF(peer_alt_names);
1387 goto fail1;
1388 }
1389 Py_DECREF(peer_alt_names);
1390 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001391
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001392 /* Authority Information Access: OCSP URIs */
1393 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1394 if (obj == NULL) {
1395 goto fail1;
1396 } else if (obj != Py_None) {
1397 result = PyDict_SetItemString(retval, "OCSP", obj);
1398 Py_DECREF(obj);
1399 if (result < 0) {
1400 goto fail1;
1401 }
1402 }
1403
1404 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1405 if (obj == NULL) {
1406 goto fail1;
1407 } else if (obj != Py_None) {
1408 result = PyDict_SetItemString(retval, "caIssuers", obj);
1409 Py_DECREF(obj);
1410 if (result < 0) {
1411 goto fail1;
1412 }
1413 }
1414
1415 /* CDP (CRL distribution points) */
1416 obj = _get_crl_dp(certificate);
1417 if (obj == NULL) {
1418 goto fail1;
1419 } else if (obj != Py_None) {
1420 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1421 Py_DECREF(obj);
1422 if (result < 0) {
1423 goto fail1;
1424 }
1425 }
1426
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001427 BIO_free(biobuf);
1428 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001429
1430 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001431 if (biobuf != NULL)
1432 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001433 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001434 Py_XDECREF(retval);
1435 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001436}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001437
Christian Heimes9a5395a2013-06-17 15:44:12 +02001438static PyObject *
1439_certificate_to_der(X509 *certificate)
1440{
1441 unsigned char *bytes_buf = NULL;
1442 int len;
1443 PyObject *retval;
1444
1445 bytes_buf = NULL;
1446 len = i2d_X509(certificate, &bytes_buf);
1447 if (len < 0) {
1448 _setSSLError(NULL, 0, __FILE__, __LINE__);
1449 return NULL;
1450 }
1451 /* this is actually an immutable bytes sequence */
1452 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1453 OPENSSL_free(bytes_buf);
1454 return retval;
1455}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001456
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001457/*[clinic input]
1458_ssl._test_decode_cert
1459 path: object(converter="PyUnicode_FSConverter")
1460 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001461
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001462[clinic start generated code]*/
1463
1464static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001465_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1466/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001467{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001468 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 X509 *x=NULL;
1470 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001471
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001472 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1473 PyErr_SetString(PySSLErrorObject,
1474 "Can't malloc memory to read file");
1475 goto fail0;
1476 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001477
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001478 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001479 PyErr_SetString(PySSLErrorObject,
1480 "Can't open file");
1481 goto fail0;
1482 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001484 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1485 if (x == NULL) {
1486 PyErr_SetString(PySSLErrorObject,
1487 "Error decoding PEM-encoded file");
1488 goto fail0;
1489 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001490
Antoine Pitroufb046912010-11-09 20:21:19 +00001491 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001492 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001493
1494 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001495 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001496 if (cert != NULL) BIO_free(cert);
1497 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001498}
1499
1500
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001501/*[clinic input]
1502_ssl._SSLSocket.peer_certificate
1503 der as binary_mode: bool = False
1504 /
1505
1506Returns the certificate for the peer.
1507
1508If no certificate was provided, returns None. If a certificate was
1509provided, but not validated, returns an empty dictionary. Otherwise
1510returns a dict containing information about the peer certificate.
1511
1512If the optional argument is True, returns a DER-encoded copy of the
1513peer certificate, or None if no certificate was provided. This will
1514return the certificate even if it wasn't validated.
1515[clinic start generated code]*/
1516
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001517static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001518_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1519/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001520{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001522 X509 *peer_cert;
1523 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001524
Christian Heimes66dc33b2017-05-23 16:02:02 -07001525 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001526 PyErr_SetString(PyExc_ValueError,
1527 "handshake not done yet");
1528 return NULL;
1529 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001530 peer_cert = SSL_get_peer_certificate(self->ssl);
1531 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001532 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001533
Antoine Pitrou721738f2012-08-15 23:20:39 +02001534 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001536 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001537 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001538 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001540 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001542 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001543 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001544 X509_free(peer_cert);
1545 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001546}
1547
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001548static PyObject *
1549cipher_to_tuple(const SSL_CIPHER *cipher)
1550{
1551 const char *cipher_name, *cipher_protocol;
1552 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 if (retval == NULL)
1554 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001556 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001558 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 PyTuple_SET_ITEM(retval, 0, Py_None);
1560 } else {
1561 v = PyUnicode_FromString(cipher_name);
1562 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001563 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 PyTuple_SET_ITEM(retval, 0, v);
1565 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001566
1567 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001569 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 PyTuple_SET_ITEM(retval, 1, Py_None);
1571 } else {
1572 v = PyUnicode_FromString(cipher_protocol);
1573 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001574 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 PyTuple_SET_ITEM(retval, 1, v);
1576 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001577
1578 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001579 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001580 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001581 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001582
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001583 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001584
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001585 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001586 Py_DECREF(retval);
1587 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001588}
1589
Christian Heimes25bfcd52016-09-06 00:04:45 +02001590#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1591static PyObject *
1592cipher_to_dict(const SSL_CIPHER *cipher)
1593{
1594 const char *cipher_name, *cipher_protocol;
1595
1596 unsigned long cipher_id;
1597 int alg_bits, strength_bits, len;
1598 char buf[512] = {0};
1599#if OPENSSL_VERSION_1_1
1600 int aead, nid;
1601 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1602#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001603
1604 /* can be NULL */
1605 cipher_name = SSL_CIPHER_get_name(cipher);
1606 cipher_protocol = SSL_CIPHER_get_version(cipher);
1607 cipher_id = SSL_CIPHER_get_id(cipher);
1608 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001609 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1610 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001611 if (len > 1 && buf[len-1] == '\n')
1612 buf[len-1] = '\0';
1613 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1614
1615#if OPENSSL_VERSION_1_1
1616 aead = SSL_CIPHER_is_aead(cipher);
1617 nid = SSL_CIPHER_get_cipher_nid(cipher);
1618 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1619 nid = SSL_CIPHER_get_digest_nid(cipher);
1620 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1621 nid = SSL_CIPHER_get_kx_nid(cipher);
1622 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1623 nid = SSL_CIPHER_get_auth_nid(cipher);
1624 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1625#endif
1626
Victor Stinner410b9882016-09-12 12:00:23 +02001627 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001628 "{sksssssssisi"
1629#if OPENSSL_VERSION_1_1
1630 "sOssssssss"
1631#endif
1632 "}",
1633 "id", cipher_id,
1634 "name", cipher_name,
1635 "protocol", cipher_protocol,
1636 "description", buf,
1637 "strength_bits", strength_bits,
1638 "alg_bits", alg_bits
1639#if OPENSSL_VERSION_1_1
1640 ,"aead", aead ? Py_True : Py_False,
1641 "symmetric", skcipher,
1642 "digest", digest,
1643 "kea", kx,
1644 "auth", auth
1645#endif
1646 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001647}
1648#endif
1649
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001650/*[clinic input]
1651_ssl._SSLSocket.shared_ciphers
1652[clinic start generated code]*/
1653
1654static PyObject *
1655_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1656/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001657{
1658 STACK_OF(SSL_CIPHER) *ciphers;
1659 int i;
1660 PyObject *res;
1661
Christian Heimes598894f2016-09-05 23:19:05 +02001662 ciphers = SSL_get_ciphers(self->ssl);
1663 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001664 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001665 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1666 if (!res)
1667 return NULL;
1668 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1669 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1670 if (!tup) {
1671 Py_DECREF(res);
1672 return NULL;
1673 }
1674 PyList_SET_ITEM(res, i, tup);
1675 }
1676 return res;
1677}
1678
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001679/*[clinic input]
1680_ssl._SSLSocket.cipher
1681[clinic start generated code]*/
1682
1683static PyObject *
1684_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1685/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001686{
1687 const SSL_CIPHER *current;
1688
1689 if (self->ssl == NULL)
1690 Py_RETURN_NONE;
1691 current = SSL_get_current_cipher(self->ssl);
1692 if (current == NULL)
1693 Py_RETURN_NONE;
1694 return cipher_to_tuple(current);
1695}
1696
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001697/*[clinic input]
1698_ssl._SSLSocket.version
1699[clinic start generated code]*/
1700
1701static PyObject *
1702_ssl__SSLSocket_version_impl(PySSLSocket *self)
1703/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001704{
1705 const char *version;
1706
1707 if (self->ssl == NULL)
1708 Py_RETURN_NONE;
1709 version = SSL_get_version(self->ssl);
1710 if (!strcmp(version, "unknown"))
1711 Py_RETURN_NONE;
1712 return PyUnicode_FromString(version);
1713}
1714
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001715#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001716/*[clinic input]
1717_ssl._SSLSocket.selected_npn_protocol
1718[clinic start generated code]*/
1719
1720static PyObject *
1721_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1722/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1723{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001724 const unsigned char *out;
1725 unsigned int outlen;
1726
Victor Stinner4569cd52013-06-23 14:58:43 +02001727 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001728 &out, &outlen);
1729
1730 if (out == NULL)
1731 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001732 return PyUnicode_FromStringAndSize((char *)out, outlen);
1733}
1734#endif
1735
1736#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001737/*[clinic input]
1738_ssl._SSLSocket.selected_alpn_protocol
1739[clinic start generated code]*/
1740
1741static PyObject *
1742_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1743/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1744{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001745 const unsigned char *out;
1746 unsigned int outlen;
1747
1748 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1749
1750 if (out == NULL)
1751 Py_RETURN_NONE;
1752 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001753}
1754#endif
1755
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001756/*[clinic input]
1757_ssl._SSLSocket.compression
1758[clinic start generated code]*/
1759
1760static PyObject *
1761_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1762/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1763{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001764#ifdef OPENSSL_NO_COMP
1765 Py_RETURN_NONE;
1766#else
1767 const COMP_METHOD *comp_method;
1768 const char *short_name;
1769
1770 if (self->ssl == NULL)
1771 Py_RETURN_NONE;
1772 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001773 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001774 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001775 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001776 if (short_name == NULL)
1777 Py_RETURN_NONE;
1778 return PyUnicode_DecodeFSDefault(short_name);
1779#endif
1780}
1781
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001782static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1783 Py_INCREF(self->ctx);
1784 return self->ctx;
1785}
1786
1787static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1788 void *closure) {
1789
1790 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001791#if !HAVE_SNI
1792 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1793 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001794 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001795#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001796 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001797 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001798 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001799#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001800 } else {
1801 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1802 return -1;
1803 }
1804
1805 return 0;
1806}
1807
1808PyDoc_STRVAR(PySSL_set_context_doc,
1809"_setter_context(ctx)\n\
1810\
1811This changes the context associated with the SSLSocket. This is typically\n\
1812used from within a callback function set by the set_servername_callback\n\
1813on the SSLContext to change the certificate information associated with the\n\
1814SSLSocket before the cryptographic exchange handshake messages\n");
1815
1816
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001817static PyObject *
1818PySSL_get_server_side(PySSLSocket *self, void *c)
1819{
1820 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1821}
1822
1823PyDoc_STRVAR(PySSL_get_server_side_doc,
1824"Whether this is a server-side socket.");
1825
1826static PyObject *
1827PySSL_get_server_hostname(PySSLSocket *self, void *c)
1828{
1829 if (self->server_hostname == NULL)
1830 Py_RETURN_NONE;
1831 Py_INCREF(self->server_hostname);
1832 return self->server_hostname;
1833}
1834
1835PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1836"The currently set server hostname (for SNI).");
1837
1838static PyObject *
1839PySSL_get_owner(PySSLSocket *self, void *c)
1840{
1841 PyObject *owner;
1842
1843 if (self->owner == NULL)
1844 Py_RETURN_NONE;
1845
1846 owner = PyWeakref_GetObject(self->owner);
1847 Py_INCREF(owner);
1848 return owner;
1849}
1850
1851static int
1852PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1853{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001854 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001855 if (self->owner == NULL)
1856 return -1;
1857 return 0;
1858}
1859
1860PyDoc_STRVAR(PySSL_get_owner_doc,
1861"The Python-level owner of this object.\
1862Passed as \"self\" in servername callback.");
1863
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001864
Antoine Pitrou152efa22010-05-16 18:19:27 +00001865static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001866{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001867 if (self->ssl)
1868 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001869 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001870 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001871 Py_XDECREF(self->server_hostname);
1872 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001873 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001874}
1875
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001876/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001877 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001878 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001879 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001880
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001881static int
Victor Stinner14690702015-04-06 22:46:13 +02001882PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001883{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001884 int rc;
1885#ifdef HAVE_POLL
1886 struct pollfd pollfd;
1887 _PyTime_t ms;
1888#else
1889 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 fd_set fds;
1891 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001892#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001895 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001896 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001897 else if (timeout < 0) {
1898 if (s->sock_timeout > 0)
1899 return SOCKET_HAS_TIMED_OUT;
1900 else
1901 return SOCKET_IS_BLOCKING;
1902 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001903
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001904 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001905 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001906 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001907
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001908 /* Prefer poll, if available, since you can poll() any fd
1909 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001910#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001911 pollfd.fd = s->sock_fd;
1912 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001913
Victor Stinner14690702015-04-06 22:46:13 +02001914 /* timeout is in seconds, poll() uses milliseconds */
1915 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001916 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001917
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001918 PySSL_BEGIN_ALLOW_THREADS
1919 rc = poll(&pollfd, 1, (int)ms);
1920 PySSL_END_ALLOW_THREADS
1921#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001923 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001925
Victor Stinner14690702015-04-06 22:46:13 +02001926 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001927
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001928 FD_ZERO(&fds);
1929 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001930
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001931 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001932 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001933 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001934 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001935 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001936 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001937 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001938 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001939#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001940
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001941 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1942 (when we are able to write or when there's something to read) */
1943 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001944}
1945
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001946/*[clinic input]
1947_ssl._SSLSocket.write
1948 b: Py_buffer
1949 /
1950
1951Writes the bytes-like object b into the SSL object.
1952
1953Returns the number of bytes written.
1954[clinic start generated code]*/
1955
1956static PyObject *
1957_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1958/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001959{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 int len;
1961 int sockstate;
1962 int err;
1963 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001964 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001965 _PyTime_t timeout, deadline = 0;
1966 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001967
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001968 if (sock != NULL) {
1969 if (((PyObject*)sock) == Py_None) {
1970 _setSSLError("Underlying socket connection gone",
1971 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1972 return NULL;
1973 }
1974 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975 }
1976
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001977 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001978 PyErr_Format(PyExc_OverflowError,
1979 "string longer than %d bytes", INT_MAX);
1980 goto error;
1981 }
1982
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001983 if (sock != NULL) {
1984 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001985 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001986 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1987 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1988 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989
Victor Stinner14690702015-04-06 22:46:13 +02001990 timeout = GET_SOCKET_TIMEOUT(sock);
1991 has_timeout = (timeout > 0);
1992 if (has_timeout)
1993 deadline = _PyTime_GetMonotonicClock() + timeout;
1994
1995 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001997 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001998 "The write operation timed out");
1999 goto error;
2000 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2001 PyErr_SetString(PySSLErrorObject,
2002 "Underlying socket has been closed.");
2003 goto error;
2004 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2005 PyErr_SetString(PySSLErrorObject,
2006 "Underlying socket too large for select().");
2007 goto error;
2008 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002009
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002011 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002012 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002013 err = SSL_get_error(self->ssl, len);
2014 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002015
2016 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002017 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002018
Victor Stinner14690702015-04-06 22:46:13 +02002019 if (has_timeout)
2020 timeout = deadline - _PyTime_GetMonotonicClock();
2021
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002022 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002023 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002024 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002025 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 } else {
2027 sockstate = SOCKET_OPERATION_OK;
2028 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002029
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002030 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002031 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002032 "The write operation timed out");
2033 goto error;
2034 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2035 PyErr_SetString(PySSLErrorObject,
2036 "Underlying socket has been closed.");
2037 goto error;
2038 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2039 break;
2040 }
2041 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002042
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002043 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002044 if (len > 0)
2045 return PyLong_FromLong(len);
2046 else
2047 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002048
2049error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002050 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002051 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002052}
2053
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002054/*[clinic input]
2055_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002056
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002057Returns the number of already decrypted bytes available for read, pending on the connection.
2058[clinic start generated code]*/
2059
2060static PyObject *
2061_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2062/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002063{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002064 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002066 PySSL_BEGIN_ALLOW_THREADS
2067 count = SSL_pending(self->ssl);
2068 PySSL_END_ALLOW_THREADS
2069 if (count < 0)
2070 return PySSL_SetError(self, count, __FILE__, __LINE__);
2071 else
2072 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002073}
2074
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002075/*[clinic input]
2076_ssl._SSLSocket.read
2077 size as len: int
2078 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002079 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002080 ]
2081 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002082
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002083Read up to size bytes from the SSL socket.
2084[clinic start generated code]*/
2085
2086static PyObject *
2087_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2088 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002089/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002090{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002092 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002093 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002094 int sockstate;
2095 int err;
2096 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002097 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002098 _PyTime_t timeout, deadline = 0;
2099 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002100
Martin Panter5503d472016-03-27 05:35:19 +00002101 if (!group_right_1 && len < 0) {
2102 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2103 return NULL;
2104 }
2105
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002106 if (sock != NULL) {
2107 if (((PyObject*)sock) == Py_None) {
2108 _setSSLError("Underlying socket connection gone",
2109 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2110 return NULL;
2111 }
2112 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002113 }
2114
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002115 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002116 dest = PyBytes_FromStringAndSize(NULL, len);
2117 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002118 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002119 if (len == 0) {
2120 Py_XDECREF(sock);
2121 return dest;
2122 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002123 mem = PyBytes_AS_STRING(dest);
2124 }
2125 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002126 mem = buffer->buf;
2127 if (len <= 0 || len > buffer->len) {
2128 len = (int) buffer->len;
2129 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002130 PyErr_SetString(PyExc_OverflowError,
2131 "maximum length can't fit in a C 'int'");
2132 goto error;
2133 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002134 if (len == 0) {
2135 count = 0;
2136 goto done;
2137 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002138 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 }
2140
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002141 if (sock != NULL) {
2142 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002143 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002144 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2145 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2146 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002147
Victor Stinner14690702015-04-06 22:46:13 +02002148 timeout = GET_SOCKET_TIMEOUT(sock);
2149 has_timeout = (timeout > 0);
2150 if (has_timeout)
2151 deadline = _PyTime_GetMonotonicClock() + timeout;
2152
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002154 PySSL_BEGIN_ALLOW_THREADS
2155 count = SSL_read(self->ssl, mem, len);
2156 err = SSL_get_error(self->ssl, count);
2157 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 if (PyErr_CheckSignals())
2160 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002161
Victor Stinner14690702015-04-06 22:46:13 +02002162 if (has_timeout)
2163 timeout = deadline - _PyTime_GetMonotonicClock();
2164
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002166 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002167 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002168 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002169 } else if (err == SSL_ERROR_ZERO_RETURN &&
2170 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002171 {
2172 count = 0;
2173 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002174 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002175 else
2176 sockstate = SOCKET_OPERATION_OK;
2177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002178 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002179 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002180 "The read operation timed out");
2181 goto error;
2182 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2183 break;
2184 }
2185 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002186
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002187 if (count <= 0) {
2188 PySSL_SetError(self, count, __FILE__, __LINE__);
2189 goto error;
2190 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002191
2192done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002193 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002194 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002195 _PyBytes_Resize(&dest, count);
2196 return dest;
2197 }
2198 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002199 return PyLong_FromLong(count);
2200 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002201
2202error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002203 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002204 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002205 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002207}
2208
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002209/*[clinic input]
2210_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002211
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002212Does the SSL shutdown handshake with the remote end.
2213
2214Returns the underlying socket object.
2215[clinic start generated code]*/
2216
2217static PyObject *
2218_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2219/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002220{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002221 int err, ssl_err, sockstate, nonblocking;
2222 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002223 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002224 _PyTime_t timeout, deadline = 0;
2225 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002226
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002227 if (sock != NULL) {
2228 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002229 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002230 _setSSLError("Underlying socket connection gone",
2231 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2232 return NULL;
2233 }
2234 Py_INCREF(sock);
2235
2236 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002237 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002238 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2239 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002241
Victor Stinner14690702015-04-06 22:46:13 +02002242 timeout = GET_SOCKET_TIMEOUT(sock);
2243 has_timeout = (timeout > 0);
2244 if (has_timeout)
2245 deadline = _PyTime_GetMonotonicClock() + timeout;
2246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 while (1) {
2248 PySSL_BEGIN_ALLOW_THREADS
2249 /* Disable read-ahead so that unwrap can work correctly.
2250 * Otherwise OpenSSL might read in too much data,
2251 * eating clear text data that happens to be
2252 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002253 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002254 * function is used and the shutdown_seen_zero != 0
2255 * condition is met.
2256 */
2257 if (self->shutdown_seen_zero)
2258 SSL_set_read_ahead(self->ssl, 0);
2259 err = SSL_shutdown(self->ssl);
2260 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002261
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2263 if (err > 0)
2264 break;
2265 if (err == 0) {
2266 /* Don't loop endlessly; instead preserve legacy
2267 behaviour of trying SSL_shutdown() only twice.
2268 This looks necessary for OpenSSL < 0.9.8m */
2269 if (++zeros > 1)
2270 break;
2271 /* Shutdown was sent, now try receiving */
2272 self->shutdown_seen_zero = 1;
2273 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002274 }
2275
Victor Stinner14690702015-04-06 22:46:13 +02002276 if (has_timeout)
2277 timeout = deadline - _PyTime_GetMonotonicClock();
2278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 /* Possibly retry shutdown until timeout or failure */
2280 ssl_err = SSL_get_error(self->ssl, err);
2281 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002282 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002283 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002284 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 else
2286 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002287
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002288 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2289 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002290 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002291 "The read operation timed out");
2292 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002293 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002295 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 }
2297 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2298 PyErr_SetString(PySSLErrorObject,
2299 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002300 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002301 }
2302 else if (sockstate != SOCKET_OPERATION_OK)
2303 /* Retain the SSL error code */
2304 break;
2305 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002306
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002307 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002308 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002309 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002310 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002311 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002312 /* It's already INCREF'ed */
2313 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002314 else
2315 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002316
2317error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002318 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002319 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002320}
2321
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002322/*[clinic input]
2323_ssl._SSLSocket.tls_unique_cb
2324
2325Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2326
2327If the TLS handshake is not yet complete, None is returned.
2328[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002329
Antoine Pitroud6494802011-07-21 01:11:30 +02002330static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002331_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2332/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002333{
2334 PyObject *retval = NULL;
2335 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002336 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002337
2338 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2339 /* if session is resumed XOR we are the client */
2340 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2341 }
2342 else {
2343 /* if a new session XOR we are the server */
2344 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2345 }
2346
2347 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002348 if (len == 0)
2349 Py_RETURN_NONE;
2350
2351 retval = PyBytes_FromStringAndSize(buf, len);
2352
2353 return retval;
2354}
2355
Christian Heimes99a65702016-09-10 23:44:53 +02002356#ifdef OPENSSL_VERSION_1_1
2357
2358static SSL_SESSION*
2359_ssl_session_dup(SSL_SESSION *session) {
2360 SSL_SESSION *newsession = NULL;
2361 int slen;
2362 unsigned char *senc = NULL, *p;
2363 const unsigned char *const_p;
2364
2365 if (session == NULL) {
2366 PyErr_SetString(PyExc_ValueError, "Invalid session");
2367 goto error;
2368 }
2369
2370 /* get length */
2371 slen = i2d_SSL_SESSION(session, NULL);
2372 if (slen == 0 || slen > 0xFF00) {
2373 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2374 goto error;
2375 }
2376 if ((senc = PyMem_Malloc(slen)) == NULL) {
2377 PyErr_NoMemory();
2378 goto error;
2379 }
2380 p = senc;
2381 if (!i2d_SSL_SESSION(session, &p)) {
2382 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2383 goto error;
2384 }
2385 const_p = senc;
2386 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2387 if (session == NULL) {
2388 goto error;
2389 }
2390 PyMem_Free(senc);
2391 return newsession;
2392 error:
2393 if (senc != NULL) {
2394 PyMem_Free(senc);
2395 }
2396 return NULL;
2397}
2398#endif
2399
2400static PyObject *
2401PySSL_get_session(PySSLSocket *self, void *closure) {
2402 /* get_session can return sessions from a server-side connection,
2403 * it does not check for handshake done or client socket. */
2404 PySSLSession *pysess;
2405 SSL_SESSION *session;
2406
2407#ifdef OPENSSL_VERSION_1_1
2408 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2409 * https://github.com/openssl/openssl/issues/1550 */
2410 session = SSL_get0_session(self->ssl); /* borrowed reference */
2411 if (session == NULL) {
2412 Py_RETURN_NONE;
2413 }
2414 if ((session = _ssl_session_dup(session)) == NULL) {
2415 return NULL;
2416 }
2417#else
2418 session = SSL_get1_session(self->ssl);
2419 if (session == NULL) {
2420 Py_RETURN_NONE;
2421 }
2422#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002423 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002424 if (pysess == NULL) {
2425 SSL_SESSION_free(session);
2426 return NULL;
2427 }
2428
2429 assert(self->ctx);
2430 pysess->ctx = self->ctx;
2431 Py_INCREF(pysess->ctx);
2432 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002433 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002434 return (PyObject *)pysess;
2435}
2436
2437static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2438 void *closure)
2439 {
2440 PySSLSession *pysess;
2441#ifdef OPENSSL_VERSION_1_1
2442 SSL_SESSION *session;
2443#endif
2444 int result;
2445
2446 if (!PySSLSession_Check(value)) {
2447 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2448 return -1;
2449 }
2450 pysess = (PySSLSession *)value;
2451
2452 if (self->ctx->ctx != pysess->ctx->ctx) {
2453 PyErr_SetString(PyExc_ValueError,
2454 "Session refers to a different SSLContext.");
2455 return -1;
2456 }
2457 if (self->socket_type != PY_SSL_CLIENT) {
2458 PyErr_SetString(PyExc_ValueError,
2459 "Cannot set session for server-side SSLSocket.");
2460 return -1;
2461 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002462 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002463 PyErr_SetString(PyExc_ValueError,
2464 "Cannot set session after handshake.");
2465 return -1;
2466 }
2467#ifdef OPENSSL_VERSION_1_1
2468 /* duplicate session */
2469 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2470 return -1;
2471 }
2472 result = SSL_set_session(self->ssl, session);
2473 /* free duplicate, SSL_set_session() bumps ref count */
2474 SSL_SESSION_free(session);
2475#else
2476 result = SSL_set_session(self->ssl, pysess->session);
2477#endif
2478 if (result == 0) {
2479 _setSSLError(NULL, 0, __FILE__, __LINE__);
2480 return -1;
2481 }
2482 return 0;
2483}
2484
2485PyDoc_STRVAR(PySSL_set_session_doc,
2486"_setter_session(session)\n\
2487\
2488Get / set SSLSession.");
2489
2490static PyObject *
2491PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2492 if (SSL_session_reused(self->ssl)) {
2493 Py_RETURN_TRUE;
2494 } else {
2495 Py_RETURN_FALSE;
2496 }
2497}
2498
2499PyDoc_STRVAR(PySSL_get_session_reused_doc,
2500"Was the client session reused during handshake?");
2501
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002502static PyGetSetDef ssl_getsetlist[] = {
2503 {"context", (getter) PySSL_get_context,
2504 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002505 {"server_side", (getter) PySSL_get_server_side, NULL,
2506 PySSL_get_server_side_doc},
2507 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2508 PySSL_get_server_hostname_doc},
2509 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2510 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002511 {"session", (getter) PySSL_get_session,
2512 (setter) PySSL_set_session, PySSL_set_session_doc},
2513 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2514 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002515 {NULL}, /* sentinel */
2516};
2517
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002518static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002519 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2520 _SSL__SSLSOCKET_WRITE_METHODDEF
2521 _SSL__SSLSOCKET_READ_METHODDEF
2522 _SSL__SSLSOCKET_PENDING_METHODDEF
2523 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2524 _SSL__SSLSOCKET_CIPHER_METHODDEF
2525 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2526 _SSL__SSLSOCKET_VERSION_METHODDEF
2527 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2528 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2529 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2530 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2531 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002532 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002533};
2534
Antoine Pitrou152efa22010-05-16 18:19:27 +00002535static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002536 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002537 "_ssl._SSLSocket", /*tp_name*/
2538 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002539 0, /*tp_itemsize*/
2540 /* methods */
2541 (destructor)PySSL_dealloc, /*tp_dealloc*/
2542 0, /*tp_print*/
2543 0, /*tp_getattr*/
2544 0, /*tp_setattr*/
2545 0, /*tp_reserved*/
2546 0, /*tp_repr*/
2547 0, /*tp_as_number*/
2548 0, /*tp_as_sequence*/
2549 0, /*tp_as_mapping*/
2550 0, /*tp_hash*/
2551 0, /*tp_call*/
2552 0, /*tp_str*/
2553 0, /*tp_getattro*/
2554 0, /*tp_setattro*/
2555 0, /*tp_as_buffer*/
2556 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2557 0, /*tp_doc*/
2558 0, /*tp_traverse*/
2559 0, /*tp_clear*/
2560 0, /*tp_richcompare*/
2561 0, /*tp_weaklistoffset*/
2562 0, /*tp_iter*/
2563 0, /*tp_iternext*/
2564 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002565 0, /*tp_members*/
2566 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002567};
2568
Antoine Pitrou152efa22010-05-16 18:19:27 +00002569
2570/*
2571 * _SSLContext objects
2572 */
2573
Christian Heimes5fe668c2016-09-12 00:01:11 +02002574static int
2575_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2576{
2577 int mode;
2578 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2579
2580 switch(n) {
2581 case PY_SSL_CERT_NONE:
2582 mode = SSL_VERIFY_NONE;
2583 break;
2584 case PY_SSL_CERT_OPTIONAL:
2585 mode = SSL_VERIFY_PEER;
2586 break;
2587 case PY_SSL_CERT_REQUIRED:
2588 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2589 break;
2590 default:
2591 PyErr_SetString(PyExc_ValueError,
2592 "invalid value for verify_mode");
2593 return -1;
2594 }
2595 /* keep current verify cb */
2596 verify_cb = SSL_CTX_get_verify_callback(ctx);
2597 SSL_CTX_set_verify(ctx, mode, verify_cb);
2598 return 0;
2599}
2600
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002601/*[clinic input]
2602@classmethod
2603_ssl._SSLContext.__new__
2604 protocol as proto_version: int
2605 /
2606[clinic start generated code]*/
2607
Antoine Pitrou152efa22010-05-16 18:19:27 +00002608static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002609_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2610/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002611{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002612 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002613 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002614 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002615 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002616#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002617 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002618#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002619
Antoine Pitrou152efa22010-05-16 18:19:27 +00002620 PySSL_BEGIN_ALLOW_THREADS
2621 if (proto_version == PY_SSL_VERSION_TLS1)
2622 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002623#if HAVE_TLSv1_2
2624 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2625 ctx = SSL_CTX_new(TLSv1_1_method());
2626 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2627 ctx = SSL_CTX_new(TLSv1_2_method());
2628#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002629#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002630 else if (proto_version == PY_SSL_VERSION_SSL3)
2631 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002632#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002633#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002634 else if (proto_version == PY_SSL_VERSION_SSL2)
2635 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002636#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002637 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002638 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002639 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2640 ctx = SSL_CTX_new(TLS_client_method());
2641 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2642 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002643 else
2644 proto_version = -1;
2645 PySSL_END_ALLOW_THREADS
2646
2647 if (proto_version == -1) {
2648 PyErr_SetString(PyExc_ValueError,
2649 "invalid protocol version");
2650 return NULL;
2651 }
2652 if (ctx == NULL) {
2653 PyErr_SetString(PySSLErrorObject,
2654 "failed to allocate SSL context");
2655 return NULL;
2656 }
2657
2658 assert(type != NULL && type->tp_alloc != NULL);
2659 self = (PySSLContext *) type->tp_alloc(type, 0);
2660 if (self == NULL) {
2661 SSL_CTX_free(ctx);
2662 return NULL;
2663 }
2664 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002665#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002666 self->npn_protocols = NULL;
2667#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002668#ifdef HAVE_ALPN
2669 self->alpn_protocols = NULL;
2670#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002671#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002672 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002673#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002674 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002675 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2676 self->check_hostname = 1;
2677 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2678 Py_DECREF(self);
2679 return NULL;
2680 }
2681 } else {
2682 self->check_hostname = 0;
2683 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2684 Py_DECREF(self);
2685 return NULL;
2686 }
2687 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002688 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002689 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2690 if (proto_version != PY_SSL_VERSION_SSL2)
2691 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002692 if (proto_version != PY_SSL_VERSION_SSL3)
2693 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002694 /* Minimal security flags for server and client side context.
2695 * Client sockets ignore server-side parameters. */
2696#ifdef SSL_OP_NO_COMPRESSION
2697 options |= SSL_OP_NO_COMPRESSION;
2698#endif
2699#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2700 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2701#endif
2702#ifdef SSL_OP_SINGLE_DH_USE
2703 options |= SSL_OP_SINGLE_DH_USE;
2704#endif
2705#ifdef SSL_OP_SINGLE_ECDH_USE
2706 options |= SSL_OP_SINGLE_ECDH_USE;
2707#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002708 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002709
Christian Heimes358cfd42016-09-10 22:43:48 +02002710 /* A bare minimum cipher list without completly broken cipher suites.
2711 * It's far from perfect but gives users a better head start. */
2712 if (proto_version != PY_SSL_VERSION_SSL2) {
2713 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2714 } else {
2715 /* SSLv2 needs MD5 */
2716 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2717 }
2718 if (result == 0) {
2719 Py_DECREF(self);
2720 ERR_clear_error();
2721 PyErr_SetString(PySSLErrorObject,
2722 "No cipher can be selected.");
2723 return NULL;
2724 }
2725
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002726#if defined(SSL_MODE_RELEASE_BUFFERS)
2727 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2728 usage for no cost at all. However, don't do this for OpenSSL versions
2729 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2730 2014-0198. I can't find exactly which beta fixed this CVE, so be
2731 conservative and assume it wasn't fixed until release. We do this check
2732 at runtime to avoid problems from the dynamic linker.
2733 See #25672 for more on this. */
2734 libver = SSLeay();
2735 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2736 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2737 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2738 }
2739#endif
2740
2741
Donald Stufft8ae264c2017-03-02 11:45:29 -05002742#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002743 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2744 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002745 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2746 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002747#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002748 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2749#else
2750 {
2751 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2752 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2753 EC_KEY_free(key);
2754 }
2755#endif
2756#endif
2757
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002758#define SID_CTX "Python"
2759 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2760 sizeof(SID_CTX));
2761#undef SID_CTX
2762
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002763#ifdef X509_V_FLAG_TRUSTED_FIRST
2764 {
2765 /* Improve trust chain building when cross-signed intermediate
2766 certificates are present. See https://bugs.python.org/issue23476. */
2767 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2768 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2769 }
2770#endif
2771
Antoine Pitrou152efa22010-05-16 18:19:27 +00002772 return (PyObject *)self;
2773}
2774
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002775static int
2776context_traverse(PySSLContext *self, visitproc visit, void *arg)
2777{
2778#ifndef OPENSSL_NO_TLSEXT
2779 Py_VISIT(self->set_hostname);
2780#endif
2781 return 0;
2782}
2783
2784static int
2785context_clear(PySSLContext *self)
2786{
2787#ifndef OPENSSL_NO_TLSEXT
2788 Py_CLEAR(self->set_hostname);
2789#endif
2790 return 0;
2791}
2792
Antoine Pitrou152efa22010-05-16 18:19:27 +00002793static void
2794context_dealloc(PySSLContext *self)
2795{
INADA Naokia6296d32017-08-24 14:55:17 +09002796 /* bpo-31095: UnTrack is needed before calling any callbacks */
2797 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002798 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002799 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002800#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002801 PyMem_FREE(self->npn_protocols);
2802#endif
2803#ifdef HAVE_ALPN
2804 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002805#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002806 Py_TYPE(self)->tp_free(self);
2807}
2808
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002809/*[clinic input]
2810_ssl._SSLContext.set_ciphers
2811 cipherlist: str
2812 /
2813[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002814
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002815static PyObject *
2816_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2817/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2818{
2819 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002820 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002821 /* Clearing the error queue is necessary on some OpenSSL versions,
2822 otherwise the error will be reported again when another SSL call
2823 is done. */
2824 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002825 PyErr_SetString(PySSLErrorObject,
2826 "No cipher can be selected.");
2827 return NULL;
2828 }
2829 Py_RETURN_NONE;
2830}
2831
Christian Heimes25bfcd52016-09-06 00:04:45 +02002832#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2833/*[clinic input]
2834_ssl._SSLContext.get_ciphers
2835[clinic start generated code]*/
2836
2837static PyObject *
2838_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2839/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2840{
2841 SSL *ssl = NULL;
2842 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002843 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002844 int i=0;
2845 PyObject *result = NULL, *dct;
2846
2847 ssl = SSL_new(self->ctx);
2848 if (ssl == NULL) {
2849 _setSSLError(NULL, 0, __FILE__, __LINE__);
2850 goto exit;
2851 }
2852 sk = SSL_get_ciphers(ssl);
2853
2854 result = PyList_New(sk_SSL_CIPHER_num(sk));
2855 if (result == NULL) {
2856 goto exit;
2857 }
2858
2859 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2860 cipher = sk_SSL_CIPHER_value(sk, i);
2861 dct = cipher_to_dict(cipher);
2862 if (dct == NULL) {
2863 Py_CLEAR(result);
2864 goto exit;
2865 }
2866 PyList_SET_ITEM(result, i, dct);
2867 }
2868
2869 exit:
2870 if (ssl != NULL)
2871 SSL_free(ssl);
2872 return result;
2873
2874}
2875#endif
2876
2877
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002878#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002879static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002880do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2881 const unsigned char *server_protocols, unsigned int server_protocols_len,
2882 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002883{
Benjamin Peterson88615022015-01-23 17:30:26 -05002884 int ret;
2885 if (client_protocols == NULL) {
2886 client_protocols = (unsigned char *)"";
2887 client_protocols_len = 0;
2888 }
2889 if (server_protocols == NULL) {
2890 server_protocols = (unsigned char *)"";
2891 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002892 }
2893
Benjamin Peterson88615022015-01-23 17:30:26 -05002894 ret = SSL_select_next_proto(out, outlen,
2895 server_protocols, server_protocols_len,
2896 client_protocols, client_protocols_len);
2897 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2898 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002899
2900 return SSL_TLSEXT_ERR_OK;
2901}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002902#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002903
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002904#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002905/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2906static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002907_advertiseNPN_cb(SSL *s,
2908 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002909 void *args)
2910{
2911 PySSLContext *ssl_ctx = (PySSLContext *) args;
2912
2913 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002914 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002915 *len = 0;
2916 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002917 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002918 *len = ssl_ctx->npn_protocols_len;
2919 }
2920
2921 return SSL_TLSEXT_ERR_OK;
2922}
2923/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2924static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002925_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002926 unsigned char **out, unsigned char *outlen,
2927 const unsigned char *server, unsigned int server_len,
2928 void *args)
2929{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002930 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002931 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002932 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002933}
2934#endif
2935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002936/*[clinic input]
2937_ssl._SSLContext._set_npn_protocols
2938 protos: Py_buffer
2939 /
2940[clinic start generated code]*/
2941
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002942static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002943_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2944 Py_buffer *protos)
2945/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002946{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002947#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002948 PyMem_Free(self->npn_protocols);
2949 self->npn_protocols = PyMem_Malloc(protos->len);
2950 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002951 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002952 memcpy(self->npn_protocols, protos->buf, protos->len);
2953 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002954
2955 /* set both server and client callbacks, because the context can
2956 * be used to create both types of sockets */
2957 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2958 _advertiseNPN_cb,
2959 self);
2960 SSL_CTX_set_next_proto_select_cb(self->ctx,
2961 _selectNPN_cb,
2962 self);
2963
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002964 Py_RETURN_NONE;
2965#else
2966 PyErr_SetString(PyExc_NotImplementedError,
2967 "The NPN extension requires OpenSSL 1.0.1 or later.");
2968 return NULL;
2969#endif
2970}
2971
Benjamin Petersoncca27322015-01-23 16:35:37 -05002972#ifdef HAVE_ALPN
2973static int
2974_selectALPN_cb(SSL *s,
2975 const unsigned char **out, unsigned char *outlen,
2976 const unsigned char *client_protocols, unsigned int client_protocols_len,
2977 void *args)
2978{
2979 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002980 return do_protocol_selection(1, (unsigned char **)out, outlen,
2981 ctx->alpn_protocols, ctx->alpn_protocols_len,
2982 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002983}
2984#endif
2985
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002986/*[clinic input]
2987_ssl._SSLContext._set_alpn_protocols
2988 protos: Py_buffer
2989 /
2990[clinic start generated code]*/
2991
Benjamin Petersoncca27322015-01-23 16:35:37 -05002992static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002993_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2994 Py_buffer *protos)
2995/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002996{
2997#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03002998 if (protos->len > UINT_MAX) {
2999 PyErr_Format(PyExc_OverflowError,
3000 "protocols longer than %d bytes", UINT_MAX);
3001 return NULL;
3002 }
3003
Benjamin Petersoncca27322015-01-23 16:35:37 -05003004 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003005 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003006 if (!self->alpn_protocols)
3007 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003008 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003009 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003010
3011 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3012 return PyErr_NoMemory();
3013 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3014
Benjamin Petersoncca27322015-01-23 16:35:37 -05003015 Py_RETURN_NONE;
3016#else
3017 PyErr_SetString(PyExc_NotImplementedError,
3018 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3019 return NULL;
3020#endif
3021}
3022
Antoine Pitrou152efa22010-05-16 18:19:27 +00003023static PyObject *
3024get_verify_mode(PySSLContext *self, void *c)
3025{
3026 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3027 case SSL_VERIFY_NONE:
3028 return PyLong_FromLong(PY_SSL_CERT_NONE);
3029 case SSL_VERIFY_PEER:
3030 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3031 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3032 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3033 }
3034 PyErr_SetString(PySSLErrorObject,
3035 "invalid return value from SSL_CTX_get_verify_mode");
3036 return NULL;
3037}
3038
3039static int
3040set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3041{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003042 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003043 if (!PyArg_Parse(arg, "i", &n))
3044 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003045 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003046 PyErr_SetString(PyExc_ValueError,
3047 "Cannot set verify_mode to CERT_NONE when "
3048 "check_hostname is enabled.");
3049 return -1;
3050 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003051 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003052}
3053
3054static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003055get_verify_flags(PySSLContext *self, void *c)
3056{
3057 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003058 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003059 unsigned long flags;
3060
3061 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003062 param = X509_STORE_get0_param(store);
3063 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003064 return PyLong_FromUnsignedLong(flags);
3065}
3066
3067static int
3068set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3069{
3070 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003071 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003072 unsigned long new_flags, flags, set, clear;
3073
3074 if (!PyArg_Parse(arg, "k", &new_flags))
3075 return -1;
3076 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003077 param = X509_STORE_get0_param(store);
3078 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003079 clear = flags & ~new_flags;
3080 set = ~flags & new_flags;
3081 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003082 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003083 _setSSLError(NULL, 0, __FILE__, __LINE__);
3084 return -1;
3085 }
3086 }
3087 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003088 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003089 _setSSLError(NULL, 0, __FILE__, __LINE__);
3090 return -1;
3091 }
3092 }
3093 return 0;
3094}
3095
3096static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003097get_options(PySSLContext *self, void *c)
3098{
3099 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3100}
3101
3102static int
3103set_options(PySSLContext *self, PyObject *arg, void *c)
3104{
3105 long new_opts, opts, set, clear;
3106 if (!PyArg_Parse(arg, "l", &new_opts))
3107 return -1;
3108 opts = SSL_CTX_get_options(self->ctx);
3109 clear = opts & ~new_opts;
3110 set = ~opts & new_opts;
3111 if (clear) {
3112#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3113 SSL_CTX_clear_options(self->ctx, clear);
3114#else
3115 PyErr_SetString(PyExc_ValueError,
3116 "can't clear options before OpenSSL 0.9.8m");
3117 return -1;
3118#endif
3119 }
3120 if (set)
3121 SSL_CTX_set_options(self->ctx, set);
3122 return 0;
3123}
3124
Christian Heimes1aa9a752013-12-02 02:41:19 +01003125static PyObject *
3126get_check_hostname(PySSLContext *self, void *c)
3127{
3128 return PyBool_FromLong(self->check_hostname);
3129}
3130
3131static int
3132set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3133{
3134 int check_hostname;
3135 if (!PyArg_Parse(arg, "p", &check_hostname))
3136 return -1;
3137 if (check_hostname &&
3138 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3139 PyErr_SetString(PyExc_ValueError,
3140 "check_hostname needs a SSL context with either "
3141 "CERT_OPTIONAL or CERT_REQUIRED");
3142 return -1;
3143 }
3144 self->check_hostname = check_hostname;
3145 return 0;
3146}
3147
3148
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003149typedef struct {
3150 PyThreadState *thread_state;
3151 PyObject *callable;
3152 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003153 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003154 int error;
3155} _PySSLPasswordInfo;
3156
3157static int
3158_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3159 const char *bad_type_error)
3160{
3161 /* Set the password and size fields of a _PySSLPasswordInfo struct
3162 from a unicode, bytes, or byte array object.
3163 The password field will be dynamically allocated and must be freed
3164 by the caller */
3165 PyObject *password_bytes = NULL;
3166 const char *data = NULL;
3167 Py_ssize_t size;
3168
3169 if (PyUnicode_Check(password)) {
3170 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3171 if (!password_bytes) {
3172 goto error;
3173 }
3174 data = PyBytes_AS_STRING(password_bytes);
3175 size = PyBytes_GET_SIZE(password_bytes);
3176 } else if (PyBytes_Check(password)) {
3177 data = PyBytes_AS_STRING(password);
3178 size = PyBytes_GET_SIZE(password);
3179 } else if (PyByteArray_Check(password)) {
3180 data = PyByteArray_AS_STRING(password);
3181 size = PyByteArray_GET_SIZE(password);
3182 } else {
3183 PyErr_SetString(PyExc_TypeError, bad_type_error);
3184 goto error;
3185 }
3186
Victor Stinner9ee02032013-06-23 15:08:23 +02003187 if (size > (Py_ssize_t)INT_MAX) {
3188 PyErr_Format(PyExc_ValueError,
3189 "password cannot be longer than %d bytes", INT_MAX);
3190 goto error;
3191 }
3192
Victor Stinner11ebff22013-07-07 17:07:52 +02003193 PyMem_Free(pw_info->password);
3194 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003195 if (!pw_info->password) {
3196 PyErr_SetString(PyExc_MemoryError,
3197 "unable to allocate password buffer");
3198 goto error;
3199 }
3200 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003201 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003202
3203 Py_XDECREF(password_bytes);
3204 return 1;
3205
3206error:
3207 Py_XDECREF(password_bytes);
3208 return 0;
3209}
3210
3211static int
3212_password_callback(char *buf, int size, int rwflag, void *userdata)
3213{
3214 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3215 PyObject *fn_ret = NULL;
3216
3217 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3218
3219 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003220 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003221 if (!fn_ret) {
3222 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3223 core python API, so we could use it to add a frame here */
3224 goto error;
3225 }
3226
3227 if (!_pwinfo_set(pw_info, fn_ret,
3228 "password callback must return a string")) {
3229 goto error;
3230 }
3231 Py_CLEAR(fn_ret);
3232 }
3233
3234 if (pw_info->size > size) {
3235 PyErr_Format(PyExc_ValueError,
3236 "password cannot be longer than %d bytes", size);
3237 goto error;
3238 }
3239
3240 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3241 memcpy(buf, pw_info->password, pw_info->size);
3242 return pw_info->size;
3243
3244error:
3245 Py_XDECREF(fn_ret);
3246 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3247 pw_info->error = 1;
3248 return -1;
3249}
3250
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003251/*[clinic input]
3252_ssl._SSLContext.load_cert_chain
3253 certfile: object
3254 keyfile: object = NULL
3255 password: object = NULL
3256
3257[clinic start generated code]*/
3258
Antoine Pitroub5218772010-05-21 09:56:06 +00003259static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003260_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3261 PyObject *keyfile, PyObject *password)
3262/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003263{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003264 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003265 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3266 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003267 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003268 int r;
3269
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003270 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003271 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003272 if (keyfile == Py_None)
3273 keyfile = NULL;
3274 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3275 PyErr_SetString(PyExc_TypeError,
3276 "certfile should be a valid filesystem path");
3277 return NULL;
3278 }
3279 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3280 PyErr_SetString(PyExc_TypeError,
3281 "keyfile should be a valid filesystem path");
3282 goto error;
3283 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003284 if (password && password != Py_None) {
3285 if (PyCallable_Check(password)) {
3286 pw_info.callable = password;
3287 } else if (!_pwinfo_set(&pw_info, password,
3288 "password should be a string or callable")) {
3289 goto error;
3290 }
3291 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3292 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3293 }
3294 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003295 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3296 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003297 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003298 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003299 if (pw_info.error) {
3300 ERR_clear_error();
3301 /* the password callback has already set the error information */
3302 }
3303 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003304 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003305 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003306 }
3307 else {
3308 _setSSLError(NULL, 0, __FILE__, __LINE__);
3309 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003310 goto error;
3311 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003312 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003313 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003314 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3315 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003316 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3317 Py_CLEAR(keyfile_bytes);
3318 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003319 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003320 if (pw_info.error) {
3321 ERR_clear_error();
3322 /* the password callback has already set the error information */
3323 }
3324 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003325 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003326 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003327 }
3328 else {
3329 _setSSLError(NULL, 0, __FILE__, __LINE__);
3330 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003331 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003332 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003333 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003334 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003335 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003336 if (r != 1) {
3337 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003338 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003339 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003340 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3341 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003342 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003343 Py_RETURN_NONE;
3344
3345error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003346 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3347 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003348 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003349 Py_XDECREF(keyfile_bytes);
3350 Py_XDECREF(certfile_bytes);
3351 return NULL;
3352}
3353
Christian Heimesefff7062013-11-21 03:35:02 +01003354/* internal helper function, returns -1 on error
3355 */
3356static int
3357_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3358 int filetype)
3359{
3360 BIO *biobuf = NULL;
3361 X509_STORE *store;
3362 int retval = 0, err, loaded = 0;
3363
3364 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3365
3366 if (len <= 0) {
3367 PyErr_SetString(PyExc_ValueError,
3368 "Empty certificate data");
3369 return -1;
3370 } else if (len > INT_MAX) {
3371 PyErr_SetString(PyExc_OverflowError,
3372 "Certificate data is too long.");
3373 return -1;
3374 }
3375
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003376 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003377 if (biobuf == NULL) {
3378 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3379 return -1;
3380 }
3381
3382 store = SSL_CTX_get_cert_store(self->ctx);
3383 assert(store != NULL);
3384
3385 while (1) {
3386 X509 *cert = NULL;
3387 int r;
3388
3389 if (filetype == SSL_FILETYPE_ASN1) {
3390 cert = d2i_X509_bio(biobuf, NULL);
3391 } else {
3392 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003393 SSL_CTX_get_default_passwd_cb(self->ctx),
3394 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3395 );
Christian Heimesefff7062013-11-21 03:35:02 +01003396 }
3397 if (cert == NULL) {
3398 break;
3399 }
3400 r = X509_STORE_add_cert(store, cert);
3401 X509_free(cert);
3402 if (!r) {
3403 err = ERR_peek_last_error();
3404 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3405 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3406 /* cert already in hash table, not an error */
3407 ERR_clear_error();
3408 } else {
3409 break;
3410 }
3411 }
3412 loaded++;
3413 }
3414
3415 err = ERR_peek_last_error();
3416 if ((filetype == SSL_FILETYPE_ASN1) &&
3417 (loaded > 0) &&
3418 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3419 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3420 /* EOF ASN1 file, not an error */
3421 ERR_clear_error();
3422 retval = 0;
3423 } else if ((filetype == SSL_FILETYPE_PEM) &&
3424 (loaded > 0) &&
3425 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3426 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3427 /* EOF PEM file, not an error */
3428 ERR_clear_error();
3429 retval = 0;
3430 } else {
3431 _setSSLError(NULL, 0, __FILE__, __LINE__);
3432 retval = -1;
3433 }
3434
3435 BIO_free(biobuf);
3436 return retval;
3437}
3438
3439
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003440/*[clinic input]
3441_ssl._SSLContext.load_verify_locations
3442 cafile: object = NULL
3443 capath: object = NULL
3444 cadata: object = NULL
3445
3446[clinic start generated code]*/
3447
Antoine Pitrou152efa22010-05-16 18:19:27 +00003448static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003449_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3450 PyObject *cafile,
3451 PyObject *capath,
3452 PyObject *cadata)
3453/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003454{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003455 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3456 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003457 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003458
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003459 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003460 if (cafile == Py_None)
3461 cafile = NULL;
3462 if (capath == Py_None)
3463 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003464 if (cadata == Py_None)
3465 cadata = NULL;
3466
3467 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003468 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003469 "cafile, capath and cadata cannot be all omitted");
3470 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003471 }
3472 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3473 PyErr_SetString(PyExc_TypeError,
3474 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003475 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003476 }
3477 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003478 PyErr_SetString(PyExc_TypeError,
3479 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003480 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003481 }
Christian Heimesefff7062013-11-21 03:35:02 +01003482
3483 /* validata cadata type and load cadata */
3484 if (cadata) {
3485 Py_buffer buf;
3486 PyObject *cadata_ascii = NULL;
3487
3488 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3489 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3490 PyBuffer_Release(&buf);
3491 PyErr_SetString(PyExc_TypeError,
3492 "cadata should be a contiguous buffer with "
3493 "a single dimension");
3494 goto error;
3495 }
3496 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3497 PyBuffer_Release(&buf);
3498 if (r == -1) {
3499 goto error;
3500 }
3501 } else {
3502 PyErr_Clear();
3503 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3504 if (cadata_ascii == NULL) {
3505 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003506 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003507 "bytes-like object");
3508 goto error;
3509 }
3510 r = _add_ca_certs(self,
3511 PyBytes_AS_STRING(cadata_ascii),
3512 PyBytes_GET_SIZE(cadata_ascii),
3513 SSL_FILETYPE_PEM);
3514 Py_DECREF(cadata_ascii);
3515 if (r == -1) {
3516 goto error;
3517 }
3518 }
3519 }
3520
3521 /* load cafile or capath */
3522 if (cafile || capath) {
3523 if (cafile)
3524 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3525 if (capath)
3526 capath_buf = PyBytes_AS_STRING(capath_bytes);
3527 PySSL_BEGIN_ALLOW_THREADS
3528 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3529 PySSL_END_ALLOW_THREADS
3530 if (r != 1) {
3531 ok = 0;
3532 if (errno != 0) {
3533 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003534 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003535 }
3536 else {
3537 _setSSLError(NULL, 0, __FILE__, __LINE__);
3538 }
3539 goto error;
3540 }
3541 }
3542 goto end;
3543
3544 error:
3545 ok = 0;
3546 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003547 Py_XDECREF(cafile_bytes);
3548 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003549 if (ok) {
3550 Py_RETURN_NONE;
3551 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003552 return NULL;
3553 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003554}
3555
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003556/*[clinic input]
3557_ssl._SSLContext.load_dh_params
3558 path as filepath: object
3559 /
3560
3561[clinic start generated code]*/
3562
Antoine Pitrou152efa22010-05-16 18:19:27 +00003563static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003564_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3565/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003566{
3567 FILE *f;
3568 DH *dh;
3569
Victor Stinnerdaf45552013-08-28 00:53:59 +02003570 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003571 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003572 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003573
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003574 errno = 0;
3575 PySSL_BEGIN_ALLOW_THREADS
3576 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003577 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003578 PySSL_END_ALLOW_THREADS
3579 if (dh == NULL) {
3580 if (errno != 0) {
3581 ERR_clear_error();
3582 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3583 }
3584 else {
3585 _setSSLError(NULL, 0, __FILE__, __LINE__);
3586 }
3587 return NULL;
3588 }
3589 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3590 _setSSLError(NULL, 0, __FILE__, __LINE__);
3591 DH_free(dh);
3592 Py_RETURN_NONE;
3593}
3594
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003595/*[clinic input]
3596_ssl._SSLContext._wrap_socket
3597 sock: object(subclass_of="PySocketModule.Sock_Type")
3598 server_side: int
3599 server_hostname as hostname_obj: object = None
3600
3601[clinic start generated code]*/
3602
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003603static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003604_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3605 int server_side, PyObject *hostname_obj)
3606/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003607{
Antoine Pitroud5323212010-10-22 18:19:07 +00003608 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003609 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003610
Antoine Pitroud5323212010-10-22 18:19:07 +00003611 /* server_hostname is either None (or absent), or to be encoded
3612 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003613 if (hostname_obj != Py_None) {
3614 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003615 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003616 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003617
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003618 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3619 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003620 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003621 if (hostname != NULL)
3622 PyMem_Free(hostname);
3623 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003624}
3625
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003626/*[clinic input]
3627_ssl._SSLContext._wrap_bio
3628 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3629 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3630 server_side: int
3631 server_hostname as hostname_obj: object = None
3632
3633[clinic start generated code]*/
3634
Antoine Pitroub0182c82010-10-12 20:09:02 +00003635static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003636_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3637 PySSLMemoryBIO *outgoing, int server_side,
3638 PyObject *hostname_obj)
3639/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003640{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003641 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003642 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003643
3644 /* server_hostname is either None (or absent), or to be encoded
3645 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003646 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003647 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3648 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003649 }
3650
3651 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3652 incoming, outgoing);
3653
3654 PyMem_Free(hostname);
3655 return res;
3656}
3657
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003658/*[clinic input]
3659_ssl._SSLContext.session_stats
3660[clinic start generated code]*/
3661
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003662static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003663_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3664/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003665{
3666 int r;
3667 PyObject *value, *stats = PyDict_New();
3668 if (!stats)
3669 return NULL;
3670
3671#define ADD_STATS(SSL_NAME, KEY_NAME) \
3672 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3673 if (value == NULL) \
3674 goto error; \
3675 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3676 Py_DECREF(value); \
3677 if (r < 0) \
3678 goto error;
3679
3680 ADD_STATS(number, "number");
3681 ADD_STATS(connect, "connect");
3682 ADD_STATS(connect_good, "connect_good");
3683 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3684 ADD_STATS(accept, "accept");
3685 ADD_STATS(accept_good, "accept_good");
3686 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3687 ADD_STATS(accept, "accept");
3688 ADD_STATS(hits, "hits");
3689 ADD_STATS(misses, "misses");
3690 ADD_STATS(timeouts, "timeouts");
3691 ADD_STATS(cache_full, "cache_full");
3692
3693#undef ADD_STATS
3694
3695 return stats;
3696
3697error:
3698 Py_DECREF(stats);
3699 return NULL;
3700}
3701
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003702/*[clinic input]
3703_ssl._SSLContext.set_default_verify_paths
3704[clinic start generated code]*/
3705
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003706static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003707_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3708/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003709{
3710 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3711 _setSSLError(NULL, 0, __FILE__, __LINE__);
3712 return NULL;
3713 }
3714 Py_RETURN_NONE;
3715}
3716
Antoine Pitrou501da612011-12-21 09:27:41 +01003717#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003718/*[clinic input]
3719_ssl._SSLContext.set_ecdh_curve
3720 name: object
3721 /
3722
3723[clinic start generated code]*/
3724
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003725static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003726_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3727/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003728{
3729 PyObject *name_bytes;
3730 int nid;
3731 EC_KEY *key;
3732
3733 if (!PyUnicode_FSConverter(name, &name_bytes))
3734 return NULL;
3735 assert(PyBytes_Check(name_bytes));
3736 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3737 Py_DECREF(name_bytes);
3738 if (nid == 0) {
3739 PyErr_Format(PyExc_ValueError,
3740 "unknown elliptic curve name %R", name);
3741 return NULL;
3742 }
3743 key = EC_KEY_new_by_curve_name(nid);
3744 if (key == NULL) {
3745 _setSSLError(NULL, 0, __FILE__, __LINE__);
3746 return NULL;
3747 }
3748 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3749 EC_KEY_free(key);
3750 Py_RETURN_NONE;
3751}
Antoine Pitrou501da612011-12-21 09:27:41 +01003752#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003753
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003754#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003755static int
3756_servername_callback(SSL *s, int *al, void *args)
3757{
3758 int ret;
3759 PySSLContext *ssl_ctx = (PySSLContext *) args;
3760 PySSLSocket *ssl;
3761 PyObject *servername_o;
3762 PyObject *servername_idna;
3763 PyObject *result;
3764 /* The high-level ssl.SSLSocket object */
3765 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003766 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003767#ifdef WITH_THREAD
3768 PyGILState_STATE gstate = PyGILState_Ensure();
3769#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003770
3771 if (ssl_ctx->set_hostname == NULL) {
3772 /* remove race condition in this the call back while if removing the
3773 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003774#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003775 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003776#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003777 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003778 }
3779
3780 ssl = SSL_get_app_data(s);
3781 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003782
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003783 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003784 * SSL connection and that has a .context attribute that can be changed to
3785 * identify the requested hostname. Since the official API is the Python
3786 * level API we want to pass the callback a Python level object rather than
3787 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3788 * SSLObject) that will be passed. Otherwise if there's a socket then that
3789 * will be passed. If both do not exist only then the C-level object is
3790 * passed. */
3791 if (ssl->owner)
3792 ssl_socket = PyWeakref_GetObject(ssl->owner);
3793 else if (ssl->Socket)
3794 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3795 else
3796 ssl_socket = (PyObject *) ssl;
3797
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003798 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003799 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003800 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003801
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003802 if (servername == NULL) {
3803 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3804 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003805 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003806 else {
3807 servername_o = PyBytes_FromString(servername);
3808 if (servername_o == NULL) {
3809 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3810 goto error;
3811 }
3812 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3813 if (servername_idna == NULL) {
3814 PyErr_WriteUnraisable(servername_o);
3815 Py_DECREF(servername_o);
3816 goto error;
3817 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003818 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003819 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3820 servername_idna, ssl_ctx, NULL);
3821 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003822 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003823 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003824
3825 if (result == NULL) {
3826 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3827 *al = SSL_AD_HANDSHAKE_FAILURE;
3828 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3829 }
3830 else {
3831 if (result != Py_None) {
3832 *al = (int) PyLong_AsLong(result);
3833 if (PyErr_Occurred()) {
3834 PyErr_WriteUnraisable(result);
3835 *al = SSL_AD_INTERNAL_ERROR;
3836 }
3837 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3838 }
3839 else {
3840 ret = SSL_TLSEXT_ERR_OK;
3841 }
3842 Py_DECREF(result);
3843 }
3844
Stefan Krah20d60802013-01-17 17:07:17 +01003845#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003846 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003847#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003848 return ret;
3849
3850error:
3851 Py_DECREF(ssl_socket);
3852 *al = SSL_AD_INTERNAL_ERROR;
3853 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003854#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003855 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003856#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003857 return ret;
3858}
Antoine Pitroua5963382013-03-30 16:39:00 +01003859#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003860
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003861/*[clinic input]
3862_ssl._SSLContext.set_servername_callback
3863 method as cb: object
3864 /
3865
3866Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3867
3868If the argument is None then the callback is disabled. The method is called
3869with the SSLSocket, the server name as a string, and the SSLContext object.
3870See RFC 6066 for details of the SNI extension.
3871[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003872
3873static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003874_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3875/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003876{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003877#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003878 Py_CLEAR(self->set_hostname);
3879 if (cb == Py_None) {
3880 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3881 }
3882 else {
3883 if (!PyCallable_Check(cb)) {
3884 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3885 PyErr_SetString(PyExc_TypeError,
3886 "not a callable object");
3887 return NULL;
3888 }
3889 Py_INCREF(cb);
3890 self->set_hostname = cb;
3891 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3892 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3893 }
3894 Py_RETURN_NONE;
3895#else
3896 PyErr_SetString(PyExc_NotImplementedError,
3897 "The TLS extension servername callback, "
3898 "SSL_CTX_set_tlsext_servername_callback, "
3899 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003900 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003901#endif
3902}
3903
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003904/*[clinic input]
3905_ssl._SSLContext.cert_store_stats
3906
3907Returns quantities of loaded X.509 certificates.
3908
3909X.509 certificates with a CA extension and certificate revocation lists
3910inside the context's cert store.
3911
3912NOTE: Certificates in a capath directory aren't loaded unless they have
3913been used at least once.
3914[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003915
3916static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003917_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3918/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003919{
3920 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003921 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003922 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003923 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003924
3925 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003926 objs = X509_STORE_get0_objects(store);
3927 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3928 obj = sk_X509_OBJECT_value(objs, i);
3929 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003930 case X509_LU_X509:
3931 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003932 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003933 ca++;
3934 }
3935 break;
3936 case X509_LU_CRL:
3937 crl++;
3938 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003939 default:
3940 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3941 * As far as I can tell they are internal states and never
3942 * stored in a cert store */
3943 break;
3944 }
3945 }
3946 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3947 "x509_ca", ca);
3948}
3949
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003950/*[clinic input]
3951_ssl._SSLContext.get_ca_certs
3952 binary_form: bool = False
3953
3954Returns a list of dicts with information of loaded CA certs.
3955
3956If the optional argument is True, returns a DER-encoded copy of the CA
3957certificate.
3958
3959NOTE: Certificates in a capath directory aren't loaded unless they have
3960been used at least once.
3961[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003962
3963static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003964_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3965/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003966{
3967 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003968 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003969 PyObject *ci = NULL, *rlist = NULL;
3970 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003971
3972 if ((rlist = PyList_New(0)) == NULL) {
3973 return NULL;
3974 }
3975
3976 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003977 objs = X509_STORE_get0_objects(store);
3978 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003979 X509_OBJECT *obj;
3980 X509 *cert;
3981
Christian Heimes598894f2016-09-05 23:19:05 +02003982 obj = sk_X509_OBJECT_value(objs, i);
3983 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003984 /* not a x509 cert */
3985 continue;
3986 }
3987 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003988 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003989 if (!X509_check_ca(cert)) {
3990 continue;
3991 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003992 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003993 ci = _certificate_to_der(cert);
3994 } else {
3995 ci = _decode_certificate(cert);
3996 }
3997 if (ci == NULL) {
3998 goto error;
3999 }
4000 if (PyList_Append(rlist, ci) == -1) {
4001 goto error;
4002 }
4003 Py_CLEAR(ci);
4004 }
4005 return rlist;
4006
4007 error:
4008 Py_XDECREF(ci);
4009 Py_XDECREF(rlist);
4010 return NULL;
4011}
4012
4013
Antoine Pitrou152efa22010-05-16 18:19:27 +00004014static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004015 {"check_hostname", (getter) get_check_hostname,
4016 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004017 {"options", (getter) get_options,
4018 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004019 {"verify_flags", (getter) get_verify_flags,
4020 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004021 {"verify_mode", (getter) get_verify_mode,
4022 (setter) set_verify_mode, NULL},
4023 {NULL}, /* sentinel */
4024};
4025
4026static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004027 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4028 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4029 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4030 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4031 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4032 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4033 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4034 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4035 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4036 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4037 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4038 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4039 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4040 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004041 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004042 {NULL, NULL} /* sentinel */
4043};
4044
4045static PyTypeObject PySSLContext_Type = {
4046 PyVarObject_HEAD_INIT(NULL, 0)
4047 "_ssl._SSLContext", /*tp_name*/
4048 sizeof(PySSLContext), /*tp_basicsize*/
4049 0, /*tp_itemsize*/
4050 (destructor)context_dealloc, /*tp_dealloc*/
4051 0, /*tp_print*/
4052 0, /*tp_getattr*/
4053 0, /*tp_setattr*/
4054 0, /*tp_reserved*/
4055 0, /*tp_repr*/
4056 0, /*tp_as_number*/
4057 0, /*tp_as_sequence*/
4058 0, /*tp_as_mapping*/
4059 0, /*tp_hash*/
4060 0, /*tp_call*/
4061 0, /*tp_str*/
4062 0, /*tp_getattro*/
4063 0, /*tp_setattro*/
4064 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004065 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004066 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004067 (traverseproc) context_traverse, /*tp_traverse*/
4068 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004069 0, /*tp_richcompare*/
4070 0, /*tp_weaklistoffset*/
4071 0, /*tp_iter*/
4072 0, /*tp_iternext*/
4073 context_methods, /*tp_methods*/
4074 0, /*tp_members*/
4075 context_getsetlist, /*tp_getset*/
4076 0, /*tp_base*/
4077 0, /*tp_dict*/
4078 0, /*tp_descr_get*/
4079 0, /*tp_descr_set*/
4080 0, /*tp_dictoffset*/
4081 0, /*tp_init*/
4082 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004083 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004084};
4085
4086
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004087/*
4088 * MemoryBIO objects
4089 */
4090
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004091/*[clinic input]
4092@classmethod
4093_ssl.MemoryBIO.__new__
4094
4095[clinic start generated code]*/
4096
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004097static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004098_ssl_MemoryBIO_impl(PyTypeObject *type)
4099/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004100{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004101 BIO *bio;
4102 PySSLMemoryBIO *self;
4103
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004104 bio = BIO_new(BIO_s_mem());
4105 if (bio == NULL) {
4106 PyErr_SetString(PySSLErrorObject,
4107 "failed to allocate BIO");
4108 return NULL;
4109 }
4110 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4111 * just that no data is currently available. The SSL routines should retry
4112 * the read, which we can achieve by calling BIO_set_retry_read(). */
4113 BIO_set_retry_read(bio);
4114 BIO_set_mem_eof_return(bio, -1);
4115
4116 assert(type != NULL && type->tp_alloc != NULL);
4117 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4118 if (self == NULL) {
4119 BIO_free(bio);
4120 return NULL;
4121 }
4122 self->bio = bio;
4123 self->eof_written = 0;
4124
4125 return (PyObject *) self;
4126}
4127
4128static void
4129memory_bio_dealloc(PySSLMemoryBIO *self)
4130{
4131 BIO_free(self->bio);
4132 Py_TYPE(self)->tp_free(self);
4133}
4134
4135static PyObject *
4136memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4137{
Segev Finer5cff6372017-07-27 01:19:17 +03004138 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004139}
4140
4141PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4142"The number of bytes pending in the memory BIO.");
4143
4144static PyObject *
4145memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4146{
4147 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4148 && self->eof_written);
4149}
4150
4151PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4152"Whether the memory BIO is at EOF.");
4153
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004154/*[clinic input]
4155_ssl.MemoryBIO.read
4156 size as len: int = -1
4157 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004158
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004159Read up to size bytes from the memory BIO.
4160
4161If size is not specified, read the entire buffer.
4162If the return value is an empty bytes instance, this means either
4163EOF or that no data is available. Use the "eof" property to
4164distinguish between the two.
4165[clinic start generated code]*/
4166
4167static PyObject *
4168_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4169/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4170{
4171 int avail, nbytes;
4172 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004173
Segev Finer5cff6372017-07-27 01:19:17 +03004174 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004175 if ((len < 0) || (len > avail))
4176 len = avail;
4177
4178 result = PyBytes_FromStringAndSize(NULL, len);
4179 if ((result == NULL) || (len == 0))
4180 return result;
4181
4182 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4183 /* There should never be any short reads but check anyway. */
4184 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4185 Py_DECREF(result);
4186 return NULL;
4187 }
4188
4189 return result;
4190}
4191
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004192/*[clinic input]
4193_ssl.MemoryBIO.write
4194 b: Py_buffer
4195 /
4196
4197Writes the bytes b into the memory BIO.
4198
4199Returns the number of bytes written.
4200[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201
4202static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004203_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4204/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004206 int nbytes;
4207
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004208 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004209 PyErr_Format(PyExc_OverflowError,
4210 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004211 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004212 }
4213
4214 if (self->eof_written) {
4215 PyErr_SetString(PySSLErrorObject,
4216 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004217 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004218 }
4219
Segev Finer5cff6372017-07-27 01:19:17 +03004220 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004221 if (nbytes < 0) {
4222 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004223 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004224 }
4225
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004226 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004227}
4228
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004229/*[clinic input]
4230_ssl.MemoryBIO.write_eof
4231
4232Write an EOF marker to the memory BIO.
4233
4234When all data has been read, the "eof" property will be True.
4235[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004236
4237static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004238_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4239/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004240{
4241 self->eof_written = 1;
4242 /* After an EOF is written, a zero return from read() should be a real EOF
4243 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4244 BIO_clear_retry_flags(self->bio);
4245 BIO_set_mem_eof_return(self->bio, 0);
4246
4247 Py_RETURN_NONE;
4248}
4249
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004250static PyGetSetDef memory_bio_getsetlist[] = {
4251 {"pending", (getter) memory_bio_get_pending, NULL,
4252 PySSL_memory_bio_pending_doc},
4253 {"eof", (getter) memory_bio_get_eof, NULL,
4254 PySSL_memory_bio_eof_doc},
4255 {NULL}, /* sentinel */
4256};
4257
4258static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004259 _SSL_MEMORYBIO_READ_METHODDEF
4260 _SSL_MEMORYBIO_WRITE_METHODDEF
4261 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004262 {NULL, NULL} /* sentinel */
4263};
4264
4265static PyTypeObject PySSLMemoryBIO_Type = {
4266 PyVarObject_HEAD_INIT(NULL, 0)
4267 "_ssl.MemoryBIO", /*tp_name*/
4268 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4269 0, /*tp_itemsize*/
4270 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4271 0, /*tp_print*/
4272 0, /*tp_getattr*/
4273 0, /*tp_setattr*/
4274 0, /*tp_reserved*/
4275 0, /*tp_repr*/
4276 0, /*tp_as_number*/
4277 0, /*tp_as_sequence*/
4278 0, /*tp_as_mapping*/
4279 0, /*tp_hash*/
4280 0, /*tp_call*/
4281 0, /*tp_str*/
4282 0, /*tp_getattro*/
4283 0, /*tp_setattro*/
4284 0, /*tp_as_buffer*/
4285 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4286 0, /*tp_doc*/
4287 0, /*tp_traverse*/
4288 0, /*tp_clear*/
4289 0, /*tp_richcompare*/
4290 0, /*tp_weaklistoffset*/
4291 0, /*tp_iter*/
4292 0, /*tp_iternext*/
4293 memory_bio_methods, /*tp_methods*/
4294 0, /*tp_members*/
4295 memory_bio_getsetlist, /*tp_getset*/
4296 0, /*tp_base*/
4297 0, /*tp_dict*/
4298 0, /*tp_descr_get*/
4299 0, /*tp_descr_set*/
4300 0, /*tp_dictoffset*/
4301 0, /*tp_init*/
4302 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004303 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004304};
4305
Antoine Pitrou152efa22010-05-16 18:19:27 +00004306
Christian Heimes99a65702016-09-10 23:44:53 +02004307/*
4308 * SSL Session object
4309 */
4310
4311static void
4312PySSLSession_dealloc(PySSLSession *self)
4313{
INADA Naokia6296d32017-08-24 14:55:17 +09004314 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004315 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004316 Py_XDECREF(self->ctx);
4317 if (self->session != NULL) {
4318 SSL_SESSION_free(self->session);
4319 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004320 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004321}
4322
4323static PyObject *
4324PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4325{
4326 int result;
4327
4328 if (left == NULL || right == NULL) {
4329 PyErr_BadInternalCall();
4330 return NULL;
4331 }
4332
4333 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4334 Py_RETURN_NOTIMPLEMENTED;
4335 }
4336
4337 if (left == right) {
4338 result = 0;
4339 } else {
4340 const unsigned char *left_id, *right_id;
4341 unsigned int left_len, right_len;
4342 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4343 &left_len);
4344 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4345 &right_len);
4346 if (left_len == right_len) {
4347 result = memcmp(left_id, right_id, left_len);
4348 } else {
4349 result = 1;
4350 }
4351 }
4352
4353 switch (op) {
4354 case Py_EQ:
4355 if (result == 0) {
4356 Py_RETURN_TRUE;
4357 } else {
4358 Py_RETURN_FALSE;
4359 }
4360 break;
4361 case Py_NE:
4362 if (result != 0) {
4363 Py_RETURN_TRUE;
4364 } else {
4365 Py_RETURN_FALSE;
4366 }
4367 break;
4368 case Py_LT:
4369 case Py_LE:
4370 case Py_GT:
4371 case Py_GE:
4372 Py_RETURN_NOTIMPLEMENTED;
4373 break;
4374 default:
4375 PyErr_BadArgument();
4376 return NULL;
4377 }
4378}
4379
4380static int
4381PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4382{
4383 Py_VISIT(self->ctx);
4384 return 0;
4385}
4386
4387static int
4388PySSLSession_clear(PySSLSession *self)
4389{
4390 Py_CLEAR(self->ctx);
4391 return 0;
4392}
4393
4394
4395static PyObject *
4396PySSLSession_get_time(PySSLSession *self, void *closure) {
4397 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4398}
4399
4400PyDoc_STRVAR(PySSLSession_get_time_doc,
4401"Session creation time (seconds since epoch).");
4402
4403
4404static PyObject *
4405PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4406 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4407}
4408
4409PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4410"Session timeout (delta in seconds).");
4411
4412
4413static PyObject *
4414PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4415 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4416 return PyLong_FromUnsignedLong(hint);
4417}
4418
4419PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4420"Ticket life time hint.");
4421
4422
4423static PyObject *
4424PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4425 const unsigned char *id;
4426 unsigned int len;
4427 id = SSL_SESSION_get_id(self->session, &len);
4428 return PyBytes_FromStringAndSize((const char *)id, len);
4429}
4430
4431PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4432"Session id");
4433
4434
4435static PyObject *
4436PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4437 if (SSL_SESSION_has_ticket(self->session)) {
4438 Py_RETURN_TRUE;
4439 } else {
4440 Py_RETURN_FALSE;
4441 }
4442}
4443
4444PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4445"Does the session contain a ticket?");
4446
4447
4448static PyGetSetDef PySSLSession_getsetlist[] = {
4449 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4450 PySSLSession_get_has_ticket_doc},
4451 {"id", (getter) PySSLSession_get_session_id, NULL,
4452 PySSLSession_get_session_id_doc},
4453 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4454 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4455 {"time", (getter) PySSLSession_get_time, NULL,
4456 PySSLSession_get_time_doc},
4457 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4458 PySSLSession_get_timeout_doc},
4459 {NULL}, /* sentinel */
4460};
4461
4462static PyTypeObject PySSLSession_Type = {
4463 PyVarObject_HEAD_INIT(NULL, 0)
4464 "_ssl.Session", /*tp_name*/
4465 sizeof(PySSLSession), /*tp_basicsize*/
4466 0, /*tp_itemsize*/
4467 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4468 0, /*tp_print*/
4469 0, /*tp_getattr*/
4470 0, /*tp_setattr*/
4471 0, /*tp_reserved*/
4472 0, /*tp_repr*/
4473 0, /*tp_as_number*/
4474 0, /*tp_as_sequence*/
4475 0, /*tp_as_mapping*/
4476 0, /*tp_hash*/
4477 0, /*tp_call*/
4478 0, /*tp_str*/
4479 0, /*tp_getattro*/
4480 0, /*tp_setattro*/
4481 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004482 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004483 0, /*tp_doc*/
4484 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4485 (inquiry)PySSLSession_clear, /*tp_clear*/
4486 PySSLSession_richcompare, /*tp_richcompare*/
4487 0, /*tp_weaklistoffset*/
4488 0, /*tp_iter*/
4489 0, /*tp_iternext*/
4490 0, /*tp_methods*/
4491 0, /*tp_members*/
4492 PySSLSession_getsetlist, /*tp_getset*/
4493};
4494
4495
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004496/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004497/*[clinic input]
4498_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004499 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004500 entropy: double
4501 /
4502
4503Mix string into the OpenSSL PRNG state.
4504
4505entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304506string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004507[clinic start generated code]*/
4508
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004509static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004510_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004511/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004512{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004513 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004514 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004515
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004516 buf = (const char *)view->buf;
4517 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004518 do {
4519 written = Py_MIN(len, INT_MAX);
4520 RAND_add(buf, (int)written, entropy);
4521 buf += written;
4522 len -= written;
4523 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004524 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004525}
4526
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004527static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004528PySSL_RAND(int len, int pseudo)
4529{
4530 int ok;
4531 PyObject *bytes;
4532 unsigned long err;
4533 const char *errstr;
4534 PyObject *v;
4535
Victor Stinner1e81a392013-12-19 16:47:04 +01004536 if (len < 0) {
4537 PyErr_SetString(PyExc_ValueError, "num must be positive");
4538 return NULL;
4539 }
4540
Victor Stinner99c8b162011-05-24 12:05:19 +02004541 bytes = PyBytes_FromStringAndSize(NULL, len);
4542 if (bytes == NULL)
4543 return NULL;
4544 if (pseudo) {
4545 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4546 if (ok == 0 || ok == 1)
4547 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4548 }
4549 else {
4550 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4551 if (ok == 1)
4552 return bytes;
4553 }
4554 Py_DECREF(bytes);
4555
4556 err = ERR_get_error();
4557 errstr = ERR_reason_error_string(err);
4558 v = Py_BuildValue("(ks)", err, errstr);
4559 if (v != NULL) {
4560 PyErr_SetObject(PySSLErrorObject, v);
4561 Py_DECREF(v);
4562 }
4563 return NULL;
4564}
4565
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004566/*[clinic input]
4567_ssl.RAND_bytes
4568 n: int
4569 /
4570
4571Generate n cryptographically strong pseudo-random bytes.
4572[clinic start generated code]*/
4573
Victor Stinner99c8b162011-05-24 12:05:19 +02004574static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004575_ssl_RAND_bytes_impl(PyObject *module, int n)
4576/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004577{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004578 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004579}
4580
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004581/*[clinic input]
4582_ssl.RAND_pseudo_bytes
4583 n: int
4584 /
4585
4586Generate n pseudo-random bytes.
4587
4588Return a pair (bytes, is_cryptographic). is_cryptographic is True
4589if the bytes generated are cryptographically strong.
4590[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004591
4592static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004593_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4594/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004595{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004596 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004597}
4598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004599/*[clinic input]
4600_ssl.RAND_status
4601
4602Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4603
4604It is necessary to seed the PRNG with RAND_add() on some platforms before
4605using the ssl() function.
4606[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004607
4608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004609_ssl_RAND_status_impl(PyObject *module)
4610/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004611{
Christian Heimes217cfd12007-12-02 14:31:20 +00004612 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004613}
4614
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004615#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004616/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004617/*[clinic input]
4618_ssl.RAND_egd
4619 path: object(converter="PyUnicode_FSConverter")
4620 /
4621
4622Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4623
4624Returns number of bytes read. Raises SSLError if connection to EGD
4625fails or if it does not provide enough data to seed PRNG.
4626[clinic start generated code]*/
4627
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004628static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004629_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4630/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004631{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004632 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004633 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004634 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004635 PyErr_SetString(PySSLErrorObject,
4636 "EGD connection failed or EGD did not return "
4637 "enough data to seed the PRNG");
4638 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004639 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004640 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004641}
Christian Heimesa5d07652016-09-24 10:48:05 +02004642/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004643#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004644
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004645
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004646
4647/*[clinic input]
4648_ssl.get_default_verify_paths
4649
4650Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4651
4652The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4653[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004654
4655static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004656_ssl_get_default_verify_paths_impl(PyObject *module)
4657/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004658{
4659 PyObject *ofile_env = NULL;
4660 PyObject *ofile = NULL;
4661 PyObject *odir_env = NULL;
4662 PyObject *odir = NULL;
4663
Benjamin Petersond113c962015-07-18 10:59:13 -07004664#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004665 const char *tmp = (info); \
4666 target = NULL; \
4667 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4668 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4669 target = PyBytes_FromString(tmp); } \
4670 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004671 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004672
Benjamin Petersond113c962015-07-18 10:59:13 -07004673 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4674 CONVERT(X509_get_default_cert_file(), ofile);
4675 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4676 CONVERT(X509_get_default_cert_dir(), odir);
4677#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004678
Christian Heimes200bb1b2013-06-14 15:14:29 +02004679 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004680
4681 error:
4682 Py_XDECREF(ofile_env);
4683 Py_XDECREF(ofile);
4684 Py_XDECREF(odir_env);
4685 Py_XDECREF(odir);
4686 return NULL;
4687}
4688
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004689static PyObject*
4690asn1obj2py(ASN1_OBJECT *obj)
4691{
4692 int nid;
4693 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004694
4695 nid = OBJ_obj2nid(obj);
4696 if (nid == NID_undef) {
4697 PyErr_Format(PyExc_ValueError, "Unknown object");
4698 return NULL;
4699 }
4700 sn = OBJ_nid2sn(nid);
4701 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004702 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004703}
4704
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004705/*[clinic input]
4706_ssl.txt2obj
4707 txt: str
4708 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004709
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004710Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4711
4712By default objects are looked up by OID. With name=True short and
4713long name are also matched.
4714[clinic start generated code]*/
4715
4716static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004717_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4718/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004719{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004720 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004721 ASN1_OBJECT *obj;
4722
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004723 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4724 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004725 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004726 return NULL;
4727 }
4728 result = asn1obj2py(obj);
4729 ASN1_OBJECT_free(obj);
4730 return result;
4731}
4732
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004733/*[clinic input]
4734_ssl.nid2obj
4735 nid: int
4736 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004737
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004738Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4739[clinic start generated code]*/
4740
4741static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004742_ssl_nid2obj_impl(PyObject *module, int nid)
4743/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004744{
4745 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004746 ASN1_OBJECT *obj;
4747
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004748 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004749 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004750 return NULL;
4751 }
4752 obj = OBJ_nid2obj(nid);
4753 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004754 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004755 return NULL;
4756 }
4757 result = asn1obj2py(obj);
4758 ASN1_OBJECT_free(obj);
4759 return result;
4760}
4761
Christian Heimes46bebee2013-06-09 19:03:31 +02004762#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004763
4764static PyObject*
4765certEncodingType(DWORD encodingType)
4766{
4767 static PyObject *x509_asn = NULL;
4768 static PyObject *pkcs_7_asn = NULL;
4769
4770 if (x509_asn == NULL) {
4771 x509_asn = PyUnicode_InternFromString("x509_asn");
4772 if (x509_asn == NULL)
4773 return NULL;
4774 }
4775 if (pkcs_7_asn == NULL) {
4776 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4777 if (pkcs_7_asn == NULL)
4778 return NULL;
4779 }
4780 switch(encodingType) {
4781 case X509_ASN_ENCODING:
4782 Py_INCREF(x509_asn);
4783 return x509_asn;
4784 case PKCS_7_ASN_ENCODING:
4785 Py_INCREF(pkcs_7_asn);
4786 return pkcs_7_asn;
4787 default:
4788 return PyLong_FromLong(encodingType);
4789 }
4790}
4791
4792static PyObject*
4793parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4794{
4795 CERT_ENHKEY_USAGE *usage;
4796 DWORD size, error, i;
4797 PyObject *retval;
4798
4799 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4800 error = GetLastError();
4801 if (error == CRYPT_E_NOT_FOUND) {
4802 Py_RETURN_TRUE;
4803 }
4804 return PyErr_SetFromWindowsErr(error);
4805 }
4806
4807 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4808 if (usage == NULL) {
4809 return PyErr_NoMemory();
4810 }
4811
4812 /* Now get the actual enhanced usage property */
4813 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4814 PyMem_Free(usage);
4815 error = GetLastError();
4816 if (error == CRYPT_E_NOT_FOUND) {
4817 Py_RETURN_TRUE;
4818 }
4819 return PyErr_SetFromWindowsErr(error);
4820 }
4821 retval = PySet_New(NULL);
4822 if (retval == NULL) {
4823 goto error;
4824 }
4825 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4826 if (usage->rgpszUsageIdentifier[i]) {
4827 PyObject *oid;
4828 int err;
4829 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4830 if (oid == NULL) {
4831 Py_CLEAR(retval);
4832 goto error;
4833 }
4834 err = PySet_Add(retval, oid);
4835 Py_DECREF(oid);
4836 if (err == -1) {
4837 Py_CLEAR(retval);
4838 goto error;
4839 }
4840 }
4841 }
4842 error:
4843 PyMem_Free(usage);
4844 return retval;
4845}
4846
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004847/*[clinic input]
4848_ssl.enum_certificates
4849 store_name: str
4850
4851Retrieve certificates from Windows' cert store.
4852
4853store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4854more cert storages, too. The function returns a list of (bytes,
4855encoding_type, trust) tuples. The encoding_type flag can be interpreted
4856with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4857a set of OIDs or the boolean True.
4858[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004859
Christian Heimes46bebee2013-06-09 19:03:31 +02004860static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004861_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4862/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004863{
Christian Heimes46bebee2013-06-09 19:03:31 +02004864 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004865 PCCERT_CONTEXT pCertCtx = NULL;
4866 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004867 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004868
Christian Heimes44109d72013-11-22 01:51:30 +01004869 result = PyList_New(0);
4870 if (result == NULL) {
4871 return NULL;
4872 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004873 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4874 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4875 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004876 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004877 Py_DECREF(result);
4878 return PyErr_SetFromWindowsErr(GetLastError());
4879 }
4880
Christian Heimes44109d72013-11-22 01:51:30 +01004881 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4882 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4883 pCertCtx->cbCertEncoded);
4884 if (!cert) {
4885 Py_CLEAR(result);
4886 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004887 }
Christian Heimes44109d72013-11-22 01:51:30 +01004888 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4889 Py_CLEAR(result);
4890 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004891 }
Christian Heimes44109d72013-11-22 01:51:30 +01004892 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4893 if (keyusage == Py_True) {
4894 Py_DECREF(keyusage);
4895 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004896 }
Christian Heimes44109d72013-11-22 01:51:30 +01004897 if (keyusage == NULL) {
4898 Py_CLEAR(result);
4899 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004900 }
Christian Heimes44109d72013-11-22 01:51:30 +01004901 if ((tup = PyTuple_New(3)) == NULL) {
4902 Py_CLEAR(result);
4903 break;
4904 }
4905 PyTuple_SET_ITEM(tup, 0, cert);
4906 cert = NULL;
4907 PyTuple_SET_ITEM(tup, 1, enc);
4908 enc = NULL;
4909 PyTuple_SET_ITEM(tup, 2, keyusage);
4910 keyusage = NULL;
4911 if (PyList_Append(result, tup) < 0) {
4912 Py_CLEAR(result);
4913 break;
4914 }
4915 Py_CLEAR(tup);
4916 }
4917 if (pCertCtx) {
4918 /* loop ended with an error, need to clean up context manually */
4919 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004920 }
4921
4922 /* In error cases cert, enc and tup may not be NULL */
4923 Py_XDECREF(cert);
4924 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004925 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004926 Py_XDECREF(tup);
4927
4928 if (!CertCloseStore(hStore, 0)) {
4929 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004930 Py_XDECREF(result);
4931 return PyErr_SetFromWindowsErr(GetLastError());
4932 }
4933 return result;
4934}
4935
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004936/*[clinic input]
4937_ssl.enum_crls
4938 store_name: str
4939
4940Retrieve CRLs from Windows' cert store.
4941
4942store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4943more cert storages, too. The function returns a list of (bytes,
4944encoding_type) tuples. The encoding_type flag can be interpreted with
4945X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4946[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004947
4948static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004949_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4950/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004951{
Christian Heimes44109d72013-11-22 01:51:30 +01004952 HCERTSTORE hStore = NULL;
4953 PCCRL_CONTEXT pCrlCtx = NULL;
4954 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4955 PyObject *result = NULL;
4956
Christian Heimes44109d72013-11-22 01:51:30 +01004957 result = PyList_New(0);
4958 if (result == NULL) {
4959 return NULL;
4960 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004961 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4962 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4963 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004964 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004965 Py_DECREF(result);
4966 return PyErr_SetFromWindowsErr(GetLastError());
4967 }
Christian Heimes44109d72013-11-22 01:51:30 +01004968
4969 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4970 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4971 pCrlCtx->cbCrlEncoded);
4972 if (!crl) {
4973 Py_CLEAR(result);
4974 break;
4975 }
4976 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4977 Py_CLEAR(result);
4978 break;
4979 }
4980 if ((tup = PyTuple_New(2)) == NULL) {
4981 Py_CLEAR(result);
4982 break;
4983 }
4984 PyTuple_SET_ITEM(tup, 0, crl);
4985 crl = NULL;
4986 PyTuple_SET_ITEM(tup, 1, enc);
4987 enc = NULL;
4988
4989 if (PyList_Append(result, tup) < 0) {
4990 Py_CLEAR(result);
4991 break;
4992 }
4993 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004994 }
Christian Heimes44109d72013-11-22 01:51:30 +01004995 if (pCrlCtx) {
4996 /* loop ended with an error, need to clean up context manually */
4997 CertFreeCRLContext(pCrlCtx);
4998 }
4999
5000 /* In error cases cert, enc and tup may not be NULL */
5001 Py_XDECREF(crl);
5002 Py_XDECREF(enc);
5003 Py_XDECREF(tup);
5004
5005 if (!CertCloseStore(hStore, 0)) {
5006 /* This error case might shadow another exception.*/
5007 Py_XDECREF(result);
5008 return PyErr_SetFromWindowsErr(GetLastError());
5009 }
5010 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005011}
Christian Heimes44109d72013-11-22 01:51:30 +01005012
5013#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005014
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005015/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005016static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005017 _SSL__TEST_DECODE_CERT_METHODDEF
5018 _SSL_RAND_ADD_METHODDEF
5019 _SSL_RAND_BYTES_METHODDEF
5020 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5021 _SSL_RAND_EGD_METHODDEF
5022 _SSL_RAND_STATUS_METHODDEF
5023 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5024 _SSL_ENUM_CERTIFICATES_METHODDEF
5025 _SSL_ENUM_CRLS_METHODDEF
5026 _SSL_TXT2OBJ_METHODDEF
5027 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005028 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005029};
5030
5031
Christian Heimes598894f2016-09-05 23:19:05 +02005032#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033
5034/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005035 * of the Python C thread library
5036 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5037 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005038
5039static PyThread_type_lock *_ssl_locks = NULL;
5040
Christian Heimes4d98ca92013-08-19 17:36:29 +02005041#if OPENSSL_VERSION_NUMBER >= 0x10000000
5042/* use new CRYPTO_THREADID API. */
5043static void
5044_ssl_threadid_callback(CRYPTO_THREADID *id)
5045{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005046 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005047}
5048#else
5049/* deprecated CRYPTO_set_id_callback() API. */
5050static unsigned long
5051_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005052 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005053}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005054#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005055
Bill Janssen6e027db2007-11-15 22:23:56 +00005056static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005057 (int mode, int n, const char *file, int line) {
5058 /* this function is needed to perform locking on shared data
5059 structures. (Note that OpenSSL uses a number of global data
5060 structures that will be implicitly shared whenever multiple
5061 threads use OpenSSL.) Multi-threaded applications will
5062 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005064 locking_function() must be able to handle up to
5065 CRYPTO_num_locks() different mutex locks. It sets the n-th
5066 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005067
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005068 file and line are the file number of the function setting the
5069 lock. They can be useful for debugging.
5070 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005071
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005072 if ((_ssl_locks == NULL) ||
5073 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5074 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005076 if (mode & CRYPTO_LOCK) {
5077 PyThread_acquire_lock(_ssl_locks[n], 1);
5078 } else {
5079 PyThread_release_lock(_ssl_locks[n]);
5080 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005081}
5082
5083static int _setup_ssl_threads(void) {
5084
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005085 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005086
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005087 if (_ssl_locks == NULL) {
5088 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005089 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5090 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005091 if (_ssl_locks == NULL) {
5092 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005093 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005094 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005095 for (i = 0; i < _ssl_locks_count; i++) {
5096 _ssl_locks[i] = PyThread_allocate_lock();
5097 if (_ssl_locks[i] == NULL) {
5098 unsigned int j;
5099 for (j = 0; j < i; j++) {
5100 PyThread_free_lock(_ssl_locks[j]);
5101 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005102 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005103 return 0;
5104 }
5105 }
5106 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005107#if OPENSSL_VERSION_NUMBER >= 0x10000000
5108 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5109#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005110 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005111#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005112 }
5113 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005114}
5115
Christian Heimes598894f2016-09-05 23:19:05 +02005116#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005117
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005118PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005119"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005120for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005121
Martin v. Löwis1a214512008-06-11 05:26:20 +00005122
5123static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005124 PyModuleDef_HEAD_INIT,
5125 "_ssl",
5126 module_doc,
5127 -1,
5128 PySSL_methods,
5129 NULL,
5130 NULL,
5131 NULL,
5132 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005133};
5134
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005135
5136static void
5137parse_openssl_version(unsigned long libver,
5138 unsigned int *major, unsigned int *minor,
5139 unsigned int *fix, unsigned int *patch,
5140 unsigned int *status)
5141{
5142 *status = libver & 0xF;
5143 libver >>= 4;
5144 *patch = libver & 0xFF;
5145 libver >>= 8;
5146 *fix = libver & 0xFF;
5147 libver >>= 8;
5148 *minor = libver & 0xFF;
5149 libver >>= 8;
5150 *major = libver & 0xFF;
5151}
5152
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005153PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005154PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005155{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005156 PyObject *m, *d, *r;
5157 unsigned long libver;
5158 unsigned int major, minor, fix, patch, status;
5159 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005160 struct py_ssl_error_code *errcode;
5161 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005162
Antoine Pitrou152efa22010-05-16 18:19:27 +00005163 if (PyType_Ready(&PySSLContext_Type) < 0)
5164 return NULL;
5165 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005166 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005167 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5168 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005169 if (PyType_Ready(&PySSLSession_Type) < 0)
5170 return NULL;
5171
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005173 m = PyModule_Create(&_sslmodule);
5174 if (m == NULL)
5175 return NULL;
5176 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005178 /* Load _socket module and its C API */
5179 socket_api = PySocketModule_ImportModuleAndAPI();
5180 if (!socket_api)
5181 return NULL;
5182 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005183
Christian Heimesc941e622017-09-05 15:47:11 +02005184#ifndef OPENSSL_VERSION_1_1
5185 /* Load all algorithms and initialize cpuid */
5186 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005187 /* Init OpenSSL */
5188 SSL_load_error_strings();
5189 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005190#endif
5191
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005192#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005193#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005194 /* note that this will start threading if not already started */
5195 if (!_setup_ssl_threads()) {
5196 return NULL;
5197 }
Christian Heimes598894f2016-09-05 23:19:05 +02005198#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5199 /* OpenSSL 1.1.0 builtin thread support is enabled */
5200 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005201#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005202#endif /* WITH_THREAD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005203
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005204 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005205 sslerror_type_slots[0].pfunc = PyExc_OSError;
5206 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005207 if (PySSLErrorObject == NULL)
5208 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005209
Antoine Pitrou41032a62011-10-27 23:56:55 +02005210 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5211 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5212 PySSLErrorObject, NULL);
5213 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5214 "ssl.SSLWantReadError", SSLWantReadError_doc,
5215 PySSLErrorObject, NULL);
5216 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5217 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5218 PySSLErrorObject, NULL);
5219 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5220 "ssl.SSLSyscallError", SSLSyscallError_doc,
5221 PySSLErrorObject, NULL);
5222 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5223 "ssl.SSLEOFError", SSLEOFError_doc,
5224 PySSLErrorObject, NULL);
5225 if (PySSLZeroReturnErrorObject == NULL
5226 || PySSLWantReadErrorObject == NULL
5227 || PySSLWantWriteErrorObject == NULL
5228 || PySSLSyscallErrorObject == NULL
5229 || PySSLEOFErrorObject == NULL)
5230 return NULL;
5231 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5232 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5233 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5234 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5235 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5236 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005237 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005238 if (PyDict_SetItemString(d, "_SSLContext",
5239 (PyObject *)&PySSLContext_Type) != 0)
5240 return NULL;
5241 if (PyDict_SetItemString(d, "_SSLSocket",
5242 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005243 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005244 if (PyDict_SetItemString(d, "MemoryBIO",
5245 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5246 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005247 if (PyDict_SetItemString(d, "SSLSession",
5248 (PyObject *)&PySSLSession_Type) != 0)
5249 return NULL;
5250
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005251 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5252 PY_SSL_ERROR_ZERO_RETURN);
5253 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5254 PY_SSL_ERROR_WANT_READ);
5255 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5256 PY_SSL_ERROR_WANT_WRITE);
5257 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5258 PY_SSL_ERROR_WANT_X509_LOOKUP);
5259 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5260 PY_SSL_ERROR_SYSCALL);
5261 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5262 PY_SSL_ERROR_SSL);
5263 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5264 PY_SSL_ERROR_WANT_CONNECT);
5265 /* non ssl.h errorcodes */
5266 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5267 PY_SSL_ERROR_EOF);
5268 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5269 PY_SSL_ERROR_INVALID_ERROR_CODE);
5270 /* cert requirements */
5271 PyModule_AddIntConstant(m, "CERT_NONE",
5272 PY_SSL_CERT_NONE);
5273 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5274 PY_SSL_CERT_OPTIONAL);
5275 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5276 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005277 /* CRL verification for verification_flags */
5278 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5279 0);
5280 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5281 X509_V_FLAG_CRL_CHECK);
5282 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5283 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5284 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5285 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005286#ifdef X509_V_FLAG_TRUSTED_FIRST
5287 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5288 X509_V_FLAG_TRUSTED_FIRST);
5289#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005290
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005291 /* Alert Descriptions from ssl.h */
5292 /* note RESERVED constants no longer intended for use have been removed */
5293 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5294
5295#define ADD_AD_CONSTANT(s) \
5296 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5297 SSL_AD_##s)
5298
5299 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5300 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5301 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5302 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5303 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5304 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5305 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5306 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5307 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5308 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5309 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5310 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5311 ADD_AD_CONSTANT(UNKNOWN_CA);
5312 ADD_AD_CONSTANT(ACCESS_DENIED);
5313 ADD_AD_CONSTANT(DECODE_ERROR);
5314 ADD_AD_CONSTANT(DECRYPT_ERROR);
5315 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5316 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5317 ADD_AD_CONSTANT(INTERNAL_ERROR);
5318 ADD_AD_CONSTANT(USER_CANCELLED);
5319 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005320 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005321#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5322 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5323#endif
5324#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5325 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5326#endif
5327#ifdef SSL_AD_UNRECOGNIZED_NAME
5328 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5329#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005330#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5331 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5332#endif
5333#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5334 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5335#endif
5336#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5337 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5338#endif
5339
5340#undef ADD_AD_CONSTANT
5341
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005342 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005343#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005344 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5345 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005346#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005347#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005348 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5349 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005350#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005351 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005352 PY_SSL_VERSION_TLS);
5353 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5354 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005355 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5356 PY_SSL_VERSION_TLS_CLIENT);
5357 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5358 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005359 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5360 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005361#if HAVE_TLSv1_2
5362 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5363 PY_SSL_VERSION_TLS1_1);
5364 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5365 PY_SSL_VERSION_TLS1_2);
5366#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005367
Antoine Pitroub5218772010-05-21 09:56:06 +00005368 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005369 PyModule_AddIntConstant(m, "OP_ALL",
5370 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005371 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5372 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5373 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005374#if HAVE_TLSv1_2
5375 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5376 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5377#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005378 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5379 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005380 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005381 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005382#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005383 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005384#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005385#ifdef SSL_OP_NO_COMPRESSION
5386 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5387 SSL_OP_NO_COMPRESSION);
5388#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005389
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005390#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005391 r = Py_True;
5392#else
5393 r = Py_False;
5394#endif
5395 Py_INCREF(r);
5396 PyModule_AddObject(m, "HAS_SNI", r);
5397
Antoine Pitroud6494802011-07-21 01:11:30 +02005398 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005399 Py_INCREF(r);
5400 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5401
Antoine Pitrou501da612011-12-21 09:27:41 +01005402#ifdef OPENSSL_NO_ECDH
5403 r = Py_False;
5404#else
5405 r = Py_True;
5406#endif
5407 Py_INCREF(r);
5408 PyModule_AddObject(m, "HAS_ECDH", r);
5409
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005410#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005411 r = Py_True;
5412#else
5413 r = Py_False;
5414#endif
5415 Py_INCREF(r);
5416 PyModule_AddObject(m, "HAS_NPN", r);
5417
Benjamin Petersoncca27322015-01-23 16:35:37 -05005418#ifdef HAVE_ALPN
5419 r = Py_True;
5420#else
5421 r = Py_False;
5422#endif
5423 Py_INCREF(r);
5424 PyModule_AddObject(m, "HAS_ALPN", r);
5425
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005426 /* Mappings for error codes */
5427 err_codes_to_names = PyDict_New();
5428 err_names_to_codes = PyDict_New();
5429 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5430 return NULL;
5431 errcode = error_codes;
5432 while (errcode->mnemonic != NULL) {
5433 PyObject *mnemo, *key;
5434 mnemo = PyUnicode_FromString(errcode->mnemonic);
5435 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5436 if (mnemo == NULL || key == NULL)
5437 return NULL;
5438 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5439 return NULL;
5440 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5441 return NULL;
5442 Py_DECREF(key);
5443 Py_DECREF(mnemo);
5444 errcode++;
5445 }
5446 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5447 return NULL;
5448 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5449 return NULL;
5450
5451 lib_codes_to_names = PyDict_New();
5452 if (lib_codes_to_names == NULL)
5453 return NULL;
5454 libcode = library_codes;
5455 while (libcode->library != NULL) {
5456 PyObject *mnemo, *key;
5457 key = PyLong_FromLong(libcode->code);
5458 mnemo = PyUnicode_FromString(libcode->library);
5459 if (key == NULL || mnemo == NULL)
5460 return NULL;
5461 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5462 return NULL;
5463 Py_DECREF(key);
5464 Py_DECREF(mnemo);
5465 libcode++;
5466 }
5467 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5468 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005469
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005470 /* OpenSSL version */
5471 /* SSLeay() gives us the version of the library linked against,
5472 which could be different from the headers version.
5473 */
5474 libver = SSLeay();
5475 r = PyLong_FromUnsignedLong(libver);
5476 if (r == NULL)
5477 return NULL;
5478 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5479 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005480 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005481 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5482 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5483 return NULL;
5484 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5485 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5486 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005487
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005488 libver = OPENSSL_VERSION_NUMBER;
5489 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5490 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5491 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5492 return NULL;
5493
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005494 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005495}