blob: 1380c575119bf41dde74491abd17446f17aea599 [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;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100318#ifdef OPENSSL_NPN_NEGOTIATED
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 *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000790_create_tuple_for_attribute (ASN1_OBJECT *name, ASN1_STRING *value) {
Thomas Woutersed03b412007-08-28 21:37:11 +0000791
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000792 char namebuf[X509_NAME_MAXLEN];
793 int buflen;
794 PyObject *name_obj;
795 PyObject *value_obj;
796 PyObject *attr;
797 unsigned char *valuebuf = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000798
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000799 buflen = OBJ_obj2txt(namebuf, sizeof(namebuf), name, 0);
800 if (buflen < 0) {
801 _setSSLError(NULL, 0, __FILE__, __LINE__);
802 goto fail;
803 }
804 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
805 if (name_obj == NULL)
806 goto fail;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000807
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000808 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
809 if (buflen < 0) {
810 _setSSLError(NULL, 0, __FILE__, __LINE__);
811 Py_DECREF(name_obj);
812 goto fail;
813 }
814 value_obj = PyUnicode_DecodeUTF8((char *) valuebuf,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000815 buflen, "strict");
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 OPENSSL_free(valuebuf);
817 if (value_obj == NULL) {
818 Py_DECREF(name_obj);
819 goto fail;
820 }
821 attr = PyTuple_New(2);
822 if (attr == NULL) {
823 Py_DECREF(name_obj);
824 Py_DECREF(value_obj);
825 goto fail;
826 }
827 PyTuple_SET_ITEM(attr, 0, name_obj);
828 PyTuple_SET_ITEM(attr, 1, value_obj);
829 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000830
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000831 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000833}
834
835static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000836_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000837{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
839 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
840 PyObject *rdnt;
841 PyObject *attr = NULL; /* tuple to hold an attribute */
842 int entry_count = X509_NAME_entry_count(xname);
843 X509_NAME_ENTRY *entry;
844 ASN1_OBJECT *name;
845 ASN1_STRING *value;
846 int index_counter;
847 int rdn_level = -1;
848 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000849
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 dn = PyList_New(0);
851 if (dn == NULL)
852 return NULL;
853 /* now create another tuple to hold the top-level RDN */
854 rdn = PyList_New(0);
855 if (rdn == NULL)
856 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000857
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 for (index_counter = 0;
859 index_counter < entry_count;
860 index_counter++)
861 {
862 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000863
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 /* check to see if we've gotten to a new RDN */
865 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200866 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000867 /* yes, new RDN */
868 /* add old RDN to DN */
869 rdnt = PyList_AsTuple(rdn);
870 Py_DECREF(rdn);
871 if (rdnt == NULL)
872 goto fail0;
873 retcode = PyList_Append(dn, rdnt);
874 Py_DECREF(rdnt);
875 if (retcode < 0)
876 goto fail0;
877 /* create new RDN */
878 rdn = PyList_New(0);
879 if (rdn == NULL)
880 goto fail0;
881 }
882 }
Christian Heimes598894f2016-09-05 23:19:05 +0200883 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000884
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 /* now add this attribute to the current RDN */
886 name = X509_NAME_ENTRY_get_object(entry);
887 value = X509_NAME_ENTRY_get_data(entry);
888 attr = _create_tuple_for_attribute(name, value);
889 /*
890 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
891 entry->set,
892 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
893 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
894 */
895 if (attr == NULL)
896 goto fail1;
897 retcode = PyList_Append(rdn, attr);
898 Py_DECREF(attr);
899 if (retcode < 0)
900 goto fail1;
901 }
902 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100903 if (rdn != NULL) {
904 if (PyList_GET_SIZE(rdn) > 0) {
905 rdnt = PyList_AsTuple(rdn);
906 Py_DECREF(rdn);
907 if (rdnt == NULL)
908 goto fail0;
909 retcode = PyList_Append(dn, rdnt);
910 Py_DECREF(rdnt);
911 if (retcode < 0)
912 goto fail0;
913 }
914 else {
915 Py_DECREF(rdn);
916 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000917 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000918
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000919 /* convert list to tuple */
920 rdnt = PyList_AsTuple(dn);
921 Py_DECREF(dn);
922 if (rdnt == NULL)
923 return NULL;
924 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
926 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000928
929 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 Py_XDECREF(dn);
931 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000932}
933
934static PyObject *
935_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000936
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 /* this code follows the procedure outlined in
938 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
939 function to extract the STACK_OF(GENERAL_NAME),
940 then iterates through the stack to add the
941 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400943 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200945 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000946 GENERAL_NAMES *names = NULL;
947 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000948 BIO *biobuf = NULL;
949 char buf[2048];
950 char *vptr;
951 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 if (certificate == NULL)
954 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 /* get a memory buffer */
957 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000958
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400959 names = (GENERAL_NAMES *)X509_get_ext_d2i(
960 certificate, NID_subject_alt_name, NULL, NULL);
961 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000962 if (peer_alt_names == Py_None) {
963 peer_alt_names = PyList_New(0);
964 if (peer_alt_names == NULL)
965 goto fail;
966 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000967
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000968 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000969 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200970 int gntype;
971 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000972
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200974 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200975 switch (gntype) {
976 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 /* we special-case DirName as a tuple of
978 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000979
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000980 t = PyTuple_New(2);
981 if (t == NULL) {
982 goto fail;
983 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000984
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000985 v = PyUnicode_FromString("DirName");
986 if (v == NULL) {
987 Py_DECREF(t);
988 goto fail;
989 }
990 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000991
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000992 v = _create_tuple_for_X509_NAME (name->d.dirn);
993 if (v == NULL) {
994 Py_DECREF(t);
995 goto fail;
996 }
997 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200998 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000999
Christian Heimes824f7f32013-08-17 00:54:47 +02001000 case GEN_EMAIL:
1001 case GEN_DNS:
1002 case GEN_URI:
1003 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1004 correctly, CVE-2013-4238 */
1005 t = PyTuple_New(2);
1006 if (t == NULL)
1007 goto fail;
1008 switch (gntype) {
1009 case GEN_EMAIL:
1010 v = PyUnicode_FromString("email");
1011 as = name->d.rfc822Name;
1012 break;
1013 case GEN_DNS:
1014 v = PyUnicode_FromString("DNS");
1015 as = name->d.dNSName;
1016 break;
1017 case GEN_URI:
1018 v = PyUnicode_FromString("URI");
1019 as = name->d.uniformResourceIdentifier;
1020 break;
1021 }
1022 if (v == NULL) {
1023 Py_DECREF(t);
1024 goto fail;
1025 }
1026 PyTuple_SET_ITEM(t, 0, v);
1027 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1028 ASN1_STRING_length(as));
1029 if (v == NULL) {
1030 Py_DECREF(t);
1031 goto fail;
1032 }
1033 PyTuple_SET_ITEM(t, 1, v);
1034 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001035
Christian Heimes1c03abd2016-09-06 23:25:35 +02001036 case GEN_RID:
1037 t = PyTuple_New(2);
1038 if (t == NULL)
1039 goto fail;
1040
1041 v = PyUnicode_FromString("Registered ID");
1042 if (v == NULL) {
1043 Py_DECREF(t);
1044 goto fail;
1045 }
1046 PyTuple_SET_ITEM(t, 0, v);
1047
1048 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1049 if (len < 0) {
1050 Py_DECREF(t);
1051 _setSSLError(NULL, 0, __FILE__, __LINE__);
1052 goto fail;
1053 } else if (len >= (int)sizeof(buf)) {
1054 v = PyUnicode_FromString("<INVALID>");
1055 } else {
1056 v = PyUnicode_FromStringAndSize(buf, len);
1057 }
1058 if (v == NULL) {
1059 Py_DECREF(t);
1060 goto fail;
1061 }
1062 PyTuple_SET_ITEM(t, 1, v);
1063 break;
1064
Christian Heimes824f7f32013-08-17 00:54:47 +02001065 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001066 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001067 switch (gntype) {
1068 /* check for new general name type */
1069 case GEN_OTHERNAME:
1070 case GEN_X400:
1071 case GEN_EDIPARTY:
1072 case GEN_IPADD:
1073 case GEN_RID:
1074 break;
1075 default:
1076 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1077 "Unknown general name type %d",
1078 gntype) == -1) {
1079 goto fail;
1080 }
1081 break;
1082 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 (void) BIO_reset(biobuf);
1084 GENERAL_NAME_print(biobuf, name);
1085 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1086 if (len < 0) {
1087 _setSSLError(NULL, 0, __FILE__, __LINE__);
1088 goto fail;
1089 }
1090 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001091 if (vptr == NULL) {
1092 PyErr_Format(PyExc_ValueError,
1093 "Invalid value %.200s",
1094 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001095 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001096 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001097 t = PyTuple_New(2);
1098 if (t == NULL)
1099 goto fail;
1100 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1101 if (v == NULL) {
1102 Py_DECREF(t);
1103 goto fail;
1104 }
1105 PyTuple_SET_ITEM(t, 0, v);
1106 v = PyUnicode_FromStringAndSize((vptr + 1),
1107 (len - (vptr - buf + 1)));
1108 if (v == NULL) {
1109 Py_DECREF(t);
1110 goto fail;
1111 }
1112 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001113 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001114 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001115
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001116 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001118 if (PyList_Append(peer_alt_names, t) < 0) {
1119 Py_DECREF(t);
1120 goto fail;
1121 }
1122 Py_DECREF(t);
1123 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001124 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001125 }
1126 BIO_free(biobuf);
1127 if (peer_alt_names != Py_None) {
1128 v = PyList_AsTuple(peer_alt_names);
1129 Py_DECREF(peer_alt_names);
1130 return v;
1131 } else {
1132 return peer_alt_names;
1133 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001134
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001135
1136 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 if (biobuf != NULL)
1138 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001139
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001140 if (peer_alt_names != Py_None) {
1141 Py_XDECREF(peer_alt_names);
1142 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001144 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001145}
1146
1147static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001148_get_aia_uri(X509 *certificate, int nid) {
1149 PyObject *lst = NULL, *ostr = NULL;
1150 int i, result;
1151 AUTHORITY_INFO_ACCESS *info;
1152
1153 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001154 if (info == NULL)
1155 return Py_None;
1156 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1157 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001158 return Py_None;
1159 }
1160
1161 if ((lst = PyList_New(0)) == NULL) {
1162 goto fail;
1163 }
1164
1165 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1166 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1167 ASN1_IA5STRING *uri;
1168
1169 if ((OBJ_obj2nid(ad->method) != nid) ||
1170 (ad->location->type != GEN_URI)) {
1171 continue;
1172 }
1173 uri = ad->location->d.uniformResourceIdentifier;
1174 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1175 uri->length);
1176 if (ostr == NULL) {
1177 goto fail;
1178 }
1179 result = PyList_Append(lst, ostr);
1180 Py_DECREF(ostr);
1181 if (result < 0) {
1182 goto fail;
1183 }
1184 }
1185 AUTHORITY_INFO_ACCESS_free(info);
1186
1187 /* convert to tuple or None */
1188 if (PyList_Size(lst) == 0) {
1189 Py_DECREF(lst);
1190 return Py_None;
1191 } else {
1192 PyObject *tup;
1193 tup = PyList_AsTuple(lst);
1194 Py_DECREF(lst);
1195 return tup;
1196 }
1197
1198 fail:
1199 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001200 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001201 return NULL;
1202}
1203
1204static PyObject *
1205_get_crl_dp(X509 *certificate) {
1206 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001207 int i, j;
1208 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001209
Christian Heimes598894f2016-09-05 23:19:05 +02001210 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001211
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001212 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001213 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001214
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001215 lst = PyList_New(0);
1216 if (lst == NULL)
1217 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001218
1219 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1220 DIST_POINT *dp;
1221 STACK_OF(GENERAL_NAME) *gns;
1222
1223 dp = sk_DIST_POINT_value(dps, i);
1224 gns = dp->distpoint->name.fullname;
1225
1226 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1227 GENERAL_NAME *gn;
1228 ASN1_IA5STRING *uri;
1229 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001230 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001231
1232 gn = sk_GENERAL_NAME_value(gns, j);
1233 if (gn->type != GEN_URI) {
1234 continue;
1235 }
1236 uri = gn->d.uniformResourceIdentifier;
1237 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1238 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001239 if (ouri == NULL)
1240 goto done;
1241
1242 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001243 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001244 if (err < 0)
1245 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001246 }
1247 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001248
1249 /* Convert to tuple. */
1250 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1251
1252 done:
1253 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001254 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001255 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001256}
1257
1258static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001259_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001261 PyObject *retval = NULL;
1262 BIO *biobuf = NULL;
1263 PyObject *peer;
1264 PyObject *peer_alt_names = NULL;
1265 PyObject *issuer;
1266 PyObject *version;
1267 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001268 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 ASN1_INTEGER *serialNumber;
1270 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001271 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 ASN1_TIME *notBefore, *notAfter;
1273 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001274
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001275 retval = PyDict_New();
1276 if (retval == NULL)
1277 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001278
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001279 peer = _create_tuple_for_X509_NAME(
1280 X509_get_subject_name(certificate));
1281 if (peer == NULL)
1282 goto fail0;
1283 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1284 Py_DECREF(peer);
1285 goto fail0;
1286 }
1287 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001288
Antoine Pitroufb046912010-11-09 20:21:19 +00001289 issuer = _create_tuple_for_X509_NAME(
1290 X509_get_issuer_name(certificate));
1291 if (issuer == NULL)
1292 goto fail0;
1293 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001294 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001295 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001296 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001297 Py_DECREF(issuer);
1298
1299 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001300 if (version == NULL)
1301 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001302 if (PyDict_SetItemString(retval, "version", version) < 0) {
1303 Py_DECREF(version);
1304 goto fail0;
1305 }
1306 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001307
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001308 /* get a memory buffer */
1309 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001310
Antoine Pitroufb046912010-11-09 20:21:19 +00001311 (void) BIO_reset(biobuf);
1312 serialNumber = X509_get_serialNumber(certificate);
1313 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1314 i2a_ASN1_INTEGER(biobuf, serialNumber);
1315 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1316 if (len < 0) {
1317 _setSSLError(NULL, 0, __FILE__, __LINE__);
1318 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001319 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001320 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1321 if (sn_obj == NULL)
1322 goto fail1;
1323 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1324 Py_DECREF(sn_obj);
1325 goto fail1;
1326 }
1327 Py_DECREF(sn_obj);
1328
1329 (void) BIO_reset(biobuf);
1330 notBefore = X509_get_notBefore(certificate);
1331 ASN1_TIME_print(biobuf, notBefore);
1332 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1333 if (len < 0) {
1334 _setSSLError(NULL, 0, __FILE__, __LINE__);
1335 goto fail1;
1336 }
1337 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1338 if (pnotBefore == NULL)
1339 goto fail1;
1340 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1341 Py_DECREF(pnotBefore);
1342 goto fail1;
1343 }
1344 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001345
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001346 (void) BIO_reset(biobuf);
1347 notAfter = X509_get_notAfter(certificate);
1348 ASN1_TIME_print(biobuf, notAfter);
1349 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1350 if (len < 0) {
1351 _setSSLError(NULL, 0, __FILE__, __LINE__);
1352 goto fail1;
1353 }
1354 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1355 if (pnotAfter == NULL)
1356 goto fail1;
1357 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1358 Py_DECREF(pnotAfter);
1359 goto fail1;
1360 }
1361 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001362
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001363 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001364
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001365 peer_alt_names = _get_peer_alt_names(certificate);
1366 if (peer_alt_names == NULL)
1367 goto fail1;
1368 else if (peer_alt_names != Py_None) {
1369 if (PyDict_SetItemString(retval, "subjectAltName",
1370 peer_alt_names) < 0) {
1371 Py_DECREF(peer_alt_names);
1372 goto fail1;
1373 }
1374 Py_DECREF(peer_alt_names);
1375 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001376
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001377 /* Authority Information Access: OCSP URIs */
1378 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1379 if (obj == NULL) {
1380 goto fail1;
1381 } else if (obj != Py_None) {
1382 result = PyDict_SetItemString(retval, "OCSP", obj);
1383 Py_DECREF(obj);
1384 if (result < 0) {
1385 goto fail1;
1386 }
1387 }
1388
1389 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1390 if (obj == NULL) {
1391 goto fail1;
1392 } else if (obj != Py_None) {
1393 result = PyDict_SetItemString(retval, "caIssuers", obj);
1394 Py_DECREF(obj);
1395 if (result < 0) {
1396 goto fail1;
1397 }
1398 }
1399
1400 /* CDP (CRL distribution points) */
1401 obj = _get_crl_dp(certificate);
1402 if (obj == NULL) {
1403 goto fail1;
1404 } else if (obj != Py_None) {
1405 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1406 Py_DECREF(obj);
1407 if (result < 0) {
1408 goto fail1;
1409 }
1410 }
1411
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001412 BIO_free(biobuf);
1413 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001414
1415 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 if (biobuf != NULL)
1417 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001418 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001419 Py_XDECREF(retval);
1420 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001421}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001422
Christian Heimes9a5395a2013-06-17 15:44:12 +02001423static PyObject *
1424_certificate_to_der(X509 *certificate)
1425{
1426 unsigned char *bytes_buf = NULL;
1427 int len;
1428 PyObject *retval;
1429
1430 bytes_buf = NULL;
1431 len = i2d_X509(certificate, &bytes_buf);
1432 if (len < 0) {
1433 _setSSLError(NULL, 0, __FILE__, __LINE__);
1434 return NULL;
1435 }
1436 /* this is actually an immutable bytes sequence */
1437 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1438 OPENSSL_free(bytes_buf);
1439 return retval;
1440}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001441
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001442/*[clinic input]
1443_ssl._test_decode_cert
1444 path: object(converter="PyUnicode_FSConverter")
1445 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001446
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001447[clinic start generated code]*/
1448
1449static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001450_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1451/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001452{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001453 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001454 X509 *x=NULL;
1455 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001456
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001457 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1458 PyErr_SetString(PySSLErrorObject,
1459 "Can't malloc memory to read file");
1460 goto fail0;
1461 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001462
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001463 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 PyErr_SetString(PySSLErrorObject,
1465 "Can't open file");
1466 goto fail0;
1467 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1470 if (x == NULL) {
1471 PyErr_SetString(PySSLErrorObject,
1472 "Error decoding PEM-encoded file");
1473 goto fail0;
1474 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475
Antoine Pitroufb046912010-11-09 20:21:19 +00001476 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001477 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001478
1479 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001480 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001481 if (cert != NULL) BIO_free(cert);
1482 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001483}
1484
1485
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001486/*[clinic input]
1487_ssl._SSLSocket.peer_certificate
1488 der as binary_mode: bool = False
1489 /
1490
1491Returns the certificate for the peer.
1492
1493If no certificate was provided, returns None. If a certificate was
1494provided, but not validated, returns an empty dictionary. Otherwise
1495returns a dict containing information about the peer certificate.
1496
1497If the optional argument is True, returns a DER-encoded copy of the
1498peer certificate, or None if no certificate was provided. This will
1499return the certificate even if it wasn't validated.
1500[clinic start generated code]*/
1501
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001502static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001503_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1504/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001505{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001506 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001507 X509 *peer_cert;
1508 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001509
Christian Heimes66dc33b2017-05-23 16:02:02 -07001510 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001511 PyErr_SetString(PyExc_ValueError,
1512 "handshake not done yet");
1513 return NULL;
1514 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001515 peer_cert = SSL_get_peer_certificate(self->ssl);
1516 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001518
Antoine Pitrou721738f2012-08-15 23:20:39 +02001519 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001520 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001521 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001523 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001524 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001525 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001526 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001527 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001528 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001529 X509_free(peer_cert);
1530 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001531}
1532
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001533static PyObject *
1534cipher_to_tuple(const SSL_CIPHER *cipher)
1535{
1536 const char *cipher_name, *cipher_protocol;
1537 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001538 if (retval == NULL)
1539 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001541 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001542 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001543 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001544 PyTuple_SET_ITEM(retval, 0, Py_None);
1545 } else {
1546 v = PyUnicode_FromString(cipher_name);
1547 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001548 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001549 PyTuple_SET_ITEM(retval, 0, v);
1550 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001551
1552 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001554 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001555 PyTuple_SET_ITEM(retval, 1, Py_None);
1556 } else {
1557 v = PyUnicode_FromString(cipher_protocol);
1558 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001559 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560 PyTuple_SET_ITEM(retval, 1, v);
1561 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001562
1563 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001564 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001565 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001566 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001569
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001570 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001571 Py_DECREF(retval);
1572 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001573}
1574
Christian Heimes25bfcd52016-09-06 00:04:45 +02001575#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1576static PyObject *
1577cipher_to_dict(const SSL_CIPHER *cipher)
1578{
1579 const char *cipher_name, *cipher_protocol;
1580
1581 unsigned long cipher_id;
1582 int alg_bits, strength_bits, len;
1583 char buf[512] = {0};
1584#if OPENSSL_VERSION_1_1
1585 int aead, nid;
1586 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1587#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001588
1589 /* can be NULL */
1590 cipher_name = SSL_CIPHER_get_name(cipher);
1591 cipher_protocol = SSL_CIPHER_get_version(cipher);
1592 cipher_id = SSL_CIPHER_get_id(cipher);
1593 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001594 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1595 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001596 if (len > 1 && buf[len-1] == '\n')
1597 buf[len-1] = '\0';
1598 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1599
1600#if OPENSSL_VERSION_1_1
1601 aead = SSL_CIPHER_is_aead(cipher);
1602 nid = SSL_CIPHER_get_cipher_nid(cipher);
1603 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1604 nid = SSL_CIPHER_get_digest_nid(cipher);
1605 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1606 nid = SSL_CIPHER_get_kx_nid(cipher);
1607 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1608 nid = SSL_CIPHER_get_auth_nid(cipher);
1609 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1610#endif
1611
Victor Stinner410b9882016-09-12 12:00:23 +02001612 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001613 "{sksssssssisi"
1614#if OPENSSL_VERSION_1_1
1615 "sOssssssss"
1616#endif
1617 "}",
1618 "id", cipher_id,
1619 "name", cipher_name,
1620 "protocol", cipher_protocol,
1621 "description", buf,
1622 "strength_bits", strength_bits,
1623 "alg_bits", alg_bits
1624#if OPENSSL_VERSION_1_1
1625 ,"aead", aead ? Py_True : Py_False,
1626 "symmetric", skcipher,
1627 "digest", digest,
1628 "kea", kx,
1629 "auth", auth
1630#endif
1631 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001632}
1633#endif
1634
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001635/*[clinic input]
1636_ssl._SSLSocket.shared_ciphers
1637[clinic start generated code]*/
1638
1639static PyObject *
1640_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1641/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001642{
1643 STACK_OF(SSL_CIPHER) *ciphers;
1644 int i;
1645 PyObject *res;
1646
Christian Heimes598894f2016-09-05 23:19:05 +02001647 ciphers = SSL_get_ciphers(self->ssl);
1648 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001649 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001650 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1651 if (!res)
1652 return NULL;
1653 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1654 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1655 if (!tup) {
1656 Py_DECREF(res);
1657 return NULL;
1658 }
1659 PyList_SET_ITEM(res, i, tup);
1660 }
1661 return res;
1662}
1663
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001664/*[clinic input]
1665_ssl._SSLSocket.cipher
1666[clinic start generated code]*/
1667
1668static PyObject *
1669_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1670/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001671{
1672 const SSL_CIPHER *current;
1673
1674 if (self->ssl == NULL)
1675 Py_RETURN_NONE;
1676 current = SSL_get_current_cipher(self->ssl);
1677 if (current == NULL)
1678 Py_RETURN_NONE;
1679 return cipher_to_tuple(current);
1680}
1681
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001682/*[clinic input]
1683_ssl._SSLSocket.version
1684[clinic start generated code]*/
1685
1686static PyObject *
1687_ssl__SSLSocket_version_impl(PySSLSocket *self)
1688/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001689{
1690 const char *version;
1691
1692 if (self->ssl == NULL)
1693 Py_RETURN_NONE;
1694 version = SSL_get_version(self->ssl);
1695 if (!strcmp(version, "unknown"))
1696 Py_RETURN_NONE;
1697 return PyUnicode_FromString(version);
1698}
1699
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001700#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001701/*[clinic input]
1702_ssl._SSLSocket.selected_npn_protocol
1703[clinic start generated code]*/
1704
1705static PyObject *
1706_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1707/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1708{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001709 const unsigned char *out;
1710 unsigned int outlen;
1711
Victor Stinner4569cd52013-06-23 14:58:43 +02001712 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001713 &out, &outlen);
1714
1715 if (out == NULL)
1716 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001717 return PyUnicode_FromStringAndSize((char *)out, outlen);
1718}
1719#endif
1720
1721#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001722/*[clinic input]
1723_ssl._SSLSocket.selected_alpn_protocol
1724[clinic start generated code]*/
1725
1726static PyObject *
1727_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1728/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1729{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001730 const unsigned char *out;
1731 unsigned int outlen;
1732
1733 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1734
1735 if (out == NULL)
1736 Py_RETURN_NONE;
1737 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001738}
1739#endif
1740
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001741/*[clinic input]
1742_ssl._SSLSocket.compression
1743[clinic start generated code]*/
1744
1745static PyObject *
1746_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1747/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1748{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001749#ifdef OPENSSL_NO_COMP
1750 Py_RETURN_NONE;
1751#else
1752 const COMP_METHOD *comp_method;
1753 const char *short_name;
1754
1755 if (self->ssl == NULL)
1756 Py_RETURN_NONE;
1757 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001758 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001759 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001760 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001761 if (short_name == NULL)
1762 Py_RETURN_NONE;
1763 return PyUnicode_DecodeFSDefault(short_name);
1764#endif
1765}
1766
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001767static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1768 Py_INCREF(self->ctx);
1769 return self->ctx;
1770}
1771
1772static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1773 void *closure) {
1774
1775 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001776#if !HAVE_SNI
1777 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1778 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001779 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001780#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001781 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001782 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001783 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001784#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001785 } else {
1786 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1787 return -1;
1788 }
1789
1790 return 0;
1791}
1792
1793PyDoc_STRVAR(PySSL_set_context_doc,
1794"_setter_context(ctx)\n\
1795\
1796This changes the context associated with the SSLSocket. This is typically\n\
1797used from within a callback function set by the set_servername_callback\n\
1798on the SSLContext to change the certificate information associated with the\n\
1799SSLSocket before the cryptographic exchange handshake messages\n");
1800
1801
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001802static PyObject *
1803PySSL_get_server_side(PySSLSocket *self, void *c)
1804{
1805 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1806}
1807
1808PyDoc_STRVAR(PySSL_get_server_side_doc,
1809"Whether this is a server-side socket.");
1810
1811static PyObject *
1812PySSL_get_server_hostname(PySSLSocket *self, void *c)
1813{
1814 if (self->server_hostname == NULL)
1815 Py_RETURN_NONE;
1816 Py_INCREF(self->server_hostname);
1817 return self->server_hostname;
1818}
1819
1820PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1821"The currently set server hostname (for SNI).");
1822
1823static PyObject *
1824PySSL_get_owner(PySSLSocket *self, void *c)
1825{
1826 PyObject *owner;
1827
1828 if (self->owner == NULL)
1829 Py_RETURN_NONE;
1830
1831 owner = PyWeakref_GetObject(self->owner);
1832 Py_INCREF(owner);
1833 return owner;
1834}
1835
1836static int
1837PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1838{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001839 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001840 if (self->owner == NULL)
1841 return -1;
1842 return 0;
1843}
1844
1845PyDoc_STRVAR(PySSL_get_owner_doc,
1846"The Python-level owner of this object.\
1847Passed as \"self\" in servername callback.");
1848
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001849
Antoine Pitrou152efa22010-05-16 18:19:27 +00001850static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001851{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001852 if (self->ssl)
1853 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001854 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001855 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001856 Py_XDECREF(self->server_hostname);
1857 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001858 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001859}
1860
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001861/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001862 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001863 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001864 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001865
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001866static int
Victor Stinner14690702015-04-06 22:46:13 +02001867PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001868{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001869 int rc;
1870#ifdef HAVE_POLL
1871 struct pollfd pollfd;
1872 _PyTime_t ms;
1873#else
1874 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001875 fd_set fds;
1876 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001877#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001878
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001879 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001880 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001881 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001882 else if (timeout < 0) {
1883 if (s->sock_timeout > 0)
1884 return SOCKET_HAS_TIMED_OUT;
1885 else
1886 return SOCKET_IS_BLOCKING;
1887 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001888
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001889 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001890 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001891 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001892
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001893 /* Prefer poll, if available, since you can poll() any fd
1894 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001895#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001896 pollfd.fd = s->sock_fd;
1897 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001898
Victor Stinner14690702015-04-06 22:46:13 +02001899 /* timeout is in seconds, poll() uses milliseconds */
1900 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001901 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001902
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001903 PySSL_BEGIN_ALLOW_THREADS
1904 rc = poll(&pollfd, 1, (int)ms);
1905 PySSL_END_ALLOW_THREADS
1906#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001907 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001908 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001909 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001910
Victor Stinner14690702015-04-06 22:46:13 +02001911 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001912
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001913 FD_ZERO(&fds);
1914 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001915
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001916 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001917 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001918 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001919 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001920 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001921 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001922 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001923 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001924#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001925
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001926 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1927 (when we are able to write or when there's something to read) */
1928 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001929}
1930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001931/*[clinic input]
1932_ssl._SSLSocket.write
1933 b: Py_buffer
1934 /
1935
1936Writes the bytes-like object b into the SSL object.
1937
1938Returns the number of bytes written.
1939[clinic start generated code]*/
1940
1941static PyObject *
1942_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1943/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001944{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001945 int len;
1946 int sockstate;
1947 int err;
1948 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001949 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001950 _PyTime_t timeout, deadline = 0;
1951 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001952
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001953 if (sock != NULL) {
1954 if (((PyObject*)sock) == Py_None) {
1955 _setSSLError("Underlying socket connection gone",
1956 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1957 return NULL;
1958 }
1959 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001960 }
1961
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001962 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001963 PyErr_Format(PyExc_OverflowError,
1964 "string longer than %d bytes", INT_MAX);
1965 goto error;
1966 }
1967
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001968 if (sock != NULL) {
1969 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001970 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001971 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1972 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1973 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001974
Victor Stinner14690702015-04-06 22:46:13 +02001975 timeout = GET_SOCKET_TIMEOUT(sock);
1976 has_timeout = (timeout > 0);
1977 if (has_timeout)
1978 deadline = _PyTime_GetMonotonicClock() + timeout;
1979
1980 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001981 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001982 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001983 "The write operation timed out");
1984 goto error;
1985 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1986 PyErr_SetString(PySSLErrorObject,
1987 "Underlying socket has been closed.");
1988 goto error;
1989 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1990 PyErr_SetString(PySSLErrorObject,
1991 "Underlying socket too large for select().");
1992 goto error;
1993 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001994
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001995 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001997 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001998 err = SSL_get_error(self->ssl, len);
1999 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002000
2001 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002002 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002003
Victor Stinner14690702015-04-06 22:46:13 +02002004 if (has_timeout)
2005 timeout = deadline - _PyTime_GetMonotonicClock();
2006
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002007 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002008 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002009 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002010 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002011 } else {
2012 sockstate = SOCKET_OPERATION_OK;
2013 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002014
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002015 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002016 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002017 "The write operation timed out");
2018 goto error;
2019 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2020 PyErr_SetString(PySSLErrorObject,
2021 "Underlying socket has been closed.");
2022 goto error;
2023 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2024 break;
2025 }
2026 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002027
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002028 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 if (len > 0)
2030 return PyLong_FromLong(len);
2031 else
2032 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002033
2034error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002035 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002036 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002037}
2038
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002039/*[clinic input]
2040_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002041
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002042Returns the number of already decrypted bytes available for read, pending on the connection.
2043[clinic start generated code]*/
2044
2045static PyObject *
2046_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2047/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002048{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002049 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002050
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002051 PySSL_BEGIN_ALLOW_THREADS
2052 count = SSL_pending(self->ssl);
2053 PySSL_END_ALLOW_THREADS
2054 if (count < 0)
2055 return PySSL_SetError(self, count, __FILE__, __LINE__);
2056 else
2057 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002058}
2059
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002060/*[clinic input]
2061_ssl._SSLSocket.read
2062 size as len: int
2063 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002064 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002065 ]
2066 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002067
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002068Read up to size bytes from the SSL socket.
2069[clinic start generated code]*/
2070
2071static PyObject *
2072_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2073 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002074/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002075{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002076 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002078 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002079 int sockstate;
2080 int err;
2081 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002082 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002083 _PyTime_t timeout, deadline = 0;
2084 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002085
Martin Panter5503d472016-03-27 05:35:19 +00002086 if (!group_right_1 && len < 0) {
2087 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2088 return NULL;
2089 }
2090
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002091 if (sock != NULL) {
2092 if (((PyObject*)sock) == Py_None) {
2093 _setSSLError("Underlying socket connection gone",
2094 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2095 return NULL;
2096 }
2097 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 }
2099
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002100 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002101 dest = PyBytes_FromStringAndSize(NULL, len);
2102 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002103 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002104 if (len == 0) {
2105 Py_XDECREF(sock);
2106 return dest;
2107 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002108 mem = PyBytes_AS_STRING(dest);
2109 }
2110 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002111 mem = buffer->buf;
2112 if (len <= 0 || len > buffer->len) {
2113 len = (int) buffer->len;
2114 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002115 PyErr_SetString(PyExc_OverflowError,
2116 "maximum length can't fit in a C 'int'");
2117 goto error;
2118 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002119 if (len == 0) {
2120 count = 0;
2121 goto done;
2122 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002123 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002124 }
2125
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002126 if (sock != NULL) {
2127 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002128 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002129 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2130 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2131 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002132
Victor Stinner14690702015-04-06 22:46:13 +02002133 timeout = GET_SOCKET_TIMEOUT(sock);
2134 has_timeout = (timeout > 0);
2135 if (has_timeout)
2136 deadline = _PyTime_GetMonotonicClock() + timeout;
2137
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002138 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 PySSL_BEGIN_ALLOW_THREADS
2140 count = SSL_read(self->ssl, mem, len);
2141 err = SSL_get_error(self->ssl, count);
2142 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002143
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002144 if (PyErr_CheckSignals())
2145 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002146
Victor Stinner14690702015-04-06 22:46:13 +02002147 if (has_timeout)
2148 timeout = deadline - _PyTime_GetMonotonicClock();
2149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002150 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002151 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002152 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002153 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002154 } else if (err == SSL_ERROR_ZERO_RETURN &&
2155 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002156 {
2157 count = 0;
2158 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002159 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002160 else
2161 sockstate = SOCKET_OPERATION_OK;
2162
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002163 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002164 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 "The read operation timed out");
2166 goto error;
2167 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2168 break;
2169 }
2170 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002172 if (count <= 0) {
2173 PySSL_SetError(self, count, __FILE__, __LINE__);
2174 goto error;
2175 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002176
2177done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002178 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002179 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002180 _PyBytes_Resize(&dest, count);
2181 return dest;
2182 }
2183 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 return PyLong_FromLong(count);
2185 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002186
2187error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002188 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002189 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002190 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002191 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002192}
2193
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002194/*[clinic input]
2195_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002196
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002197Does the SSL shutdown handshake with the remote end.
2198
2199Returns the underlying socket object.
2200[clinic start generated code]*/
2201
2202static PyObject *
2203_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2204/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002205{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002206 int err, ssl_err, sockstate, nonblocking;
2207 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002208 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002209 _PyTime_t timeout, deadline = 0;
2210 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002211
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002212 if (sock != NULL) {
2213 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002214 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002215 _setSSLError("Underlying socket connection gone",
2216 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2217 return NULL;
2218 }
2219 Py_INCREF(sock);
2220
2221 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002222 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002223 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2224 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002225 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226
Victor Stinner14690702015-04-06 22:46:13 +02002227 timeout = GET_SOCKET_TIMEOUT(sock);
2228 has_timeout = (timeout > 0);
2229 if (has_timeout)
2230 deadline = _PyTime_GetMonotonicClock() + timeout;
2231
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002232 while (1) {
2233 PySSL_BEGIN_ALLOW_THREADS
2234 /* Disable read-ahead so that unwrap can work correctly.
2235 * Otherwise OpenSSL might read in too much data,
2236 * eating clear text data that happens to be
2237 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002238 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002239 * function is used and the shutdown_seen_zero != 0
2240 * condition is met.
2241 */
2242 if (self->shutdown_seen_zero)
2243 SSL_set_read_ahead(self->ssl, 0);
2244 err = SSL_shutdown(self->ssl);
2245 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002246
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2248 if (err > 0)
2249 break;
2250 if (err == 0) {
2251 /* Don't loop endlessly; instead preserve legacy
2252 behaviour of trying SSL_shutdown() only twice.
2253 This looks necessary for OpenSSL < 0.9.8m */
2254 if (++zeros > 1)
2255 break;
2256 /* Shutdown was sent, now try receiving */
2257 self->shutdown_seen_zero = 1;
2258 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002259 }
2260
Victor Stinner14690702015-04-06 22:46:13 +02002261 if (has_timeout)
2262 timeout = deadline - _PyTime_GetMonotonicClock();
2263
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002264 /* Possibly retry shutdown until timeout or failure */
2265 ssl_err = SSL_get_error(self->ssl, err);
2266 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002267 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002268 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002269 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002270 else
2271 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002272
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002273 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2274 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002275 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 "The read operation timed out");
2277 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002278 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002279 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002280 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002281 }
2282 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2283 PyErr_SetString(PySSLErrorObject,
2284 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002285 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002286 }
2287 else if (sockstate != SOCKET_OPERATION_OK)
2288 /* Retain the SSL error code */
2289 break;
2290 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002291
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002292 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002293 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002294 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002296 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002297 /* It's already INCREF'ed */
2298 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002299 else
2300 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002301
2302error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002303 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002304 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002305}
2306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002307/*[clinic input]
2308_ssl._SSLSocket.tls_unique_cb
2309
2310Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2311
2312If the TLS handshake is not yet complete, None is returned.
2313[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002314
Antoine Pitroud6494802011-07-21 01:11:30 +02002315static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002316_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2317/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002318{
2319 PyObject *retval = NULL;
2320 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002321 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002322
2323 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2324 /* if session is resumed XOR we are the client */
2325 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2326 }
2327 else {
2328 /* if a new session XOR we are the server */
2329 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2330 }
2331
2332 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002333 if (len == 0)
2334 Py_RETURN_NONE;
2335
2336 retval = PyBytes_FromStringAndSize(buf, len);
2337
2338 return retval;
2339}
2340
Christian Heimes99a65702016-09-10 23:44:53 +02002341#ifdef OPENSSL_VERSION_1_1
2342
2343static SSL_SESSION*
2344_ssl_session_dup(SSL_SESSION *session) {
2345 SSL_SESSION *newsession = NULL;
2346 int slen;
2347 unsigned char *senc = NULL, *p;
2348 const unsigned char *const_p;
2349
2350 if (session == NULL) {
2351 PyErr_SetString(PyExc_ValueError, "Invalid session");
2352 goto error;
2353 }
2354
2355 /* get length */
2356 slen = i2d_SSL_SESSION(session, NULL);
2357 if (slen == 0 || slen > 0xFF00) {
2358 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2359 goto error;
2360 }
2361 if ((senc = PyMem_Malloc(slen)) == NULL) {
2362 PyErr_NoMemory();
2363 goto error;
2364 }
2365 p = senc;
2366 if (!i2d_SSL_SESSION(session, &p)) {
2367 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2368 goto error;
2369 }
2370 const_p = senc;
2371 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2372 if (session == NULL) {
2373 goto error;
2374 }
2375 PyMem_Free(senc);
2376 return newsession;
2377 error:
2378 if (senc != NULL) {
2379 PyMem_Free(senc);
2380 }
2381 return NULL;
2382}
2383#endif
2384
2385static PyObject *
2386PySSL_get_session(PySSLSocket *self, void *closure) {
2387 /* get_session can return sessions from a server-side connection,
2388 * it does not check for handshake done or client socket. */
2389 PySSLSession *pysess;
2390 SSL_SESSION *session;
2391
2392#ifdef OPENSSL_VERSION_1_1
2393 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2394 * https://github.com/openssl/openssl/issues/1550 */
2395 session = SSL_get0_session(self->ssl); /* borrowed reference */
2396 if (session == NULL) {
2397 Py_RETURN_NONE;
2398 }
2399 if ((session = _ssl_session_dup(session)) == NULL) {
2400 return NULL;
2401 }
2402#else
2403 session = SSL_get1_session(self->ssl);
2404 if (session == NULL) {
2405 Py_RETURN_NONE;
2406 }
2407#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002408 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002409 if (pysess == NULL) {
2410 SSL_SESSION_free(session);
2411 return NULL;
2412 }
2413
2414 assert(self->ctx);
2415 pysess->ctx = self->ctx;
2416 Py_INCREF(pysess->ctx);
2417 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002418 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002419 return (PyObject *)pysess;
2420}
2421
2422static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2423 void *closure)
2424 {
2425 PySSLSession *pysess;
2426#ifdef OPENSSL_VERSION_1_1
2427 SSL_SESSION *session;
2428#endif
2429 int result;
2430
2431 if (!PySSLSession_Check(value)) {
2432 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2433 return -1;
2434 }
2435 pysess = (PySSLSession *)value;
2436
2437 if (self->ctx->ctx != pysess->ctx->ctx) {
2438 PyErr_SetString(PyExc_ValueError,
2439 "Session refers to a different SSLContext.");
2440 return -1;
2441 }
2442 if (self->socket_type != PY_SSL_CLIENT) {
2443 PyErr_SetString(PyExc_ValueError,
2444 "Cannot set session for server-side SSLSocket.");
2445 return -1;
2446 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002447 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002448 PyErr_SetString(PyExc_ValueError,
2449 "Cannot set session after handshake.");
2450 return -1;
2451 }
2452#ifdef OPENSSL_VERSION_1_1
2453 /* duplicate session */
2454 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2455 return -1;
2456 }
2457 result = SSL_set_session(self->ssl, session);
2458 /* free duplicate, SSL_set_session() bumps ref count */
2459 SSL_SESSION_free(session);
2460#else
2461 result = SSL_set_session(self->ssl, pysess->session);
2462#endif
2463 if (result == 0) {
2464 _setSSLError(NULL, 0, __FILE__, __LINE__);
2465 return -1;
2466 }
2467 return 0;
2468}
2469
2470PyDoc_STRVAR(PySSL_set_session_doc,
2471"_setter_session(session)\n\
2472\
2473Get / set SSLSession.");
2474
2475static PyObject *
2476PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2477 if (SSL_session_reused(self->ssl)) {
2478 Py_RETURN_TRUE;
2479 } else {
2480 Py_RETURN_FALSE;
2481 }
2482}
2483
2484PyDoc_STRVAR(PySSL_get_session_reused_doc,
2485"Was the client session reused during handshake?");
2486
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002487static PyGetSetDef ssl_getsetlist[] = {
2488 {"context", (getter) PySSL_get_context,
2489 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002490 {"server_side", (getter) PySSL_get_server_side, NULL,
2491 PySSL_get_server_side_doc},
2492 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2493 PySSL_get_server_hostname_doc},
2494 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2495 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002496 {"session", (getter) PySSL_get_session,
2497 (setter) PySSL_set_session, PySSL_set_session_doc},
2498 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2499 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002500 {NULL}, /* sentinel */
2501};
2502
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002503static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002504 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2505 _SSL__SSLSOCKET_WRITE_METHODDEF
2506 _SSL__SSLSOCKET_READ_METHODDEF
2507 _SSL__SSLSOCKET_PENDING_METHODDEF
2508 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2509 _SSL__SSLSOCKET_CIPHER_METHODDEF
2510 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2511 _SSL__SSLSOCKET_VERSION_METHODDEF
2512 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2513 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2514 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2515 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2516 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002517 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002518};
2519
Antoine Pitrou152efa22010-05-16 18:19:27 +00002520static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002521 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002522 "_ssl._SSLSocket", /*tp_name*/
2523 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002524 0, /*tp_itemsize*/
2525 /* methods */
2526 (destructor)PySSL_dealloc, /*tp_dealloc*/
2527 0, /*tp_print*/
2528 0, /*tp_getattr*/
2529 0, /*tp_setattr*/
2530 0, /*tp_reserved*/
2531 0, /*tp_repr*/
2532 0, /*tp_as_number*/
2533 0, /*tp_as_sequence*/
2534 0, /*tp_as_mapping*/
2535 0, /*tp_hash*/
2536 0, /*tp_call*/
2537 0, /*tp_str*/
2538 0, /*tp_getattro*/
2539 0, /*tp_setattro*/
2540 0, /*tp_as_buffer*/
2541 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2542 0, /*tp_doc*/
2543 0, /*tp_traverse*/
2544 0, /*tp_clear*/
2545 0, /*tp_richcompare*/
2546 0, /*tp_weaklistoffset*/
2547 0, /*tp_iter*/
2548 0, /*tp_iternext*/
2549 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002550 0, /*tp_members*/
2551 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002552};
2553
Antoine Pitrou152efa22010-05-16 18:19:27 +00002554
2555/*
2556 * _SSLContext objects
2557 */
2558
Christian Heimes5fe668c2016-09-12 00:01:11 +02002559static int
2560_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2561{
2562 int mode;
2563 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2564
2565 switch(n) {
2566 case PY_SSL_CERT_NONE:
2567 mode = SSL_VERIFY_NONE;
2568 break;
2569 case PY_SSL_CERT_OPTIONAL:
2570 mode = SSL_VERIFY_PEER;
2571 break;
2572 case PY_SSL_CERT_REQUIRED:
2573 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2574 break;
2575 default:
2576 PyErr_SetString(PyExc_ValueError,
2577 "invalid value for verify_mode");
2578 return -1;
2579 }
2580 /* keep current verify cb */
2581 verify_cb = SSL_CTX_get_verify_callback(ctx);
2582 SSL_CTX_set_verify(ctx, mode, verify_cb);
2583 return 0;
2584}
2585
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002586/*[clinic input]
2587@classmethod
2588_ssl._SSLContext.__new__
2589 protocol as proto_version: int
2590 /
2591[clinic start generated code]*/
2592
Antoine Pitrou152efa22010-05-16 18:19:27 +00002593static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002594_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2595/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002596{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002597 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002598 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002599 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002600 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002601#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002602 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002603#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002604
Antoine Pitrou152efa22010-05-16 18:19:27 +00002605 PySSL_BEGIN_ALLOW_THREADS
2606 if (proto_version == PY_SSL_VERSION_TLS1)
2607 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002608#if HAVE_TLSv1_2
2609 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2610 ctx = SSL_CTX_new(TLSv1_1_method());
2611 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2612 ctx = SSL_CTX_new(TLSv1_2_method());
2613#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002614#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002615 else if (proto_version == PY_SSL_VERSION_SSL3)
2616 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002617#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002618#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002619 else if (proto_version == PY_SSL_VERSION_SSL2)
2620 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002621#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002622 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002623 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002624 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2625 ctx = SSL_CTX_new(TLS_client_method());
2626 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2627 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002628 else
2629 proto_version = -1;
2630 PySSL_END_ALLOW_THREADS
2631
2632 if (proto_version == -1) {
2633 PyErr_SetString(PyExc_ValueError,
2634 "invalid protocol version");
2635 return NULL;
2636 }
2637 if (ctx == NULL) {
2638 PyErr_SetString(PySSLErrorObject,
2639 "failed to allocate SSL context");
2640 return NULL;
2641 }
2642
2643 assert(type != NULL && type->tp_alloc != NULL);
2644 self = (PySSLContext *) type->tp_alloc(type, 0);
2645 if (self == NULL) {
2646 SSL_CTX_free(ctx);
2647 return NULL;
2648 }
2649 self->ctx = ctx;
Christian Heimes5cb31c92012-09-20 12:42:54 +02002650#ifdef OPENSSL_NPN_NEGOTIATED
2651 self->npn_protocols = NULL;
2652#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002653#ifdef HAVE_ALPN
2654 self->alpn_protocols = NULL;
2655#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002656#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002657 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002658#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002659 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002660 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2661 self->check_hostname = 1;
2662 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2663 Py_DECREF(self);
2664 return NULL;
2665 }
2666 } else {
2667 self->check_hostname = 0;
2668 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2669 Py_DECREF(self);
2670 return NULL;
2671 }
2672 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002673 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002674 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2675 if (proto_version != PY_SSL_VERSION_SSL2)
2676 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002677 if (proto_version != PY_SSL_VERSION_SSL3)
2678 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002679 /* Minimal security flags for server and client side context.
2680 * Client sockets ignore server-side parameters. */
2681#ifdef SSL_OP_NO_COMPRESSION
2682 options |= SSL_OP_NO_COMPRESSION;
2683#endif
2684#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2685 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2686#endif
2687#ifdef SSL_OP_SINGLE_DH_USE
2688 options |= SSL_OP_SINGLE_DH_USE;
2689#endif
2690#ifdef SSL_OP_SINGLE_ECDH_USE
2691 options |= SSL_OP_SINGLE_ECDH_USE;
2692#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002693 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002694
Christian Heimes358cfd42016-09-10 22:43:48 +02002695 /* A bare minimum cipher list without completly broken cipher suites.
2696 * It's far from perfect but gives users a better head start. */
2697 if (proto_version != PY_SSL_VERSION_SSL2) {
2698 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2699 } else {
2700 /* SSLv2 needs MD5 */
2701 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2702 }
2703 if (result == 0) {
2704 Py_DECREF(self);
2705 ERR_clear_error();
2706 PyErr_SetString(PySSLErrorObject,
2707 "No cipher can be selected.");
2708 return NULL;
2709 }
2710
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002711#if defined(SSL_MODE_RELEASE_BUFFERS)
2712 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2713 usage for no cost at all. However, don't do this for OpenSSL versions
2714 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2715 2014-0198. I can't find exactly which beta fixed this CVE, so be
2716 conservative and assume it wasn't fixed until release. We do this check
2717 at runtime to avoid problems from the dynamic linker.
2718 See #25672 for more on this. */
2719 libver = SSLeay();
2720 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2721 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2722 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2723 }
2724#endif
2725
2726
Donald Stufft8ae264c2017-03-02 11:45:29 -05002727#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002728 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2729 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002730 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2731 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002732#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002733 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2734#else
2735 {
2736 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2737 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2738 EC_KEY_free(key);
2739 }
2740#endif
2741#endif
2742
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002743#define SID_CTX "Python"
2744 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2745 sizeof(SID_CTX));
2746#undef SID_CTX
2747
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002748#ifdef X509_V_FLAG_TRUSTED_FIRST
2749 {
2750 /* Improve trust chain building when cross-signed intermediate
2751 certificates are present. See https://bugs.python.org/issue23476. */
2752 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2753 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2754 }
2755#endif
2756
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 return (PyObject *)self;
2758}
2759
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002760static int
2761context_traverse(PySSLContext *self, visitproc visit, void *arg)
2762{
2763#ifndef OPENSSL_NO_TLSEXT
2764 Py_VISIT(self->set_hostname);
2765#endif
2766 return 0;
2767}
2768
2769static int
2770context_clear(PySSLContext *self)
2771{
2772#ifndef OPENSSL_NO_TLSEXT
2773 Py_CLEAR(self->set_hostname);
2774#endif
2775 return 0;
2776}
2777
Antoine Pitrou152efa22010-05-16 18:19:27 +00002778static void
2779context_dealloc(PySSLContext *self)
2780{
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002781 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002782 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002783#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002784 PyMem_FREE(self->npn_protocols);
2785#endif
2786#ifdef HAVE_ALPN
2787 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002788#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002789 Py_TYPE(self)->tp_free(self);
2790}
2791
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002792/*[clinic input]
2793_ssl._SSLContext.set_ciphers
2794 cipherlist: str
2795 /
2796[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002797
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002798static PyObject *
2799_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2800/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2801{
2802 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002803 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002804 /* Clearing the error queue is necessary on some OpenSSL versions,
2805 otherwise the error will be reported again when another SSL call
2806 is done. */
2807 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002808 PyErr_SetString(PySSLErrorObject,
2809 "No cipher can be selected.");
2810 return NULL;
2811 }
2812 Py_RETURN_NONE;
2813}
2814
Christian Heimes25bfcd52016-09-06 00:04:45 +02002815#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2816/*[clinic input]
2817_ssl._SSLContext.get_ciphers
2818[clinic start generated code]*/
2819
2820static PyObject *
2821_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2822/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2823{
2824 SSL *ssl = NULL;
2825 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002826 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002827 int i=0;
2828 PyObject *result = NULL, *dct;
2829
2830 ssl = SSL_new(self->ctx);
2831 if (ssl == NULL) {
2832 _setSSLError(NULL, 0, __FILE__, __LINE__);
2833 goto exit;
2834 }
2835 sk = SSL_get_ciphers(ssl);
2836
2837 result = PyList_New(sk_SSL_CIPHER_num(sk));
2838 if (result == NULL) {
2839 goto exit;
2840 }
2841
2842 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2843 cipher = sk_SSL_CIPHER_value(sk, i);
2844 dct = cipher_to_dict(cipher);
2845 if (dct == NULL) {
2846 Py_CLEAR(result);
2847 goto exit;
2848 }
2849 PyList_SET_ITEM(result, i, dct);
2850 }
2851
2852 exit:
2853 if (ssl != NULL)
2854 SSL_free(ssl);
2855 return result;
2856
2857}
2858#endif
2859
2860
Benjamin Petersonc54de472015-01-28 12:06:39 -05002861#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002862static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002863do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2864 const unsigned char *server_protocols, unsigned int server_protocols_len,
2865 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002866{
Benjamin Peterson88615022015-01-23 17:30:26 -05002867 int ret;
2868 if (client_protocols == NULL) {
2869 client_protocols = (unsigned char *)"";
2870 client_protocols_len = 0;
2871 }
2872 if (server_protocols == NULL) {
2873 server_protocols = (unsigned char *)"";
2874 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002875 }
2876
Benjamin Peterson88615022015-01-23 17:30:26 -05002877 ret = SSL_select_next_proto(out, outlen,
2878 server_protocols, server_protocols_len,
2879 client_protocols, client_protocols_len);
2880 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2881 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002882
2883 return SSL_TLSEXT_ERR_OK;
2884}
2885
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002886/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2887static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002888_advertiseNPN_cb(SSL *s,
2889 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002890 void *args)
2891{
2892 PySSLContext *ssl_ctx = (PySSLContext *) args;
2893
2894 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002895 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002896 *len = 0;
2897 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002898 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002899 *len = ssl_ctx->npn_protocols_len;
2900 }
2901
2902 return SSL_TLSEXT_ERR_OK;
2903}
2904/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2905static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002906_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002907 unsigned char **out, unsigned char *outlen,
2908 const unsigned char *server, unsigned int server_len,
2909 void *args)
2910{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002911 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002912 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002913 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002914}
2915#endif
2916
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002917/*[clinic input]
2918_ssl._SSLContext._set_npn_protocols
2919 protos: Py_buffer
2920 /
2921[clinic start generated code]*/
2922
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002923static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002924_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2925 Py_buffer *protos)
2926/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002927{
2928#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002929 PyMem_Free(self->npn_protocols);
2930 self->npn_protocols = PyMem_Malloc(protos->len);
2931 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002932 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002933 memcpy(self->npn_protocols, protos->buf, protos->len);
2934 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002935
2936 /* set both server and client callbacks, because the context can
2937 * be used to create both types of sockets */
2938 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2939 _advertiseNPN_cb,
2940 self);
2941 SSL_CTX_set_next_proto_select_cb(self->ctx,
2942 _selectNPN_cb,
2943 self);
2944
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002945 Py_RETURN_NONE;
2946#else
2947 PyErr_SetString(PyExc_NotImplementedError,
2948 "The NPN extension requires OpenSSL 1.0.1 or later.");
2949 return NULL;
2950#endif
2951}
2952
Benjamin Petersoncca27322015-01-23 16:35:37 -05002953#ifdef HAVE_ALPN
2954static int
2955_selectALPN_cb(SSL *s,
2956 const unsigned char **out, unsigned char *outlen,
2957 const unsigned char *client_protocols, unsigned int client_protocols_len,
2958 void *args)
2959{
2960 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002961 return do_protocol_selection(1, (unsigned char **)out, outlen,
2962 ctx->alpn_protocols, ctx->alpn_protocols_len,
2963 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002964}
2965#endif
2966
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002967/*[clinic input]
2968_ssl._SSLContext._set_alpn_protocols
2969 protos: Py_buffer
2970 /
2971[clinic start generated code]*/
2972
Benjamin Petersoncca27322015-01-23 16:35:37 -05002973static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002974_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2975 Py_buffer *protos)
2976/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002977{
2978#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03002979 if (protos->len > UINT_MAX) {
2980 PyErr_Format(PyExc_OverflowError,
2981 "protocols longer than %d bytes", UINT_MAX);
2982 return NULL;
2983 }
2984
Benjamin Petersoncca27322015-01-23 16:35:37 -05002985 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002986 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002987 if (!self->alpn_protocols)
2988 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002989 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03002990 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002991
2992 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2993 return PyErr_NoMemory();
2994 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2995
Benjamin Petersoncca27322015-01-23 16:35:37 -05002996 Py_RETURN_NONE;
2997#else
2998 PyErr_SetString(PyExc_NotImplementedError,
2999 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3000 return NULL;
3001#endif
3002}
3003
Antoine Pitrou152efa22010-05-16 18:19:27 +00003004static PyObject *
3005get_verify_mode(PySSLContext *self, void *c)
3006{
3007 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3008 case SSL_VERIFY_NONE:
3009 return PyLong_FromLong(PY_SSL_CERT_NONE);
3010 case SSL_VERIFY_PEER:
3011 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3012 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3013 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3014 }
3015 PyErr_SetString(PySSLErrorObject,
3016 "invalid return value from SSL_CTX_get_verify_mode");
3017 return NULL;
3018}
3019
3020static int
3021set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3022{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003023 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003024 if (!PyArg_Parse(arg, "i", &n))
3025 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003026 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003027 PyErr_SetString(PyExc_ValueError,
3028 "Cannot set verify_mode to CERT_NONE when "
3029 "check_hostname is enabled.");
3030 return -1;
3031 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003032 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003033}
3034
3035static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003036get_verify_flags(PySSLContext *self, void *c)
3037{
3038 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003039 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003040 unsigned long flags;
3041
3042 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003043 param = X509_STORE_get0_param(store);
3044 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003045 return PyLong_FromUnsignedLong(flags);
3046}
3047
3048static int
3049set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3050{
3051 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003052 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003053 unsigned long new_flags, flags, set, clear;
3054
3055 if (!PyArg_Parse(arg, "k", &new_flags))
3056 return -1;
3057 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003058 param = X509_STORE_get0_param(store);
3059 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003060 clear = flags & ~new_flags;
3061 set = ~flags & new_flags;
3062 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003063 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003064 _setSSLError(NULL, 0, __FILE__, __LINE__);
3065 return -1;
3066 }
3067 }
3068 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003069 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003070 _setSSLError(NULL, 0, __FILE__, __LINE__);
3071 return -1;
3072 }
3073 }
3074 return 0;
3075}
3076
3077static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003078get_options(PySSLContext *self, void *c)
3079{
3080 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3081}
3082
3083static int
3084set_options(PySSLContext *self, PyObject *arg, void *c)
3085{
3086 long new_opts, opts, set, clear;
3087 if (!PyArg_Parse(arg, "l", &new_opts))
3088 return -1;
3089 opts = SSL_CTX_get_options(self->ctx);
3090 clear = opts & ~new_opts;
3091 set = ~opts & new_opts;
3092 if (clear) {
3093#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3094 SSL_CTX_clear_options(self->ctx, clear);
3095#else
3096 PyErr_SetString(PyExc_ValueError,
3097 "can't clear options before OpenSSL 0.9.8m");
3098 return -1;
3099#endif
3100 }
3101 if (set)
3102 SSL_CTX_set_options(self->ctx, set);
3103 return 0;
3104}
3105
Christian Heimes1aa9a752013-12-02 02:41:19 +01003106static PyObject *
3107get_check_hostname(PySSLContext *self, void *c)
3108{
3109 return PyBool_FromLong(self->check_hostname);
3110}
3111
3112static int
3113set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3114{
3115 int check_hostname;
3116 if (!PyArg_Parse(arg, "p", &check_hostname))
3117 return -1;
3118 if (check_hostname &&
3119 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3120 PyErr_SetString(PyExc_ValueError,
3121 "check_hostname needs a SSL context with either "
3122 "CERT_OPTIONAL or CERT_REQUIRED");
3123 return -1;
3124 }
3125 self->check_hostname = check_hostname;
3126 return 0;
3127}
3128
3129
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003130typedef struct {
3131 PyThreadState *thread_state;
3132 PyObject *callable;
3133 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003134 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003135 int error;
3136} _PySSLPasswordInfo;
3137
3138static int
3139_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3140 const char *bad_type_error)
3141{
3142 /* Set the password and size fields of a _PySSLPasswordInfo struct
3143 from a unicode, bytes, or byte array object.
3144 The password field will be dynamically allocated and must be freed
3145 by the caller */
3146 PyObject *password_bytes = NULL;
3147 const char *data = NULL;
3148 Py_ssize_t size;
3149
3150 if (PyUnicode_Check(password)) {
3151 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3152 if (!password_bytes) {
3153 goto error;
3154 }
3155 data = PyBytes_AS_STRING(password_bytes);
3156 size = PyBytes_GET_SIZE(password_bytes);
3157 } else if (PyBytes_Check(password)) {
3158 data = PyBytes_AS_STRING(password);
3159 size = PyBytes_GET_SIZE(password);
3160 } else if (PyByteArray_Check(password)) {
3161 data = PyByteArray_AS_STRING(password);
3162 size = PyByteArray_GET_SIZE(password);
3163 } else {
3164 PyErr_SetString(PyExc_TypeError, bad_type_error);
3165 goto error;
3166 }
3167
Victor Stinner9ee02032013-06-23 15:08:23 +02003168 if (size > (Py_ssize_t)INT_MAX) {
3169 PyErr_Format(PyExc_ValueError,
3170 "password cannot be longer than %d bytes", INT_MAX);
3171 goto error;
3172 }
3173
Victor Stinner11ebff22013-07-07 17:07:52 +02003174 PyMem_Free(pw_info->password);
3175 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003176 if (!pw_info->password) {
3177 PyErr_SetString(PyExc_MemoryError,
3178 "unable to allocate password buffer");
3179 goto error;
3180 }
3181 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003182 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003183
3184 Py_XDECREF(password_bytes);
3185 return 1;
3186
3187error:
3188 Py_XDECREF(password_bytes);
3189 return 0;
3190}
3191
3192static int
3193_password_callback(char *buf, int size, int rwflag, void *userdata)
3194{
3195 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3196 PyObject *fn_ret = NULL;
3197
3198 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3199
3200 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003201 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003202 if (!fn_ret) {
3203 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3204 core python API, so we could use it to add a frame here */
3205 goto error;
3206 }
3207
3208 if (!_pwinfo_set(pw_info, fn_ret,
3209 "password callback must return a string")) {
3210 goto error;
3211 }
3212 Py_CLEAR(fn_ret);
3213 }
3214
3215 if (pw_info->size > size) {
3216 PyErr_Format(PyExc_ValueError,
3217 "password cannot be longer than %d bytes", size);
3218 goto error;
3219 }
3220
3221 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3222 memcpy(buf, pw_info->password, pw_info->size);
3223 return pw_info->size;
3224
3225error:
3226 Py_XDECREF(fn_ret);
3227 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3228 pw_info->error = 1;
3229 return -1;
3230}
3231
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003232/*[clinic input]
3233_ssl._SSLContext.load_cert_chain
3234 certfile: object
3235 keyfile: object = NULL
3236 password: object = NULL
3237
3238[clinic start generated code]*/
3239
Antoine Pitroub5218772010-05-21 09:56:06 +00003240static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003241_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3242 PyObject *keyfile, PyObject *password)
3243/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003244{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003245 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003246 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3247 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003248 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003249 int r;
3250
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003251 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003252 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 if (keyfile == Py_None)
3254 keyfile = NULL;
3255 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3256 PyErr_SetString(PyExc_TypeError,
3257 "certfile should be a valid filesystem path");
3258 return NULL;
3259 }
3260 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3261 PyErr_SetString(PyExc_TypeError,
3262 "keyfile should be a valid filesystem path");
3263 goto error;
3264 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003265 if (password && password != Py_None) {
3266 if (PyCallable_Check(password)) {
3267 pw_info.callable = password;
3268 } else if (!_pwinfo_set(&pw_info, password,
3269 "password should be a string or callable")) {
3270 goto error;
3271 }
3272 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3273 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3274 }
3275 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003276 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3277 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003278 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003279 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003280 if (pw_info.error) {
3281 ERR_clear_error();
3282 /* the password callback has already set the error information */
3283 }
3284 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003285 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003286 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003287 }
3288 else {
3289 _setSSLError(NULL, 0, __FILE__, __LINE__);
3290 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003291 goto error;
3292 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003293 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003294 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003295 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3296 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003297 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3298 Py_CLEAR(keyfile_bytes);
3299 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003300 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003301 if (pw_info.error) {
3302 ERR_clear_error();
3303 /* the password callback has already set the error information */
3304 }
3305 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003306 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003307 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003308 }
3309 else {
3310 _setSSLError(NULL, 0, __FILE__, __LINE__);
3311 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003312 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003313 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003314 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003316 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 if (r != 1) {
3318 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003319 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003320 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003321 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3322 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003323 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003324 Py_RETURN_NONE;
3325
3326error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003327 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3328 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003329 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003330 Py_XDECREF(keyfile_bytes);
3331 Py_XDECREF(certfile_bytes);
3332 return NULL;
3333}
3334
Christian Heimesefff7062013-11-21 03:35:02 +01003335/* internal helper function, returns -1 on error
3336 */
3337static int
3338_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3339 int filetype)
3340{
3341 BIO *biobuf = NULL;
3342 X509_STORE *store;
3343 int retval = 0, err, loaded = 0;
3344
3345 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3346
3347 if (len <= 0) {
3348 PyErr_SetString(PyExc_ValueError,
3349 "Empty certificate data");
3350 return -1;
3351 } else if (len > INT_MAX) {
3352 PyErr_SetString(PyExc_OverflowError,
3353 "Certificate data is too long.");
3354 return -1;
3355 }
3356
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003357 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003358 if (biobuf == NULL) {
3359 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3360 return -1;
3361 }
3362
3363 store = SSL_CTX_get_cert_store(self->ctx);
3364 assert(store != NULL);
3365
3366 while (1) {
3367 X509 *cert = NULL;
3368 int r;
3369
3370 if (filetype == SSL_FILETYPE_ASN1) {
3371 cert = d2i_X509_bio(biobuf, NULL);
3372 } else {
3373 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003374 SSL_CTX_get_default_passwd_cb(self->ctx),
3375 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3376 );
Christian Heimesefff7062013-11-21 03:35:02 +01003377 }
3378 if (cert == NULL) {
3379 break;
3380 }
3381 r = X509_STORE_add_cert(store, cert);
3382 X509_free(cert);
3383 if (!r) {
3384 err = ERR_peek_last_error();
3385 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3386 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3387 /* cert already in hash table, not an error */
3388 ERR_clear_error();
3389 } else {
3390 break;
3391 }
3392 }
3393 loaded++;
3394 }
3395
3396 err = ERR_peek_last_error();
3397 if ((filetype == SSL_FILETYPE_ASN1) &&
3398 (loaded > 0) &&
3399 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3400 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3401 /* EOF ASN1 file, not an error */
3402 ERR_clear_error();
3403 retval = 0;
3404 } else if ((filetype == SSL_FILETYPE_PEM) &&
3405 (loaded > 0) &&
3406 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3407 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3408 /* EOF PEM file, not an error */
3409 ERR_clear_error();
3410 retval = 0;
3411 } else {
3412 _setSSLError(NULL, 0, __FILE__, __LINE__);
3413 retval = -1;
3414 }
3415
3416 BIO_free(biobuf);
3417 return retval;
3418}
3419
3420
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003421/*[clinic input]
3422_ssl._SSLContext.load_verify_locations
3423 cafile: object = NULL
3424 capath: object = NULL
3425 cadata: object = NULL
3426
3427[clinic start generated code]*/
3428
Antoine Pitrou152efa22010-05-16 18:19:27 +00003429static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003430_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3431 PyObject *cafile,
3432 PyObject *capath,
3433 PyObject *cadata)
3434/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003435{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003436 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3437 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003438 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003439
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003440 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003441 if (cafile == Py_None)
3442 cafile = NULL;
3443 if (capath == Py_None)
3444 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003445 if (cadata == Py_None)
3446 cadata = NULL;
3447
3448 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003449 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003450 "cafile, capath and cadata cannot be all omitted");
3451 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003452 }
3453 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3454 PyErr_SetString(PyExc_TypeError,
3455 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003456 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003457 }
3458 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003459 PyErr_SetString(PyExc_TypeError,
3460 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003461 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003462 }
Christian Heimesefff7062013-11-21 03:35:02 +01003463
3464 /* validata cadata type and load cadata */
3465 if (cadata) {
3466 Py_buffer buf;
3467 PyObject *cadata_ascii = NULL;
3468
3469 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3470 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3471 PyBuffer_Release(&buf);
3472 PyErr_SetString(PyExc_TypeError,
3473 "cadata should be a contiguous buffer with "
3474 "a single dimension");
3475 goto error;
3476 }
3477 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3478 PyBuffer_Release(&buf);
3479 if (r == -1) {
3480 goto error;
3481 }
3482 } else {
3483 PyErr_Clear();
3484 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3485 if (cadata_ascii == NULL) {
3486 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003487 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003488 "bytes-like object");
3489 goto error;
3490 }
3491 r = _add_ca_certs(self,
3492 PyBytes_AS_STRING(cadata_ascii),
3493 PyBytes_GET_SIZE(cadata_ascii),
3494 SSL_FILETYPE_PEM);
3495 Py_DECREF(cadata_ascii);
3496 if (r == -1) {
3497 goto error;
3498 }
3499 }
3500 }
3501
3502 /* load cafile or capath */
3503 if (cafile || capath) {
3504 if (cafile)
3505 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3506 if (capath)
3507 capath_buf = PyBytes_AS_STRING(capath_bytes);
3508 PySSL_BEGIN_ALLOW_THREADS
3509 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3510 PySSL_END_ALLOW_THREADS
3511 if (r != 1) {
3512 ok = 0;
3513 if (errno != 0) {
3514 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003515 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003516 }
3517 else {
3518 _setSSLError(NULL, 0, __FILE__, __LINE__);
3519 }
3520 goto error;
3521 }
3522 }
3523 goto end;
3524
3525 error:
3526 ok = 0;
3527 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003528 Py_XDECREF(cafile_bytes);
3529 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003530 if (ok) {
3531 Py_RETURN_NONE;
3532 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003533 return NULL;
3534 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003535}
3536
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003537/*[clinic input]
3538_ssl._SSLContext.load_dh_params
3539 path as filepath: object
3540 /
3541
3542[clinic start generated code]*/
3543
Antoine Pitrou152efa22010-05-16 18:19:27 +00003544static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003545_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3546/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003547{
3548 FILE *f;
3549 DH *dh;
3550
Victor Stinnerdaf45552013-08-28 00:53:59 +02003551 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003552 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003553 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003554
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003555 errno = 0;
3556 PySSL_BEGIN_ALLOW_THREADS
3557 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003558 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003559 PySSL_END_ALLOW_THREADS
3560 if (dh == NULL) {
3561 if (errno != 0) {
3562 ERR_clear_error();
3563 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3564 }
3565 else {
3566 _setSSLError(NULL, 0, __FILE__, __LINE__);
3567 }
3568 return NULL;
3569 }
3570 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3571 _setSSLError(NULL, 0, __FILE__, __LINE__);
3572 DH_free(dh);
3573 Py_RETURN_NONE;
3574}
3575
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003576/*[clinic input]
3577_ssl._SSLContext._wrap_socket
3578 sock: object(subclass_of="PySocketModule.Sock_Type")
3579 server_side: int
3580 server_hostname as hostname_obj: object = None
3581
3582[clinic start generated code]*/
3583
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003584static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003585_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3586 int server_side, PyObject *hostname_obj)
3587/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003588{
Antoine Pitroud5323212010-10-22 18:19:07 +00003589 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003590 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003591
Antoine Pitroud5323212010-10-22 18:19:07 +00003592 /* server_hostname is either None (or absent), or to be encoded
3593 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003594 if (hostname_obj != Py_None) {
3595 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003596 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003597 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003599 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3600 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003601 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003602 if (hostname != NULL)
3603 PyMem_Free(hostname);
3604 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003605}
3606
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003607/*[clinic input]
3608_ssl._SSLContext._wrap_bio
3609 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3610 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3611 server_side: int
3612 server_hostname as hostname_obj: object = None
3613
3614[clinic start generated code]*/
3615
Antoine Pitroub0182c82010-10-12 20:09:02 +00003616static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003617_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3618 PySSLMemoryBIO *outgoing, int server_side,
3619 PyObject *hostname_obj)
3620/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003621{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003622 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003623 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003624
3625 /* server_hostname is either None (or absent), or to be encoded
3626 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003627 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003628 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3629 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003630 }
3631
3632 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3633 incoming, outgoing);
3634
3635 PyMem_Free(hostname);
3636 return res;
3637}
3638
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003639/*[clinic input]
3640_ssl._SSLContext.session_stats
3641[clinic start generated code]*/
3642
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003643static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003644_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3645/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003646{
3647 int r;
3648 PyObject *value, *stats = PyDict_New();
3649 if (!stats)
3650 return NULL;
3651
3652#define ADD_STATS(SSL_NAME, KEY_NAME) \
3653 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3654 if (value == NULL) \
3655 goto error; \
3656 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3657 Py_DECREF(value); \
3658 if (r < 0) \
3659 goto error;
3660
3661 ADD_STATS(number, "number");
3662 ADD_STATS(connect, "connect");
3663 ADD_STATS(connect_good, "connect_good");
3664 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3665 ADD_STATS(accept, "accept");
3666 ADD_STATS(accept_good, "accept_good");
3667 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3668 ADD_STATS(accept, "accept");
3669 ADD_STATS(hits, "hits");
3670 ADD_STATS(misses, "misses");
3671 ADD_STATS(timeouts, "timeouts");
3672 ADD_STATS(cache_full, "cache_full");
3673
3674#undef ADD_STATS
3675
3676 return stats;
3677
3678error:
3679 Py_DECREF(stats);
3680 return NULL;
3681}
3682
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003683/*[clinic input]
3684_ssl._SSLContext.set_default_verify_paths
3685[clinic start generated code]*/
3686
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003687static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003688_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3689/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003690{
3691 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3692 _setSSLError(NULL, 0, __FILE__, __LINE__);
3693 return NULL;
3694 }
3695 Py_RETURN_NONE;
3696}
3697
Antoine Pitrou501da612011-12-21 09:27:41 +01003698#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003699/*[clinic input]
3700_ssl._SSLContext.set_ecdh_curve
3701 name: object
3702 /
3703
3704[clinic start generated code]*/
3705
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003706static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003707_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3708/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003709{
3710 PyObject *name_bytes;
3711 int nid;
3712 EC_KEY *key;
3713
3714 if (!PyUnicode_FSConverter(name, &name_bytes))
3715 return NULL;
3716 assert(PyBytes_Check(name_bytes));
3717 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3718 Py_DECREF(name_bytes);
3719 if (nid == 0) {
3720 PyErr_Format(PyExc_ValueError,
3721 "unknown elliptic curve name %R", name);
3722 return NULL;
3723 }
3724 key = EC_KEY_new_by_curve_name(nid);
3725 if (key == NULL) {
3726 _setSSLError(NULL, 0, __FILE__, __LINE__);
3727 return NULL;
3728 }
3729 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3730 EC_KEY_free(key);
3731 Py_RETURN_NONE;
3732}
Antoine Pitrou501da612011-12-21 09:27:41 +01003733#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003734
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003735#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003736static int
3737_servername_callback(SSL *s, int *al, void *args)
3738{
3739 int ret;
3740 PySSLContext *ssl_ctx = (PySSLContext *) args;
3741 PySSLSocket *ssl;
3742 PyObject *servername_o;
3743 PyObject *servername_idna;
3744 PyObject *result;
3745 /* The high-level ssl.SSLSocket object */
3746 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003747 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003748#ifdef WITH_THREAD
3749 PyGILState_STATE gstate = PyGILState_Ensure();
3750#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003751
3752 if (ssl_ctx->set_hostname == NULL) {
3753 /* remove race condition in this the call back while if removing the
3754 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003755#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003756 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003757#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003758 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003759 }
3760
3761 ssl = SSL_get_app_data(s);
3762 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003763
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003764 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003765 * SSL connection and that has a .context attribute that can be changed to
3766 * identify the requested hostname. Since the official API is the Python
3767 * level API we want to pass the callback a Python level object rather than
3768 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3769 * SSLObject) that will be passed. Otherwise if there's a socket then that
3770 * will be passed. If both do not exist only then the C-level object is
3771 * passed. */
3772 if (ssl->owner)
3773 ssl_socket = PyWeakref_GetObject(ssl->owner);
3774 else if (ssl->Socket)
3775 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3776 else
3777 ssl_socket = (PyObject *) ssl;
3778
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003779 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003780 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003781 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003782
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003783 if (servername == NULL) {
3784 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3785 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003786 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003787 else {
3788 servername_o = PyBytes_FromString(servername);
3789 if (servername_o == NULL) {
3790 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3791 goto error;
3792 }
3793 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3794 if (servername_idna == NULL) {
3795 PyErr_WriteUnraisable(servername_o);
3796 Py_DECREF(servername_o);
3797 goto error;
3798 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003799 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003800 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3801 servername_idna, ssl_ctx, NULL);
3802 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003803 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003804 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003805
3806 if (result == NULL) {
3807 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3808 *al = SSL_AD_HANDSHAKE_FAILURE;
3809 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3810 }
3811 else {
3812 if (result != Py_None) {
3813 *al = (int) PyLong_AsLong(result);
3814 if (PyErr_Occurred()) {
3815 PyErr_WriteUnraisable(result);
3816 *al = SSL_AD_INTERNAL_ERROR;
3817 }
3818 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3819 }
3820 else {
3821 ret = SSL_TLSEXT_ERR_OK;
3822 }
3823 Py_DECREF(result);
3824 }
3825
Stefan Krah20d60802013-01-17 17:07:17 +01003826#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003827 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003828#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003829 return ret;
3830
3831error:
3832 Py_DECREF(ssl_socket);
3833 *al = SSL_AD_INTERNAL_ERROR;
3834 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003835#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003836 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003837#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003838 return ret;
3839}
Antoine Pitroua5963382013-03-30 16:39:00 +01003840#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003841
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003842/*[clinic input]
3843_ssl._SSLContext.set_servername_callback
3844 method as cb: object
3845 /
3846
3847Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3848
3849If the argument is None then the callback is disabled. The method is called
3850with the SSLSocket, the server name as a string, and the SSLContext object.
3851See RFC 6066 for details of the SNI extension.
3852[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003853
3854static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003855_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3856/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003857{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003858#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003859 Py_CLEAR(self->set_hostname);
3860 if (cb == Py_None) {
3861 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3862 }
3863 else {
3864 if (!PyCallable_Check(cb)) {
3865 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3866 PyErr_SetString(PyExc_TypeError,
3867 "not a callable object");
3868 return NULL;
3869 }
3870 Py_INCREF(cb);
3871 self->set_hostname = cb;
3872 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3873 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3874 }
3875 Py_RETURN_NONE;
3876#else
3877 PyErr_SetString(PyExc_NotImplementedError,
3878 "The TLS extension servername callback, "
3879 "SSL_CTX_set_tlsext_servername_callback, "
3880 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003881 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003882#endif
3883}
3884
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003885/*[clinic input]
3886_ssl._SSLContext.cert_store_stats
3887
3888Returns quantities of loaded X.509 certificates.
3889
3890X.509 certificates with a CA extension and certificate revocation lists
3891inside the context's cert store.
3892
3893NOTE: Certificates in a capath directory aren't loaded unless they have
3894been used at least once.
3895[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003896
3897static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003898_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3899/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003900{
3901 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003902 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003903 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003904 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003905
3906 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003907 objs = X509_STORE_get0_objects(store);
3908 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3909 obj = sk_X509_OBJECT_value(objs, i);
3910 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003911 case X509_LU_X509:
3912 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003913 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003914 ca++;
3915 }
3916 break;
3917 case X509_LU_CRL:
3918 crl++;
3919 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003920 default:
3921 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3922 * As far as I can tell they are internal states and never
3923 * stored in a cert store */
3924 break;
3925 }
3926 }
3927 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3928 "x509_ca", ca);
3929}
3930
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003931/*[clinic input]
3932_ssl._SSLContext.get_ca_certs
3933 binary_form: bool = False
3934
3935Returns a list of dicts with information of loaded CA certs.
3936
3937If the optional argument is True, returns a DER-encoded copy of the CA
3938certificate.
3939
3940NOTE: Certificates in a capath directory aren't loaded unless they have
3941been used at least once.
3942[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003943
3944static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003945_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3946/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003947{
3948 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003949 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003950 PyObject *ci = NULL, *rlist = NULL;
3951 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003952
3953 if ((rlist = PyList_New(0)) == NULL) {
3954 return NULL;
3955 }
3956
3957 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003958 objs = X509_STORE_get0_objects(store);
3959 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003960 X509_OBJECT *obj;
3961 X509 *cert;
3962
Christian Heimes598894f2016-09-05 23:19:05 +02003963 obj = sk_X509_OBJECT_value(objs, i);
3964 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003965 /* not a x509 cert */
3966 continue;
3967 }
3968 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003969 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003970 if (!X509_check_ca(cert)) {
3971 continue;
3972 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003973 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003974 ci = _certificate_to_der(cert);
3975 } else {
3976 ci = _decode_certificate(cert);
3977 }
3978 if (ci == NULL) {
3979 goto error;
3980 }
3981 if (PyList_Append(rlist, ci) == -1) {
3982 goto error;
3983 }
3984 Py_CLEAR(ci);
3985 }
3986 return rlist;
3987
3988 error:
3989 Py_XDECREF(ci);
3990 Py_XDECREF(rlist);
3991 return NULL;
3992}
3993
3994
Antoine Pitrou152efa22010-05-16 18:19:27 +00003995static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003996 {"check_hostname", (getter) get_check_hostname,
3997 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003998 {"options", (getter) get_options,
3999 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004000 {"verify_flags", (getter) get_verify_flags,
4001 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004002 {"verify_mode", (getter) get_verify_mode,
4003 (setter) set_verify_mode, NULL},
4004 {NULL}, /* sentinel */
4005};
4006
4007static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004008 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4009 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4010 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4011 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4012 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4013 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4014 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4015 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4016 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4017 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4018 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4019 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4020 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4021 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004022 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004023 {NULL, NULL} /* sentinel */
4024};
4025
4026static PyTypeObject PySSLContext_Type = {
4027 PyVarObject_HEAD_INIT(NULL, 0)
4028 "_ssl._SSLContext", /*tp_name*/
4029 sizeof(PySSLContext), /*tp_basicsize*/
4030 0, /*tp_itemsize*/
4031 (destructor)context_dealloc, /*tp_dealloc*/
4032 0, /*tp_print*/
4033 0, /*tp_getattr*/
4034 0, /*tp_setattr*/
4035 0, /*tp_reserved*/
4036 0, /*tp_repr*/
4037 0, /*tp_as_number*/
4038 0, /*tp_as_sequence*/
4039 0, /*tp_as_mapping*/
4040 0, /*tp_hash*/
4041 0, /*tp_call*/
4042 0, /*tp_str*/
4043 0, /*tp_getattro*/
4044 0, /*tp_setattro*/
4045 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004046 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004047 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004048 (traverseproc) context_traverse, /*tp_traverse*/
4049 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004050 0, /*tp_richcompare*/
4051 0, /*tp_weaklistoffset*/
4052 0, /*tp_iter*/
4053 0, /*tp_iternext*/
4054 context_methods, /*tp_methods*/
4055 0, /*tp_members*/
4056 context_getsetlist, /*tp_getset*/
4057 0, /*tp_base*/
4058 0, /*tp_dict*/
4059 0, /*tp_descr_get*/
4060 0, /*tp_descr_set*/
4061 0, /*tp_dictoffset*/
4062 0, /*tp_init*/
4063 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004064 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004065};
4066
4067
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004068/*
4069 * MemoryBIO objects
4070 */
4071
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004072/*[clinic input]
4073@classmethod
4074_ssl.MemoryBIO.__new__
4075
4076[clinic start generated code]*/
4077
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004078static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004079_ssl_MemoryBIO_impl(PyTypeObject *type)
4080/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004081{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004082 BIO *bio;
4083 PySSLMemoryBIO *self;
4084
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004085 bio = BIO_new(BIO_s_mem());
4086 if (bio == NULL) {
4087 PyErr_SetString(PySSLErrorObject,
4088 "failed to allocate BIO");
4089 return NULL;
4090 }
4091 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4092 * just that no data is currently available. The SSL routines should retry
4093 * the read, which we can achieve by calling BIO_set_retry_read(). */
4094 BIO_set_retry_read(bio);
4095 BIO_set_mem_eof_return(bio, -1);
4096
4097 assert(type != NULL && type->tp_alloc != NULL);
4098 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4099 if (self == NULL) {
4100 BIO_free(bio);
4101 return NULL;
4102 }
4103 self->bio = bio;
4104 self->eof_written = 0;
4105
4106 return (PyObject *) self;
4107}
4108
4109static void
4110memory_bio_dealloc(PySSLMemoryBIO *self)
4111{
4112 BIO_free(self->bio);
4113 Py_TYPE(self)->tp_free(self);
4114}
4115
4116static PyObject *
4117memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4118{
Segev Finer5cff6372017-07-27 01:19:17 +03004119 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004120}
4121
4122PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4123"The number of bytes pending in the memory BIO.");
4124
4125static PyObject *
4126memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4127{
4128 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4129 && self->eof_written);
4130}
4131
4132PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4133"Whether the memory BIO is at EOF.");
4134
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004135/*[clinic input]
4136_ssl.MemoryBIO.read
4137 size as len: int = -1
4138 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004139
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004140Read up to size bytes from the memory BIO.
4141
4142If size is not specified, read the entire buffer.
4143If the return value is an empty bytes instance, this means either
4144EOF or that no data is available. Use the "eof" property to
4145distinguish between the two.
4146[clinic start generated code]*/
4147
4148static PyObject *
4149_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4150/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4151{
4152 int avail, nbytes;
4153 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004154
Segev Finer5cff6372017-07-27 01:19:17 +03004155 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004156 if ((len < 0) || (len > avail))
4157 len = avail;
4158
4159 result = PyBytes_FromStringAndSize(NULL, len);
4160 if ((result == NULL) || (len == 0))
4161 return result;
4162
4163 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4164 /* There should never be any short reads but check anyway. */
4165 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4166 Py_DECREF(result);
4167 return NULL;
4168 }
4169
4170 return result;
4171}
4172
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004173/*[clinic input]
4174_ssl.MemoryBIO.write
4175 b: Py_buffer
4176 /
4177
4178Writes the bytes b into the memory BIO.
4179
4180Returns the number of bytes written.
4181[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004182
4183static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004184_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4185/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004186{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 int nbytes;
4188
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004189 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004190 PyErr_Format(PyExc_OverflowError,
4191 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004192 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004193 }
4194
4195 if (self->eof_written) {
4196 PyErr_SetString(PySSLErrorObject,
4197 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004198 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004199 }
4200
Segev Finer5cff6372017-07-27 01:19:17 +03004201 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004202 if (nbytes < 0) {
4203 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004204 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205 }
4206
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004207 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004208}
4209
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004210/*[clinic input]
4211_ssl.MemoryBIO.write_eof
4212
4213Write an EOF marker to the memory BIO.
4214
4215When all data has been read, the "eof" property will be True.
4216[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004217
4218static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004219_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4220/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004221{
4222 self->eof_written = 1;
4223 /* After an EOF is written, a zero return from read() should be a real EOF
4224 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4225 BIO_clear_retry_flags(self->bio);
4226 BIO_set_mem_eof_return(self->bio, 0);
4227
4228 Py_RETURN_NONE;
4229}
4230
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004231static PyGetSetDef memory_bio_getsetlist[] = {
4232 {"pending", (getter) memory_bio_get_pending, NULL,
4233 PySSL_memory_bio_pending_doc},
4234 {"eof", (getter) memory_bio_get_eof, NULL,
4235 PySSL_memory_bio_eof_doc},
4236 {NULL}, /* sentinel */
4237};
4238
4239static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004240 _SSL_MEMORYBIO_READ_METHODDEF
4241 _SSL_MEMORYBIO_WRITE_METHODDEF
4242 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004243 {NULL, NULL} /* sentinel */
4244};
4245
4246static PyTypeObject PySSLMemoryBIO_Type = {
4247 PyVarObject_HEAD_INIT(NULL, 0)
4248 "_ssl.MemoryBIO", /*tp_name*/
4249 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4250 0, /*tp_itemsize*/
4251 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4252 0, /*tp_print*/
4253 0, /*tp_getattr*/
4254 0, /*tp_setattr*/
4255 0, /*tp_reserved*/
4256 0, /*tp_repr*/
4257 0, /*tp_as_number*/
4258 0, /*tp_as_sequence*/
4259 0, /*tp_as_mapping*/
4260 0, /*tp_hash*/
4261 0, /*tp_call*/
4262 0, /*tp_str*/
4263 0, /*tp_getattro*/
4264 0, /*tp_setattro*/
4265 0, /*tp_as_buffer*/
4266 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4267 0, /*tp_doc*/
4268 0, /*tp_traverse*/
4269 0, /*tp_clear*/
4270 0, /*tp_richcompare*/
4271 0, /*tp_weaklistoffset*/
4272 0, /*tp_iter*/
4273 0, /*tp_iternext*/
4274 memory_bio_methods, /*tp_methods*/
4275 0, /*tp_members*/
4276 memory_bio_getsetlist, /*tp_getset*/
4277 0, /*tp_base*/
4278 0, /*tp_dict*/
4279 0, /*tp_descr_get*/
4280 0, /*tp_descr_set*/
4281 0, /*tp_dictoffset*/
4282 0, /*tp_init*/
4283 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004284 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004285};
4286
Antoine Pitrou152efa22010-05-16 18:19:27 +00004287
Christian Heimes99a65702016-09-10 23:44:53 +02004288/*
4289 * SSL Session object
4290 */
4291
4292static void
4293PySSLSession_dealloc(PySSLSession *self)
4294{
Christian Heimesa5d07652016-09-24 10:48:05 +02004295 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004296 Py_XDECREF(self->ctx);
4297 if (self->session != NULL) {
4298 SSL_SESSION_free(self->session);
4299 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004300 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004301}
4302
4303static PyObject *
4304PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4305{
4306 int result;
4307
4308 if (left == NULL || right == NULL) {
4309 PyErr_BadInternalCall();
4310 return NULL;
4311 }
4312
4313 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4314 Py_RETURN_NOTIMPLEMENTED;
4315 }
4316
4317 if (left == right) {
4318 result = 0;
4319 } else {
4320 const unsigned char *left_id, *right_id;
4321 unsigned int left_len, right_len;
4322 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4323 &left_len);
4324 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4325 &right_len);
4326 if (left_len == right_len) {
4327 result = memcmp(left_id, right_id, left_len);
4328 } else {
4329 result = 1;
4330 }
4331 }
4332
4333 switch (op) {
4334 case Py_EQ:
4335 if (result == 0) {
4336 Py_RETURN_TRUE;
4337 } else {
4338 Py_RETURN_FALSE;
4339 }
4340 break;
4341 case Py_NE:
4342 if (result != 0) {
4343 Py_RETURN_TRUE;
4344 } else {
4345 Py_RETURN_FALSE;
4346 }
4347 break;
4348 case Py_LT:
4349 case Py_LE:
4350 case Py_GT:
4351 case Py_GE:
4352 Py_RETURN_NOTIMPLEMENTED;
4353 break;
4354 default:
4355 PyErr_BadArgument();
4356 return NULL;
4357 }
4358}
4359
4360static int
4361PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4362{
4363 Py_VISIT(self->ctx);
4364 return 0;
4365}
4366
4367static int
4368PySSLSession_clear(PySSLSession *self)
4369{
4370 Py_CLEAR(self->ctx);
4371 return 0;
4372}
4373
4374
4375static PyObject *
4376PySSLSession_get_time(PySSLSession *self, void *closure) {
4377 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4378}
4379
4380PyDoc_STRVAR(PySSLSession_get_time_doc,
4381"Session creation time (seconds since epoch).");
4382
4383
4384static PyObject *
4385PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4386 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4387}
4388
4389PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4390"Session timeout (delta in seconds).");
4391
4392
4393static PyObject *
4394PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4395 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4396 return PyLong_FromUnsignedLong(hint);
4397}
4398
4399PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4400"Ticket life time hint.");
4401
4402
4403static PyObject *
4404PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4405 const unsigned char *id;
4406 unsigned int len;
4407 id = SSL_SESSION_get_id(self->session, &len);
4408 return PyBytes_FromStringAndSize((const char *)id, len);
4409}
4410
4411PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4412"Session id");
4413
4414
4415static PyObject *
4416PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4417 if (SSL_SESSION_has_ticket(self->session)) {
4418 Py_RETURN_TRUE;
4419 } else {
4420 Py_RETURN_FALSE;
4421 }
4422}
4423
4424PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4425"Does the session contain a ticket?");
4426
4427
4428static PyGetSetDef PySSLSession_getsetlist[] = {
4429 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4430 PySSLSession_get_has_ticket_doc},
4431 {"id", (getter) PySSLSession_get_session_id, NULL,
4432 PySSLSession_get_session_id_doc},
4433 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4434 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4435 {"time", (getter) PySSLSession_get_time, NULL,
4436 PySSLSession_get_time_doc},
4437 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4438 PySSLSession_get_timeout_doc},
4439 {NULL}, /* sentinel */
4440};
4441
4442static PyTypeObject PySSLSession_Type = {
4443 PyVarObject_HEAD_INIT(NULL, 0)
4444 "_ssl.Session", /*tp_name*/
4445 sizeof(PySSLSession), /*tp_basicsize*/
4446 0, /*tp_itemsize*/
4447 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4448 0, /*tp_print*/
4449 0, /*tp_getattr*/
4450 0, /*tp_setattr*/
4451 0, /*tp_reserved*/
4452 0, /*tp_repr*/
4453 0, /*tp_as_number*/
4454 0, /*tp_as_sequence*/
4455 0, /*tp_as_mapping*/
4456 0, /*tp_hash*/
4457 0, /*tp_call*/
4458 0, /*tp_str*/
4459 0, /*tp_getattro*/
4460 0, /*tp_setattro*/
4461 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004462 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004463 0, /*tp_doc*/
4464 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4465 (inquiry)PySSLSession_clear, /*tp_clear*/
4466 PySSLSession_richcompare, /*tp_richcompare*/
4467 0, /*tp_weaklistoffset*/
4468 0, /*tp_iter*/
4469 0, /*tp_iternext*/
4470 0, /*tp_methods*/
4471 0, /*tp_members*/
4472 PySSLSession_getsetlist, /*tp_getset*/
4473};
4474
4475
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004476/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004477/*[clinic input]
4478_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004479 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480 entropy: double
4481 /
4482
4483Mix string into the OpenSSL PRNG state.
4484
4485entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304486string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004487[clinic start generated code]*/
4488
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004489static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004490_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004491/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004492{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004493 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004494 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004495
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004496 buf = (const char *)view->buf;
4497 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004498 do {
4499 written = Py_MIN(len, INT_MAX);
4500 RAND_add(buf, (int)written, entropy);
4501 buf += written;
4502 len -= written;
4503 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004504 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004505}
4506
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004507static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004508PySSL_RAND(int len, int pseudo)
4509{
4510 int ok;
4511 PyObject *bytes;
4512 unsigned long err;
4513 const char *errstr;
4514 PyObject *v;
4515
Victor Stinner1e81a392013-12-19 16:47:04 +01004516 if (len < 0) {
4517 PyErr_SetString(PyExc_ValueError, "num must be positive");
4518 return NULL;
4519 }
4520
Victor Stinner99c8b162011-05-24 12:05:19 +02004521 bytes = PyBytes_FromStringAndSize(NULL, len);
4522 if (bytes == NULL)
4523 return NULL;
4524 if (pseudo) {
4525 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4526 if (ok == 0 || ok == 1)
4527 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4528 }
4529 else {
4530 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4531 if (ok == 1)
4532 return bytes;
4533 }
4534 Py_DECREF(bytes);
4535
4536 err = ERR_get_error();
4537 errstr = ERR_reason_error_string(err);
4538 v = Py_BuildValue("(ks)", err, errstr);
4539 if (v != NULL) {
4540 PyErr_SetObject(PySSLErrorObject, v);
4541 Py_DECREF(v);
4542 }
4543 return NULL;
4544}
4545
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004546/*[clinic input]
4547_ssl.RAND_bytes
4548 n: int
4549 /
4550
4551Generate n cryptographically strong pseudo-random bytes.
4552[clinic start generated code]*/
4553
Victor Stinner99c8b162011-05-24 12:05:19 +02004554static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004555_ssl_RAND_bytes_impl(PyObject *module, int n)
4556/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004557{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004558 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004559}
4560
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561/*[clinic input]
4562_ssl.RAND_pseudo_bytes
4563 n: int
4564 /
4565
4566Generate n pseudo-random bytes.
4567
4568Return a pair (bytes, is_cryptographic). is_cryptographic is True
4569if the bytes generated are cryptographically strong.
4570[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004571
4572static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004573_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4574/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004575{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004576 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004577}
4578
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004579/*[clinic input]
4580_ssl.RAND_status
4581
4582Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4583
4584It is necessary to seed the PRNG with RAND_add() on some platforms before
4585using the ssl() function.
4586[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004587
4588static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004589_ssl_RAND_status_impl(PyObject *module)
4590/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004591{
Christian Heimes217cfd12007-12-02 14:31:20 +00004592 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004593}
4594
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004595#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004596/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004597/*[clinic input]
4598_ssl.RAND_egd
4599 path: object(converter="PyUnicode_FSConverter")
4600 /
4601
4602Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4603
4604Returns number of bytes read. Raises SSLError if connection to EGD
4605fails or if it does not provide enough data to seed PRNG.
4606[clinic start generated code]*/
4607
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004608static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004609_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4610/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004611{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004612 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004613 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004614 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004615 PyErr_SetString(PySSLErrorObject,
4616 "EGD connection failed or EGD did not return "
4617 "enough data to seed the PRNG");
4618 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004620 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004621}
Christian Heimesa5d07652016-09-24 10:48:05 +02004622/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004623#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004624
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004625
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004626
4627/*[clinic input]
4628_ssl.get_default_verify_paths
4629
4630Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4631
4632The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4633[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004634
4635static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004636_ssl_get_default_verify_paths_impl(PyObject *module)
4637/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004638{
4639 PyObject *ofile_env = NULL;
4640 PyObject *ofile = NULL;
4641 PyObject *odir_env = NULL;
4642 PyObject *odir = NULL;
4643
Benjamin Petersond113c962015-07-18 10:59:13 -07004644#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004645 const char *tmp = (info); \
4646 target = NULL; \
4647 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4648 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4649 target = PyBytes_FromString(tmp); } \
4650 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004651 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004652
Benjamin Petersond113c962015-07-18 10:59:13 -07004653 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4654 CONVERT(X509_get_default_cert_file(), ofile);
4655 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4656 CONVERT(X509_get_default_cert_dir(), odir);
4657#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004658
Christian Heimes200bb1b2013-06-14 15:14:29 +02004659 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004660
4661 error:
4662 Py_XDECREF(ofile_env);
4663 Py_XDECREF(ofile);
4664 Py_XDECREF(odir_env);
4665 Py_XDECREF(odir);
4666 return NULL;
4667}
4668
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004669static PyObject*
4670asn1obj2py(ASN1_OBJECT *obj)
4671{
4672 int nid;
4673 const char *ln, *sn;
4674 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004675 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004676
4677 nid = OBJ_obj2nid(obj);
4678 if (nid == NID_undef) {
4679 PyErr_Format(PyExc_ValueError, "Unknown object");
4680 return NULL;
4681 }
4682 sn = OBJ_nid2sn(nid);
4683 ln = OBJ_nid2ln(nid);
4684 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4685 if (buflen < 0) {
4686 _setSSLError(NULL, 0, __FILE__, __LINE__);
4687 return NULL;
4688 }
4689 if (buflen) {
4690 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4691 } else {
4692 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4693 }
4694}
4695
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004696/*[clinic input]
4697_ssl.txt2obj
4698 txt: str
4699 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004700
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004701Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4702
4703By default objects are looked up by OID. With name=True short and
4704long name are also matched.
4705[clinic start generated code]*/
4706
4707static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004708_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4709/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004710{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004711 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004712 ASN1_OBJECT *obj;
4713
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004714 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4715 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004716 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004717 return NULL;
4718 }
4719 result = asn1obj2py(obj);
4720 ASN1_OBJECT_free(obj);
4721 return result;
4722}
4723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004724/*[clinic input]
4725_ssl.nid2obj
4726 nid: int
4727 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004728
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004729Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4730[clinic start generated code]*/
4731
4732static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004733_ssl_nid2obj_impl(PyObject *module, int nid)
4734/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004735{
4736 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004737 ASN1_OBJECT *obj;
4738
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004739 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004740 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004741 return NULL;
4742 }
4743 obj = OBJ_nid2obj(nid);
4744 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004745 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004746 return NULL;
4747 }
4748 result = asn1obj2py(obj);
4749 ASN1_OBJECT_free(obj);
4750 return result;
4751}
4752
Christian Heimes46bebee2013-06-09 19:03:31 +02004753#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004754
4755static PyObject*
4756certEncodingType(DWORD encodingType)
4757{
4758 static PyObject *x509_asn = NULL;
4759 static PyObject *pkcs_7_asn = NULL;
4760
4761 if (x509_asn == NULL) {
4762 x509_asn = PyUnicode_InternFromString("x509_asn");
4763 if (x509_asn == NULL)
4764 return NULL;
4765 }
4766 if (pkcs_7_asn == NULL) {
4767 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4768 if (pkcs_7_asn == NULL)
4769 return NULL;
4770 }
4771 switch(encodingType) {
4772 case X509_ASN_ENCODING:
4773 Py_INCREF(x509_asn);
4774 return x509_asn;
4775 case PKCS_7_ASN_ENCODING:
4776 Py_INCREF(pkcs_7_asn);
4777 return pkcs_7_asn;
4778 default:
4779 return PyLong_FromLong(encodingType);
4780 }
4781}
4782
4783static PyObject*
4784parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4785{
4786 CERT_ENHKEY_USAGE *usage;
4787 DWORD size, error, i;
4788 PyObject *retval;
4789
4790 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4791 error = GetLastError();
4792 if (error == CRYPT_E_NOT_FOUND) {
4793 Py_RETURN_TRUE;
4794 }
4795 return PyErr_SetFromWindowsErr(error);
4796 }
4797
4798 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4799 if (usage == NULL) {
4800 return PyErr_NoMemory();
4801 }
4802
4803 /* Now get the actual enhanced usage property */
4804 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4805 PyMem_Free(usage);
4806 error = GetLastError();
4807 if (error == CRYPT_E_NOT_FOUND) {
4808 Py_RETURN_TRUE;
4809 }
4810 return PyErr_SetFromWindowsErr(error);
4811 }
4812 retval = PySet_New(NULL);
4813 if (retval == NULL) {
4814 goto error;
4815 }
4816 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4817 if (usage->rgpszUsageIdentifier[i]) {
4818 PyObject *oid;
4819 int err;
4820 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4821 if (oid == NULL) {
4822 Py_CLEAR(retval);
4823 goto error;
4824 }
4825 err = PySet_Add(retval, oid);
4826 Py_DECREF(oid);
4827 if (err == -1) {
4828 Py_CLEAR(retval);
4829 goto error;
4830 }
4831 }
4832 }
4833 error:
4834 PyMem_Free(usage);
4835 return retval;
4836}
4837
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004838/*[clinic input]
4839_ssl.enum_certificates
4840 store_name: str
4841
4842Retrieve certificates from Windows' cert store.
4843
4844store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4845more cert storages, too. The function returns a list of (bytes,
4846encoding_type, trust) tuples. The encoding_type flag can be interpreted
4847with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4848a set of OIDs or the boolean True.
4849[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004850
Christian Heimes46bebee2013-06-09 19:03:31 +02004851static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004852_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4853/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004854{
Christian Heimes46bebee2013-06-09 19:03:31 +02004855 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004856 PCCERT_CONTEXT pCertCtx = NULL;
4857 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004858 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004859
Christian Heimes44109d72013-11-22 01:51:30 +01004860 result = PyList_New(0);
4861 if (result == NULL) {
4862 return NULL;
4863 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004864 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4865 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4866 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004867 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004868 Py_DECREF(result);
4869 return PyErr_SetFromWindowsErr(GetLastError());
4870 }
4871
Christian Heimes44109d72013-11-22 01:51:30 +01004872 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4873 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4874 pCertCtx->cbCertEncoded);
4875 if (!cert) {
4876 Py_CLEAR(result);
4877 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004878 }
Christian Heimes44109d72013-11-22 01:51:30 +01004879 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4880 Py_CLEAR(result);
4881 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004882 }
Christian Heimes44109d72013-11-22 01:51:30 +01004883 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4884 if (keyusage == Py_True) {
4885 Py_DECREF(keyusage);
4886 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004887 }
Christian Heimes44109d72013-11-22 01:51:30 +01004888 if (keyusage == NULL) {
4889 Py_CLEAR(result);
4890 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004891 }
Christian Heimes44109d72013-11-22 01:51:30 +01004892 if ((tup = PyTuple_New(3)) == NULL) {
4893 Py_CLEAR(result);
4894 break;
4895 }
4896 PyTuple_SET_ITEM(tup, 0, cert);
4897 cert = NULL;
4898 PyTuple_SET_ITEM(tup, 1, enc);
4899 enc = NULL;
4900 PyTuple_SET_ITEM(tup, 2, keyusage);
4901 keyusage = NULL;
4902 if (PyList_Append(result, tup) < 0) {
4903 Py_CLEAR(result);
4904 break;
4905 }
4906 Py_CLEAR(tup);
4907 }
4908 if (pCertCtx) {
4909 /* loop ended with an error, need to clean up context manually */
4910 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004911 }
4912
4913 /* In error cases cert, enc and tup may not be NULL */
4914 Py_XDECREF(cert);
4915 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004916 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004917 Py_XDECREF(tup);
4918
4919 if (!CertCloseStore(hStore, 0)) {
4920 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004921 Py_XDECREF(result);
4922 return PyErr_SetFromWindowsErr(GetLastError());
4923 }
4924 return result;
4925}
4926
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004927/*[clinic input]
4928_ssl.enum_crls
4929 store_name: str
4930
4931Retrieve CRLs from Windows' cert store.
4932
4933store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4934more cert storages, too. The function returns a list of (bytes,
4935encoding_type) tuples. The encoding_type flag can be interpreted with
4936X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4937[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004938
4939static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004940_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4941/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004942{
Christian Heimes44109d72013-11-22 01:51:30 +01004943 HCERTSTORE hStore = NULL;
4944 PCCRL_CONTEXT pCrlCtx = NULL;
4945 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4946 PyObject *result = NULL;
4947
Christian Heimes44109d72013-11-22 01:51:30 +01004948 result = PyList_New(0);
4949 if (result == NULL) {
4950 return NULL;
4951 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004952 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4953 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4954 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004955 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004956 Py_DECREF(result);
4957 return PyErr_SetFromWindowsErr(GetLastError());
4958 }
Christian Heimes44109d72013-11-22 01:51:30 +01004959
4960 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4961 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4962 pCrlCtx->cbCrlEncoded);
4963 if (!crl) {
4964 Py_CLEAR(result);
4965 break;
4966 }
4967 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4968 Py_CLEAR(result);
4969 break;
4970 }
4971 if ((tup = PyTuple_New(2)) == NULL) {
4972 Py_CLEAR(result);
4973 break;
4974 }
4975 PyTuple_SET_ITEM(tup, 0, crl);
4976 crl = NULL;
4977 PyTuple_SET_ITEM(tup, 1, enc);
4978 enc = NULL;
4979
4980 if (PyList_Append(result, tup) < 0) {
4981 Py_CLEAR(result);
4982 break;
4983 }
4984 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004985 }
Christian Heimes44109d72013-11-22 01:51:30 +01004986 if (pCrlCtx) {
4987 /* loop ended with an error, need to clean up context manually */
4988 CertFreeCRLContext(pCrlCtx);
4989 }
4990
4991 /* In error cases cert, enc and tup may not be NULL */
4992 Py_XDECREF(crl);
4993 Py_XDECREF(enc);
4994 Py_XDECREF(tup);
4995
4996 if (!CertCloseStore(hStore, 0)) {
4997 /* This error case might shadow another exception.*/
4998 Py_XDECREF(result);
4999 return PyErr_SetFromWindowsErr(GetLastError());
5000 }
5001 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005002}
Christian Heimes44109d72013-11-22 01:51:30 +01005003
5004#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005005
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005006/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005007static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005008 _SSL__TEST_DECODE_CERT_METHODDEF
5009 _SSL_RAND_ADD_METHODDEF
5010 _SSL_RAND_BYTES_METHODDEF
5011 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5012 _SSL_RAND_EGD_METHODDEF
5013 _SSL_RAND_STATUS_METHODDEF
5014 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5015 _SSL_ENUM_CERTIFICATES_METHODDEF
5016 _SSL_ENUM_CRLS_METHODDEF
5017 _SSL_TXT2OBJ_METHODDEF
5018 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005019 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005020};
5021
5022
Christian Heimes598894f2016-09-05 23:19:05 +02005023#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005024
5025/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005026 * of the Python C thread library
5027 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5028 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005029
5030static PyThread_type_lock *_ssl_locks = NULL;
5031
Christian Heimes4d98ca92013-08-19 17:36:29 +02005032#if OPENSSL_VERSION_NUMBER >= 0x10000000
5033/* use new CRYPTO_THREADID API. */
5034static void
5035_ssl_threadid_callback(CRYPTO_THREADID *id)
5036{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005037 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005038}
5039#else
5040/* deprecated CRYPTO_set_id_callback() API. */
5041static unsigned long
5042_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005043 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005044}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005045#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005046
Bill Janssen6e027db2007-11-15 22:23:56 +00005047static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005048 (int mode, int n, const char *file, int line) {
5049 /* this function is needed to perform locking on shared data
5050 structures. (Note that OpenSSL uses a number of global data
5051 structures that will be implicitly shared whenever multiple
5052 threads use OpenSSL.) Multi-threaded applications will
5053 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005055 locking_function() must be able to handle up to
5056 CRYPTO_num_locks() different mutex locks. It sets the n-th
5057 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005059 file and line are the file number of the function setting the
5060 lock. They can be useful for debugging.
5061 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005063 if ((_ssl_locks == NULL) ||
5064 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5065 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005067 if (mode & CRYPTO_LOCK) {
5068 PyThread_acquire_lock(_ssl_locks[n], 1);
5069 } else {
5070 PyThread_release_lock(_ssl_locks[n]);
5071 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005072}
5073
5074static int _setup_ssl_threads(void) {
5075
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005076 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005077
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005078 if (_ssl_locks == NULL) {
5079 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005080 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5081 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005082 if (_ssl_locks == NULL) {
5083 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005084 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005085 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005086 for (i = 0; i < _ssl_locks_count; i++) {
5087 _ssl_locks[i] = PyThread_allocate_lock();
5088 if (_ssl_locks[i] == NULL) {
5089 unsigned int j;
5090 for (j = 0; j < i; j++) {
5091 PyThread_free_lock(_ssl_locks[j]);
5092 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005093 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005094 return 0;
5095 }
5096 }
5097 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005098#if OPENSSL_VERSION_NUMBER >= 0x10000000
5099 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5100#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005101 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005102#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005103 }
5104 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005105}
5106
Christian Heimes598894f2016-09-05 23:19:05 +02005107#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005108
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005109PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005110"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005111for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005112
Martin v. Löwis1a214512008-06-11 05:26:20 +00005113
5114static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005115 PyModuleDef_HEAD_INIT,
5116 "_ssl",
5117 module_doc,
5118 -1,
5119 PySSL_methods,
5120 NULL,
5121 NULL,
5122 NULL,
5123 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005124};
5125
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005126
5127static void
5128parse_openssl_version(unsigned long libver,
5129 unsigned int *major, unsigned int *minor,
5130 unsigned int *fix, unsigned int *patch,
5131 unsigned int *status)
5132{
5133 *status = libver & 0xF;
5134 libver >>= 4;
5135 *patch = libver & 0xFF;
5136 libver >>= 8;
5137 *fix = libver & 0xFF;
5138 libver >>= 8;
5139 *minor = libver & 0xFF;
5140 libver >>= 8;
5141 *major = libver & 0xFF;
5142}
5143
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005144PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005145PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005146{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005147 PyObject *m, *d, *r;
5148 unsigned long libver;
5149 unsigned int major, minor, fix, patch, status;
5150 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005151 struct py_ssl_error_code *errcode;
5152 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005153
Antoine Pitrou152efa22010-05-16 18:19:27 +00005154 if (PyType_Ready(&PySSLContext_Type) < 0)
5155 return NULL;
5156 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005157 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005158 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5159 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005160 if (PyType_Ready(&PySSLSession_Type) < 0)
5161 return NULL;
5162
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005164 m = PyModule_Create(&_sslmodule);
5165 if (m == NULL)
5166 return NULL;
5167 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005168
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005169 /* Load _socket module and its C API */
5170 socket_api = PySocketModule_ImportModuleAndAPI();
5171 if (!socket_api)
5172 return NULL;
5173 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005175 /* Init OpenSSL */
5176 SSL_load_error_strings();
5177 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005179#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005180 /* note that this will start threading if not already started */
5181 if (!_setup_ssl_threads()) {
5182 return NULL;
5183 }
Christian Heimes598894f2016-09-05 23:19:05 +02005184#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5185 /* OpenSSL 1.1.0 builtin thread support is enabled */
5186 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005187#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005188#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005189 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005190
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005191 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005192 sslerror_type_slots[0].pfunc = PyExc_OSError;
5193 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005194 if (PySSLErrorObject == NULL)
5195 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005196
Antoine Pitrou41032a62011-10-27 23:56:55 +02005197 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5198 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5199 PySSLErrorObject, NULL);
5200 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5201 "ssl.SSLWantReadError", SSLWantReadError_doc,
5202 PySSLErrorObject, NULL);
5203 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5204 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5205 PySSLErrorObject, NULL);
5206 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5207 "ssl.SSLSyscallError", SSLSyscallError_doc,
5208 PySSLErrorObject, NULL);
5209 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5210 "ssl.SSLEOFError", SSLEOFError_doc,
5211 PySSLErrorObject, NULL);
5212 if (PySSLZeroReturnErrorObject == NULL
5213 || PySSLWantReadErrorObject == NULL
5214 || PySSLWantWriteErrorObject == NULL
5215 || PySSLSyscallErrorObject == NULL
5216 || PySSLEOFErrorObject == NULL)
5217 return NULL;
5218 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5219 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5220 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5221 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5222 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5223 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005224 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005225 if (PyDict_SetItemString(d, "_SSLContext",
5226 (PyObject *)&PySSLContext_Type) != 0)
5227 return NULL;
5228 if (PyDict_SetItemString(d, "_SSLSocket",
5229 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005230 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005231 if (PyDict_SetItemString(d, "MemoryBIO",
5232 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5233 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005234 if (PyDict_SetItemString(d, "SSLSession",
5235 (PyObject *)&PySSLSession_Type) != 0)
5236 return NULL;
5237
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005238 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5239 PY_SSL_ERROR_ZERO_RETURN);
5240 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5241 PY_SSL_ERROR_WANT_READ);
5242 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5243 PY_SSL_ERROR_WANT_WRITE);
5244 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5245 PY_SSL_ERROR_WANT_X509_LOOKUP);
5246 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5247 PY_SSL_ERROR_SYSCALL);
5248 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5249 PY_SSL_ERROR_SSL);
5250 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5251 PY_SSL_ERROR_WANT_CONNECT);
5252 /* non ssl.h errorcodes */
5253 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5254 PY_SSL_ERROR_EOF);
5255 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5256 PY_SSL_ERROR_INVALID_ERROR_CODE);
5257 /* cert requirements */
5258 PyModule_AddIntConstant(m, "CERT_NONE",
5259 PY_SSL_CERT_NONE);
5260 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5261 PY_SSL_CERT_OPTIONAL);
5262 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5263 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005264 /* CRL verification for verification_flags */
5265 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5266 0);
5267 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5268 X509_V_FLAG_CRL_CHECK);
5269 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5270 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5271 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5272 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005273#ifdef X509_V_FLAG_TRUSTED_FIRST
5274 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5275 X509_V_FLAG_TRUSTED_FIRST);
5276#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005277
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005278 /* Alert Descriptions from ssl.h */
5279 /* note RESERVED constants no longer intended for use have been removed */
5280 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5281
5282#define ADD_AD_CONSTANT(s) \
5283 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5284 SSL_AD_##s)
5285
5286 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5287 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5288 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5289 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5290 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5291 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5292 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5293 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5294 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5295 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5296 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5297 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5298 ADD_AD_CONSTANT(UNKNOWN_CA);
5299 ADD_AD_CONSTANT(ACCESS_DENIED);
5300 ADD_AD_CONSTANT(DECODE_ERROR);
5301 ADD_AD_CONSTANT(DECRYPT_ERROR);
5302 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5303 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5304 ADD_AD_CONSTANT(INTERNAL_ERROR);
5305 ADD_AD_CONSTANT(USER_CANCELLED);
5306 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005307 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005308#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5309 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5310#endif
5311#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5312 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5313#endif
5314#ifdef SSL_AD_UNRECOGNIZED_NAME
5315 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5316#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005317#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5318 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5319#endif
5320#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5321 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5322#endif
5323#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5324 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5325#endif
5326
5327#undef ADD_AD_CONSTANT
5328
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005329 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005330#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005331 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5332 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005333#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005334#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005335 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5336 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005337#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005338 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005339 PY_SSL_VERSION_TLS);
5340 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5341 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005342 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5343 PY_SSL_VERSION_TLS_CLIENT);
5344 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5345 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005346 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5347 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005348#if HAVE_TLSv1_2
5349 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5350 PY_SSL_VERSION_TLS1_1);
5351 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5352 PY_SSL_VERSION_TLS1_2);
5353#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005354
Antoine Pitroub5218772010-05-21 09:56:06 +00005355 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005356 PyModule_AddIntConstant(m, "OP_ALL",
5357 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005358 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5359 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5360 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005361#if HAVE_TLSv1_2
5362 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5363 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5364#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005365 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5366 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005367 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005368 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005369#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005370 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005371#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005372#ifdef SSL_OP_NO_COMPRESSION
5373 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5374 SSL_OP_NO_COMPRESSION);
5375#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005376
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005377#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005378 r = Py_True;
5379#else
5380 r = Py_False;
5381#endif
5382 Py_INCREF(r);
5383 PyModule_AddObject(m, "HAS_SNI", r);
5384
Antoine Pitroud6494802011-07-21 01:11:30 +02005385 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005386 Py_INCREF(r);
5387 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5388
Antoine Pitrou501da612011-12-21 09:27:41 +01005389#ifdef OPENSSL_NO_ECDH
5390 r = Py_False;
5391#else
5392 r = Py_True;
5393#endif
5394 Py_INCREF(r);
5395 PyModule_AddObject(m, "HAS_ECDH", r);
5396
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005397#ifdef OPENSSL_NPN_NEGOTIATED
5398 r = Py_True;
5399#else
5400 r = Py_False;
5401#endif
5402 Py_INCREF(r);
5403 PyModule_AddObject(m, "HAS_NPN", r);
5404
Benjamin Petersoncca27322015-01-23 16:35:37 -05005405#ifdef HAVE_ALPN
5406 r = Py_True;
5407#else
5408 r = Py_False;
5409#endif
5410 Py_INCREF(r);
5411 PyModule_AddObject(m, "HAS_ALPN", r);
5412
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005413 /* Mappings for error codes */
5414 err_codes_to_names = PyDict_New();
5415 err_names_to_codes = PyDict_New();
5416 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5417 return NULL;
5418 errcode = error_codes;
5419 while (errcode->mnemonic != NULL) {
5420 PyObject *mnemo, *key;
5421 mnemo = PyUnicode_FromString(errcode->mnemonic);
5422 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5423 if (mnemo == NULL || key == NULL)
5424 return NULL;
5425 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5426 return NULL;
5427 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5428 return NULL;
5429 Py_DECREF(key);
5430 Py_DECREF(mnemo);
5431 errcode++;
5432 }
5433 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5434 return NULL;
5435 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5436 return NULL;
5437
5438 lib_codes_to_names = PyDict_New();
5439 if (lib_codes_to_names == NULL)
5440 return NULL;
5441 libcode = library_codes;
5442 while (libcode->library != NULL) {
5443 PyObject *mnemo, *key;
5444 key = PyLong_FromLong(libcode->code);
5445 mnemo = PyUnicode_FromString(libcode->library);
5446 if (key == NULL || mnemo == NULL)
5447 return NULL;
5448 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5449 return NULL;
5450 Py_DECREF(key);
5451 Py_DECREF(mnemo);
5452 libcode++;
5453 }
5454 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5455 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005456
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005457 /* OpenSSL version */
5458 /* SSLeay() gives us the version of the library linked against,
5459 which could be different from the headers version.
5460 */
5461 libver = SSLeay();
5462 r = PyLong_FromUnsignedLong(libver);
5463 if (r == NULL)
5464 return NULL;
5465 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5466 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005467 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005468 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5469 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5470 return NULL;
5471 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5472 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5473 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005474
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005475 libver = OPENSSL_VERSION_NUMBER;
5476 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5477 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5478 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5479 return NULL;
5480
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005481 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005482}