blob: e8abcb286f28f8466a54fc828cb9119669a4a5c5 [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{
INADA Naokia6296d32017-08-24 14:55:17 +09002781 /* bpo-31095: UnTrack is needed before calling any callbacks */
2782 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002783 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002784 SSL_CTX_free(self->ctx);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002785#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002786 PyMem_FREE(self->npn_protocols);
2787#endif
2788#ifdef HAVE_ALPN
2789 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002790#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002791 Py_TYPE(self)->tp_free(self);
2792}
2793
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002794/*[clinic input]
2795_ssl._SSLContext.set_ciphers
2796 cipherlist: str
2797 /
2798[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002799
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002800static PyObject *
2801_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2802/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2803{
2804 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002805 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002806 /* Clearing the error queue is necessary on some OpenSSL versions,
2807 otherwise the error will be reported again when another SSL call
2808 is done. */
2809 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002810 PyErr_SetString(PySSLErrorObject,
2811 "No cipher can be selected.");
2812 return NULL;
2813 }
2814 Py_RETURN_NONE;
2815}
2816
Christian Heimes25bfcd52016-09-06 00:04:45 +02002817#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2818/*[clinic input]
2819_ssl._SSLContext.get_ciphers
2820[clinic start generated code]*/
2821
2822static PyObject *
2823_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2824/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2825{
2826 SSL *ssl = NULL;
2827 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002828 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002829 int i=0;
2830 PyObject *result = NULL, *dct;
2831
2832 ssl = SSL_new(self->ctx);
2833 if (ssl == NULL) {
2834 _setSSLError(NULL, 0, __FILE__, __LINE__);
2835 goto exit;
2836 }
2837 sk = SSL_get_ciphers(ssl);
2838
2839 result = PyList_New(sk_SSL_CIPHER_num(sk));
2840 if (result == NULL) {
2841 goto exit;
2842 }
2843
2844 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2845 cipher = sk_SSL_CIPHER_value(sk, i);
2846 dct = cipher_to_dict(cipher);
2847 if (dct == NULL) {
2848 Py_CLEAR(result);
2849 goto exit;
2850 }
2851 PyList_SET_ITEM(result, i, dct);
2852 }
2853
2854 exit:
2855 if (ssl != NULL)
2856 SSL_free(ssl);
2857 return result;
2858
2859}
2860#endif
2861
2862
Benjamin Petersonc54de472015-01-28 12:06:39 -05002863#ifdef OPENSSL_NPN_NEGOTIATED
Benjamin Petersoncca27322015-01-23 16:35:37 -05002864static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002865do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2866 const unsigned char *server_protocols, unsigned int server_protocols_len,
2867 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002868{
Benjamin Peterson88615022015-01-23 17:30:26 -05002869 int ret;
2870 if (client_protocols == NULL) {
2871 client_protocols = (unsigned char *)"";
2872 client_protocols_len = 0;
2873 }
2874 if (server_protocols == NULL) {
2875 server_protocols = (unsigned char *)"";
2876 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002877 }
2878
Benjamin Peterson88615022015-01-23 17:30:26 -05002879 ret = SSL_select_next_proto(out, outlen,
2880 server_protocols, server_protocols_len,
2881 client_protocols, client_protocols_len);
2882 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2883 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002884
2885 return SSL_TLSEXT_ERR_OK;
2886}
2887
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002888/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2889static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002890_advertiseNPN_cb(SSL *s,
2891 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002892 void *args)
2893{
2894 PySSLContext *ssl_ctx = (PySSLContext *) args;
2895
2896 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002897 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002898 *len = 0;
2899 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002900 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002901 *len = ssl_ctx->npn_protocols_len;
2902 }
2903
2904 return SSL_TLSEXT_ERR_OK;
2905}
2906/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2907static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002908_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002909 unsigned char **out, unsigned char *outlen,
2910 const unsigned char *server, unsigned int server_len,
2911 void *args)
2912{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002913 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002914 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002915 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002916}
2917#endif
2918
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002919/*[clinic input]
2920_ssl._SSLContext._set_npn_protocols
2921 protos: Py_buffer
2922 /
2923[clinic start generated code]*/
2924
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002925static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002926_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2927 Py_buffer *protos)
2928/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002929{
2930#ifdef OPENSSL_NPN_NEGOTIATED
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002931 PyMem_Free(self->npn_protocols);
2932 self->npn_protocols = PyMem_Malloc(protos->len);
2933 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002934 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002935 memcpy(self->npn_protocols, protos->buf, protos->len);
2936 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002937
2938 /* set both server and client callbacks, because the context can
2939 * be used to create both types of sockets */
2940 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2941 _advertiseNPN_cb,
2942 self);
2943 SSL_CTX_set_next_proto_select_cb(self->ctx,
2944 _selectNPN_cb,
2945 self);
2946
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002947 Py_RETURN_NONE;
2948#else
2949 PyErr_SetString(PyExc_NotImplementedError,
2950 "The NPN extension requires OpenSSL 1.0.1 or later.");
2951 return NULL;
2952#endif
2953}
2954
Benjamin Petersoncca27322015-01-23 16:35:37 -05002955#ifdef HAVE_ALPN
2956static int
2957_selectALPN_cb(SSL *s,
2958 const unsigned char **out, unsigned char *outlen,
2959 const unsigned char *client_protocols, unsigned int client_protocols_len,
2960 void *args)
2961{
2962 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002963 return do_protocol_selection(1, (unsigned char **)out, outlen,
2964 ctx->alpn_protocols, ctx->alpn_protocols_len,
2965 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002966}
2967#endif
2968
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002969/*[clinic input]
2970_ssl._SSLContext._set_alpn_protocols
2971 protos: Py_buffer
2972 /
2973[clinic start generated code]*/
2974
Benjamin Petersoncca27322015-01-23 16:35:37 -05002975static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002976_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2977 Py_buffer *protos)
2978/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002979{
2980#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03002981 if (protos->len > UINT_MAX) {
2982 PyErr_Format(PyExc_OverflowError,
2983 "protocols longer than %d bytes", UINT_MAX);
2984 return NULL;
2985 }
2986
Benjamin Petersoncca27322015-01-23 16:35:37 -05002987 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002988 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002989 if (!self->alpn_protocols)
2990 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002991 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03002992 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002993
2994 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2995 return PyErr_NoMemory();
2996 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2997
Benjamin Petersoncca27322015-01-23 16:35:37 -05002998 Py_RETURN_NONE;
2999#else
3000 PyErr_SetString(PyExc_NotImplementedError,
3001 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3002 return NULL;
3003#endif
3004}
3005
Antoine Pitrou152efa22010-05-16 18:19:27 +00003006static PyObject *
3007get_verify_mode(PySSLContext *self, void *c)
3008{
3009 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3010 case SSL_VERIFY_NONE:
3011 return PyLong_FromLong(PY_SSL_CERT_NONE);
3012 case SSL_VERIFY_PEER:
3013 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3014 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3015 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3016 }
3017 PyErr_SetString(PySSLErrorObject,
3018 "invalid return value from SSL_CTX_get_verify_mode");
3019 return NULL;
3020}
3021
3022static int
3023set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3024{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003025 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003026 if (!PyArg_Parse(arg, "i", &n))
3027 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003028 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003029 PyErr_SetString(PyExc_ValueError,
3030 "Cannot set verify_mode to CERT_NONE when "
3031 "check_hostname is enabled.");
3032 return -1;
3033 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003034 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003035}
3036
3037static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003038get_verify_flags(PySSLContext *self, void *c)
3039{
3040 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003041 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003042 unsigned long flags;
3043
3044 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003045 param = X509_STORE_get0_param(store);
3046 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003047 return PyLong_FromUnsignedLong(flags);
3048}
3049
3050static int
3051set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3052{
3053 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003054 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003055 unsigned long new_flags, flags, set, clear;
3056
3057 if (!PyArg_Parse(arg, "k", &new_flags))
3058 return -1;
3059 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003060 param = X509_STORE_get0_param(store);
3061 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003062 clear = flags & ~new_flags;
3063 set = ~flags & new_flags;
3064 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003065 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003066 _setSSLError(NULL, 0, __FILE__, __LINE__);
3067 return -1;
3068 }
3069 }
3070 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003071 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003072 _setSSLError(NULL, 0, __FILE__, __LINE__);
3073 return -1;
3074 }
3075 }
3076 return 0;
3077}
3078
3079static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003080get_options(PySSLContext *self, void *c)
3081{
3082 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3083}
3084
3085static int
3086set_options(PySSLContext *self, PyObject *arg, void *c)
3087{
3088 long new_opts, opts, set, clear;
3089 if (!PyArg_Parse(arg, "l", &new_opts))
3090 return -1;
3091 opts = SSL_CTX_get_options(self->ctx);
3092 clear = opts & ~new_opts;
3093 set = ~opts & new_opts;
3094 if (clear) {
3095#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3096 SSL_CTX_clear_options(self->ctx, clear);
3097#else
3098 PyErr_SetString(PyExc_ValueError,
3099 "can't clear options before OpenSSL 0.9.8m");
3100 return -1;
3101#endif
3102 }
3103 if (set)
3104 SSL_CTX_set_options(self->ctx, set);
3105 return 0;
3106}
3107
Christian Heimes1aa9a752013-12-02 02:41:19 +01003108static PyObject *
3109get_check_hostname(PySSLContext *self, void *c)
3110{
3111 return PyBool_FromLong(self->check_hostname);
3112}
3113
3114static int
3115set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3116{
3117 int check_hostname;
3118 if (!PyArg_Parse(arg, "p", &check_hostname))
3119 return -1;
3120 if (check_hostname &&
3121 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3122 PyErr_SetString(PyExc_ValueError,
3123 "check_hostname needs a SSL context with either "
3124 "CERT_OPTIONAL or CERT_REQUIRED");
3125 return -1;
3126 }
3127 self->check_hostname = check_hostname;
3128 return 0;
3129}
3130
3131
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003132typedef struct {
3133 PyThreadState *thread_state;
3134 PyObject *callable;
3135 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003136 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003137 int error;
3138} _PySSLPasswordInfo;
3139
3140static int
3141_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3142 const char *bad_type_error)
3143{
3144 /* Set the password and size fields of a _PySSLPasswordInfo struct
3145 from a unicode, bytes, or byte array object.
3146 The password field will be dynamically allocated and must be freed
3147 by the caller */
3148 PyObject *password_bytes = NULL;
3149 const char *data = NULL;
3150 Py_ssize_t size;
3151
3152 if (PyUnicode_Check(password)) {
3153 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3154 if (!password_bytes) {
3155 goto error;
3156 }
3157 data = PyBytes_AS_STRING(password_bytes);
3158 size = PyBytes_GET_SIZE(password_bytes);
3159 } else if (PyBytes_Check(password)) {
3160 data = PyBytes_AS_STRING(password);
3161 size = PyBytes_GET_SIZE(password);
3162 } else if (PyByteArray_Check(password)) {
3163 data = PyByteArray_AS_STRING(password);
3164 size = PyByteArray_GET_SIZE(password);
3165 } else {
3166 PyErr_SetString(PyExc_TypeError, bad_type_error);
3167 goto error;
3168 }
3169
Victor Stinner9ee02032013-06-23 15:08:23 +02003170 if (size > (Py_ssize_t)INT_MAX) {
3171 PyErr_Format(PyExc_ValueError,
3172 "password cannot be longer than %d bytes", INT_MAX);
3173 goto error;
3174 }
3175
Victor Stinner11ebff22013-07-07 17:07:52 +02003176 PyMem_Free(pw_info->password);
3177 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003178 if (!pw_info->password) {
3179 PyErr_SetString(PyExc_MemoryError,
3180 "unable to allocate password buffer");
3181 goto error;
3182 }
3183 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003184 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003185
3186 Py_XDECREF(password_bytes);
3187 return 1;
3188
3189error:
3190 Py_XDECREF(password_bytes);
3191 return 0;
3192}
3193
3194static int
3195_password_callback(char *buf, int size, int rwflag, void *userdata)
3196{
3197 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3198 PyObject *fn_ret = NULL;
3199
3200 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3201
3202 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003203 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003204 if (!fn_ret) {
3205 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3206 core python API, so we could use it to add a frame here */
3207 goto error;
3208 }
3209
3210 if (!_pwinfo_set(pw_info, fn_ret,
3211 "password callback must return a string")) {
3212 goto error;
3213 }
3214 Py_CLEAR(fn_ret);
3215 }
3216
3217 if (pw_info->size > size) {
3218 PyErr_Format(PyExc_ValueError,
3219 "password cannot be longer than %d bytes", size);
3220 goto error;
3221 }
3222
3223 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3224 memcpy(buf, pw_info->password, pw_info->size);
3225 return pw_info->size;
3226
3227error:
3228 Py_XDECREF(fn_ret);
3229 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3230 pw_info->error = 1;
3231 return -1;
3232}
3233
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003234/*[clinic input]
3235_ssl._SSLContext.load_cert_chain
3236 certfile: object
3237 keyfile: object = NULL
3238 password: object = NULL
3239
3240[clinic start generated code]*/
3241
Antoine Pitroub5218772010-05-21 09:56:06 +00003242static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003243_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3244 PyObject *keyfile, PyObject *password)
3245/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003246{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003247 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003248 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3249 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003250 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003251 int r;
3252
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003253 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003254 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003255 if (keyfile == Py_None)
3256 keyfile = NULL;
3257 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3258 PyErr_SetString(PyExc_TypeError,
3259 "certfile should be a valid filesystem path");
3260 return NULL;
3261 }
3262 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3263 PyErr_SetString(PyExc_TypeError,
3264 "keyfile should be a valid filesystem path");
3265 goto error;
3266 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003267 if (password && password != Py_None) {
3268 if (PyCallable_Check(password)) {
3269 pw_info.callable = password;
3270 } else if (!_pwinfo_set(&pw_info, password,
3271 "password should be a string or callable")) {
3272 goto error;
3273 }
3274 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3275 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3276 }
3277 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003278 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3279 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003280 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003281 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003282 if (pw_info.error) {
3283 ERR_clear_error();
3284 /* the password callback has already set the error information */
3285 }
3286 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003287 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003288 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003289 }
3290 else {
3291 _setSSLError(NULL, 0, __FILE__, __LINE__);
3292 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003293 goto error;
3294 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003295 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003296 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003297 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3298 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003299 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3300 Py_CLEAR(keyfile_bytes);
3301 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003302 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003303 if (pw_info.error) {
3304 ERR_clear_error();
3305 /* the password callback has already set the error information */
3306 }
3307 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003308 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003309 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003310 }
3311 else {
3312 _setSSLError(NULL, 0, __FILE__, __LINE__);
3313 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003314 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003315 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003316 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003318 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003319 if (r != 1) {
3320 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003321 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003322 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003323 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3324 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003325 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003326 Py_RETURN_NONE;
3327
3328error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003329 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3330 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003331 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003332 Py_XDECREF(keyfile_bytes);
3333 Py_XDECREF(certfile_bytes);
3334 return NULL;
3335}
3336
Christian Heimesefff7062013-11-21 03:35:02 +01003337/* internal helper function, returns -1 on error
3338 */
3339static int
3340_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3341 int filetype)
3342{
3343 BIO *biobuf = NULL;
3344 X509_STORE *store;
3345 int retval = 0, err, loaded = 0;
3346
3347 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3348
3349 if (len <= 0) {
3350 PyErr_SetString(PyExc_ValueError,
3351 "Empty certificate data");
3352 return -1;
3353 } else if (len > INT_MAX) {
3354 PyErr_SetString(PyExc_OverflowError,
3355 "Certificate data is too long.");
3356 return -1;
3357 }
3358
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003359 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003360 if (biobuf == NULL) {
3361 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3362 return -1;
3363 }
3364
3365 store = SSL_CTX_get_cert_store(self->ctx);
3366 assert(store != NULL);
3367
3368 while (1) {
3369 X509 *cert = NULL;
3370 int r;
3371
3372 if (filetype == SSL_FILETYPE_ASN1) {
3373 cert = d2i_X509_bio(biobuf, NULL);
3374 } else {
3375 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003376 SSL_CTX_get_default_passwd_cb(self->ctx),
3377 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3378 );
Christian Heimesefff7062013-11-21 03:35:02 +01003379 }
3380 if (cert == NULL) {
3381 break;
3382 }
3383 r = X509_STORE_add_cert(store, cert);
3384 X509_free(cert);
3385 if (!r) {
3386 err = ERR_peek_last_error();
3387 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3388 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3389 /* cert already in hash table, not an error */
3390 ERR_clear_error();
3391 } else {
3392 break;
3393 }
3394 }
3395 loaded++;
3396 }
3397
3398 err = ERR_peek_last_error();
3399 if ((filetype == SSL_FILETYPE_ASN1) &&
3400 (loaded > 0) &&
3401 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3402 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3403 /* EOF ASN1 file, not an error */
3404 ERR_clear_error();
3405 retval = 0;
3406 } else if ((filetype == SSL_FILETYPE_PEM) &&
3407 (loaded > 0) &&
3408 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3409 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3410 /* EOF PEM file, not an error */
3411 ERR_clear_error();
3412 retval = 0;
3413 } else {
3414 _setSSLError(NULL, 0, __FILE__, __LINE__);
3415 retval = -1;
3416 }
3417
3418 BIO_free(biobuf);
3419 return retval;
3420}
3421
3422
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003423/*[clinic input]
3424_ssl._SSLContext.load_verify_locations
3425 cafile: object = NULL
3426 capath: object = NULL
3427 cadata: object = NULL
3428
3429[clinic start generated code]*/
3430
Antoine Pitrou152efa22010-05-16 18:19:27 +00003431static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003432_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3433 PyObject *cafile,
3434 PyObject *capath,
3435 PyObject *cadata)
3436/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003437{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003438 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3439 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003440 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003441
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003442 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003443 if (cafile == Py_None)
3444 cafile = NULL;
3445 if (capath == Py_None)
3446 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003447 if (cadata == Py_None)
3448 cadata = NULL;
3449
3450 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003451 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003452 "cafile, capath and cadata cannot be all omitted");
3453 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003454 }
3455 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3456 PyErr_SetString(PyExc_TypeError,
3457 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003458 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003459 }
3460 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003461 PyErr_SetString(PyExc_TypeError,
3462 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003463 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003464 }
Christian Heimesefff7062013-11-21 03:35:02 +01003465
3466 /* validata cadata type and load cadata */
3467 if (cadata) {
3468 Py_buffer buf;
3469 PyObject *cadata_ascii = NULL;
3470
3471 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3472 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3473 PyBuffer_Release(&buf);
3474 PyErr_SetString(PyExc_TypeError,
3475 "cadata should be a contiguous buffer with "
3476 "a single dimension");
3477 goto error;
3478 }
3479 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3480 PyBuffer_Release(&buf);
3481 if (r == -1) {
3482 goto error;
3483 }
3484 } else {
3485 PyErr_Clear();
3486 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3487 if (cadata_ascii == NULL) {
3488 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003489 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003490 "bytes-like object");
3491 goto error;
3492 }
3493 r = _add_ca_certs(self,
3494 PyBytes_AS_STRING(cadata_ascii),
3495 PyBytes_GET_SIZE(cadata_ascii),
3496 SSL_FILETYPE_PEM);
3497 Py_DECREF(cadata_ascii);
3498 if (r == -1) {
3499 goto error;
3500 }
3501 }
3502 }
3503
3504 /* load cafile or capath */
3505 if (cafile || capath) {
3506 if (cafile)
3507 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3508 if (capath)
3509 capath_buf = PyBytes_AS_STRING(capath_bytes);
3510 PySSL_BEGIN_ALLOW_THREADS
3511 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3512 PySSL_END_ALLOW_THREADS
3513 if (r != 1) {
3514 ok = 0;
3515 if (errno != 0) {
3516 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003517 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003518 }
3519 else {
3520 _setSSLError(NULL, 0, __FILE__, __LINE__);
3521 }
3522 goto error;
3523 }
3524 }
3525 goto end;
3526
3527 error:
3528 ok = 0;
3529 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003530 Py_XDECREF(cafile_bytes);
3531 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003532 if (ok) {
3533 Py_RETURN_NONE;
3534 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003535 return NULL;
3536 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003537}
3538
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003539/*[clinic input]
3540_ssl._SSLContext.load_dh_params
3541 path as filepath: object
3542 /
3543
3544[clinic start generated code]*/
3545
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003547_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3548/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003549{
3550 FILE *f;
3551 DH *dh;
3552
Victor Stinnerdaf45552013-08-28 00:53:59 +02003553 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003554 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003555 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003556
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003557 errno = 0;
3558 PySSL_BEGIN_ALLOW_THREADS
3559 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003560 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003561 PySSL_END_ALLOW_THREADS
3562 if (dh == NULL) {
3563 if (errno != 0) {
3564 ERR_clear_error();
3565 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3566 }
3567 else {
3568 _setSSLError(NULL, 0, __FILE__, __LINE__);
3569 }
3570 return NULL;
3571 }
3572 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3573 _setSSLError(NULL, 0, __FILE__, __LINE__);
3574 DH_free(dh);
3575 Py_RETURN_NONE;
3576}
3577
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003578/*[clinic input]
3579_ssl._SSLContext._wrap_socket
3580 sock: object(subclass_of="PySocketModule.Sock_Type")
3581 server_side: int
3582 server_hostname as hostname_obj: object = None
3583
3584[clinic start generated code]*/
3585
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003586static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003587_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3588 int server_side, PyObject *hostname_obj)
3589/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003590{
Antoine Pitroud5323212010-10-22 18:19:07 +00003591 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003592 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003593
Antoine Pitroud5323212010-10-22 18:19:07 +00003594 /* server_hostname is either None (or absent), or to be encoded
3595 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003596 if (hostname_obj != Py_None) {
3597 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003598 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003599 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003600
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003601 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3602 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003603 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003604 if (hostname != NULL)
3605 PyMem_Free(hostname);
3606 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003607}
3608
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003609/*[clinic input]
3610_ssl._SSLContext._wrap_bio
3611 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3612 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3613 server_side: int
3614 server_hostname as hostname_obj: object = None
3615
3616[clinic start generated code]*/
3617
Antoine Pitroub0182c82010-10-12 20:09:02 +00003618static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003619_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3620 PySSLMemoryBIO *outgoing, int server_side,
3621 PyObject *hostname_obj)
3622/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003623{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003624 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003625 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626
3627 /* server_hostname is either None (or absent), or to be encoded
3628 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003629 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003630 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3631 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003632 }
3633
3634 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3635 incoming, outgoing);
3636
3637 PyMem_Free(hostname);
3638 return res;
3639}
3640
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003641/*[clinic input]
3642_ssl._SSLContext.session_stats
3643[clinic start generated code]*/
3644
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003645static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003646_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3647/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003648{
3649 int r;
3650 PyObject *value, *stats = PyDict_New();
3651 if (!stats)
3652 return NULL;
3653
3654#define ADD_STATS(SSL_NAME, KEY_NAME) \
3655 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3656 if (value == NULL) \
3657 goto error; \
3658 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3659 Py_DECREF(value); \
3660 if (r < 0) \
3661 goto error;
3662
3663 ADD_STATS(number, "number");
3664 ADD_STATS(connect, "connect");
3665 ADD_STATS(connect_good, "connect_good");
3666 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3667 ADD_STATS(accept, "accept");
3668 ADD_STATS(accept_good, "accept_good");
3669 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3670 ADD_STATS(accept, "accept");
3671 ADD_STATS(hits, "hits");
3672 ADD_STATS(misses, "misses");
3673 ADD_STATS(timeouts, "timeouts");
3674 ADD_STATS(cache_full, "cache_full");
3675
3676#undef ADD_STATS
3677
3678 return stats;
3679
3680error:
3681 Py_DECREF(stats);
3682 return NULL;
3683}
3684
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003685/*[clinic input]
3686_ssl._SSLContext.set_default_verify_paths
3687[clinic start generated code]*/
3688
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003689static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003690_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3691/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003692{
3693 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3694 _setSSLError(NULL, 0, __FILE__, __LINE__);
3695 return NULL;
3696 }
3697 Py_RETURN_NONE;
3698}
3699
Antoine Pitrou501da612011-12-21 09:27:41 +01003700#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003701/*[clinic input]
3702_ssl._SSLContext.set_ecdh_curve
3703 name: object
3704 /
3705
3706[clinic start generated code]*/
3707
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003708static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003709_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3710/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003711{
3712 PyObject *name_bytes;
3713 int nid;
3714 EC_KEY *key;
3715
3716 if (!PyUnicode_FSConverter(name, &name_bytes))
3717 return NULL;
3718 assert(PyBytes_Check(name_bytes));
3719 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3720 Py_DECREF(name_bytes);
3721 if (nid == 0) {
3722 PyErr_Format(PyExc_ValueError,
3723 "unknown elliptic curve name %R", name);
3724 return NULL;
3725 }
3726 key = EC_KEY_new_by_curve_name(nid);
3727 if (key == NULL) {
3728 _setSSLError(NULL, 0, __FILE__, __LINE__);
3729 return NULL;
3730 }
3731 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3732 EC_KEY_free(key);
3733 Py_RETURN_NONE;
3734}
Antoine Pitrou501da612011-12-21 09:27:41 +01003735#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003736
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003737#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003738static int
3739_servername_callback(SSL *s, int *al, void *args)
3740{
3741 int ret;
3742 PySSLContext *ssl_ctx = (PySSLContext *) args;
3743 PySSLSocket *ssl;
3744 PyObject *servername_o;
3745 PyObject *servername_idna;
3746 PyObject *result;
3747 /* The high-level ssl.SSLSocket object */
3748 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003749 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003750#ifdef WITH_THREAD
3751 PyGILState_STATE gstate = PyGILState_Ensure();
3752#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003753
3754 if (ssl_ctx->set_hostname == NULL) {
3755 /* remove race condition in this the call back while if removing the
3756 * callback is in progress */
Stefan Krah20d60802013-01-17 17:07:17 +01003757#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003758 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003759#endif
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003760 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003761 }
3762
3763 ssl = SSL_get_app_data(s);
3764 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003765
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003766 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003767 * SSL connection and that has a .context attribute that can be changed to
3768 * identify the requested hostname. Since the official API is the Python
3769 * level API we want to pass the callback a Python level object rather than
3770 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3771 * SSLObject) that will be passed. Otherwise if there's a socket then that
3772 * will be passed. If both do not exist only then the C-level object is
3773 * passed. */
3774 if (ssl->owner)
3775 ssl_socket = PyWeakref_GetObject(ssl->owner);
3776 else if (ssl->Socket)
3777 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3778 else
3779 ssl_socket = (PyObject *) ssl;
3780
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003781 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003782 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003783 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003784
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003785 if (servername == NULL) {
3786 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3787 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003788 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003789 else {
3790 servername_o = PyBytes_FromString(servername);
3791 if (servername_o == NULL) {
3792 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3793 goto error;
3794 }
3795 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3796 if (servername_idna == NULL) {
3797 PyErr_WriteUnraisable(servername_o);
3798 Py_DECREF(servername_o);
3799 goto error;
3800 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003801 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003802 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3803 servername_idna, ssl_ctx, NULL);
3804 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003805 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003806 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003807
3808 if (result == NULL) {
3809 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3810 *al = SSL_AD_HANDSHAKE_FAILURE;
3811 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3812 }
3813 else {
3814 if (result != Py_None) {
3815 *al = (int) PyLong_AsLong(result);
3816 if (PyErr_Occurred()) {
3817 PyErr_WriteUnraisable(result);
3818 *al = SSL_AD_INTERNAL_ERROR;
3819 }
3820 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3821 }
3822 else {
3823 ret = SSL_TLSEXT_ERR_OK;
3824 }
3825 Py_DECREF(result);
3826 }
3827
Stefan Krah20d60802013-01-17 17:07:17 +01003828#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003829 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003830#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003831 return ret;
3832
3833error:
3834 Py_DECREF(ssl_socket);
3835 *al = SSL_AD_INTERNAL_ERROR;
3836 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
Stefan Krah20d60802013-01-17 17:07:17 +01003837#ifdef WITH_THREAD
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003838 PyGILState_Release(gstate);
Stefan Krah20d60802013-01-17 17:07:17 +01003839#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003840 return ret;
3841}
Antoine Pitroua5963382013-03-30 16:39:00 +01003842#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003843
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003844/*[clinic input]
3845_ssl._SSLContext.set_servername_callback
3846 method as cb: object
3847 /
3848
3849Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3850
3851If the argument is None then the callback is disabled. The method is called
3852with the SSLSocket, the server name as a string, and the SSLContext object.
3853See RFC 6066 for details of the SNI extension.
3854[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003855
3856static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003857_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3858/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003859{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003860#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003861 Py_CLEAR(self->set_hostname);
3862 if (cb == Py_None) {
3863 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3864 }
3865 else {
3866 if (!PyCallable_Check(cb)) {
3867 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3868 PyErr_SetString(PyExc_TypeError,
3869 "not a callable object");
3870 return NULL;
3871 }
3872 Py_INCREF(cb);
3873 self->set_hostname = cb;
3874 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3875 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3876 }
3877 Py_RETURN_NONE;
3878#else
3879 PyErr_SetString(PyExc_NotImplementedError,
3880 "The TLS extension servername callback, "
3881 "SSL_CTX_set_tlsext_servername_callback, "
3882 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003883 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003884#endif
3885}
3886
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003887/*[clinic input]
3888_ssl._SSLContext.cert_store_stats
3889
3890Returns quantities of loaded X.509 certificates.
3891
3892X.509 certificates with a CA extension and certificate revocation lists
3893inside the context's cert store.
3894
3895NOTE: Certificates in a capath directory aren't loaded unless they have
3896been used at least once.
3897[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003898
3899static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003900_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3901/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003902{
3903 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003904 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003905 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003906 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003907
3908 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003909 objs = X509_STORE_get0_objects(store);
3910 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3911 obj = sk_X509_OBJECT_value(objs, i);
3912 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003913 case X509_LU_X509:
3914 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003915 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003916 ca++;
3917 }
3918 break;
3919 case X509_LU_CRL:
3920 crl++;
3921 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003922 default:
3923 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3924 * As far as I can tell they are internal states and never
3925 * stored in a cert store */
3926 break;
3927 }
3928 }
3929 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3930 "x509_ca", ca);
3931}
3932
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003933/*[clinic input]
3934_ssl._SSLContext.get_ca_certs
3935 binary_form: bool = False
3936
3937Returns a list of dicts with information of loaded CA certs.
3938
3939If the optional argument is True, returns a DER-encoded copy of the CA
3940certificate.
3941
3942NOTE: Certificates in a capath directory aren't loaded unless they have
3943been used at least once.
3944[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003945
3946static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003947_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3948/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003949{
3950 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003951 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003952 PyObject *ci = NULL, *rlist = NULL;
3953 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003954
3955 if ((rlist = PyList_New(0)) == NULL) {
3956 return NULL;
3957 }
3958
3959 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003960 objs = X509_STORE_get0_objects(store);
3961 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003962 X509_OBJECT *obj;
3963 X509 *cert;
3964
Christian Heimes598894f2016-09-05 23:19:05 +02003965 obj = sk_X509_OBJECT_value(objs, i);
3966 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003967 /* not a x509 cert */
3968 continue;
3969 }
3970 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003971 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003972 if (!X509_check_ca(cert)) {
3973 continue;
3974 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003975 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003976 ci = _certificate_to_der(cert);
3977 } else {
3978 ci = _decode_certificate(cert);
3979 }
3980 if (ci == NULL) {
3981 goto error;
3982 }
3983 if (PyList_Append(rlist, ci) == -1) {
3984 goto error;
3985 }
3986 Py_CLEAR(ci);
3987 }
3988 return rlist;
3989
3990 error:
3991 Py_XDECREF(ci);
3992 Py_XDECREF(rlist);
3993 return NULL;
3994}
3995
3996
Antoine Pitrou152efa22010-05-16 18:19:27 +00003997static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003998 {"check_hostname", (getter) get_check_hostname,
3999 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004000 {"options", (getter) get_options,
4001 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004002 {"verify_flags", (getter) get_verify_flags,
4003 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004004 {"verify_mode", (getter) get_verify_mode,
4005 (setter) set_verify_mode, NULL},
4006 {NULL}, /* sentinel */
4007};
4008
4009static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004010 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4011 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4012 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4013 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4014 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4015 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4016 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4017 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4018 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4019 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4020 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4021 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4022 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4023 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004024 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004025 {NULL, NULL} /* sentinel */
4026};
4027
4028static PyTypeObject PySSLContext_Type = {
4029 PyVarObject_HEAD_INIT(NULL, 0)
4030 "_ssl._SSLContext", /*tp_name*/
4031 sizeof(PySSLContext), /*tp_basicsize*/
4032 0, /*tp_itemsize*/
4033 (destructor)context_dealloc, /*tp_dealloc*/
4034 0, /*tp_print*/
4035 0, /*tp_getattr*/
4036 0, /*tp_setattr*/
4037 0, /*tp_reserved*/
4038 0, /*tp_repr*/
4039 0, /*tp_as_number*/
4040 0, /*tp_as_sequence*/
4041 0, /*tp_as_mapping*/
4042 0, /*tp_hash*/
4043 0, /*tp_call*/
4044 0, /*tp_str*/
4045 0, /*tp_getattro*/
4046 0, /*tp_setattro*/
4047 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004048 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004049 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004050 (traverseproc) context_traverse, /*tp_traverse*/
4051 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004052 0, /*tp_richcompare*/
4053 0, /*tp_weaklistoffset*/
4054 0, /*tp_iter*/
4055 0, /*tp_iternext*/
4056 context_methods, /*tp_methods*/
4057 0, /*tp_members*/
4058 context_getsetlist, /*tp_getset*/
4059 0, /*tp_base*/
4060 0, /*tp_dict*/
4061 0, /*tp_descr_get*/
4062 0, /*tp_descr_set*/
4063 0, /*tp_dictoffset*/
4064 0, /*tp_init*/
4065 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004066 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004067};
4068
4069
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004070/*
4071 * MemoryBIO objects
4072 */
4073
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004074/*[clinic input]
4075@classmethod
4076_ssl.MemoryBIO.__new__
4077
4078[clinic start generated code]*/
4079
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004080static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004081_ssl_MemoryBIO_impl(PyTypeObject *type)
4082/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004083{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004084 BIO *bio;
4085 PySSLMemoryBIO *self;
4086
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004087 bio = BIO_new(BIO_s_mem());
4088 if (bio == NULL) {
4089 PyErr_SetString(PySSLErrorObject,
4090 "failed to allocate BIO");
4091 return NULL;
4092 }
4093 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4094 * just that no data is currently available. The SSL routines should retry
4095 * the read, which we can achieve by calling BIO_set_retry_read(). */
4096 BIO_set_retry_read(bio);
4097 BIO_set_mem_eof_return(bio, -1);
4098
4099 assert(type != NULL && type->tp_alloc != NULL);
4100 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4101 if (self == NULL) {
4102 BIO_free(bio);
4103 return NULL;
4104 }
4105 self->bio = bio;
4106 self->eof_written = 0;
4107
4108 return (PyObject *) self;
4109}
4110
4111static void
4112memory_bio_dealloc(PySSLMemoryBIO *self)
4113{
4114 BIO_free(self->bio);
4115 Py_TYPE(self)->tp_free(self);
4116}
4117
4118static PyObject *
4119memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4120{
Segev Finer5cff6372017-07-27 01:19:17 +03004121 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004122}
4123
4124PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4125"The number of bytes pending in the memory BIO.");
4126
4127static PyObject *
4128memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4129{
4130 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4131 && self->eof_written);
4132}
4133
4134PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4135"Whether the memory BIO is at EOF.");
4136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004137/*[clinic input]
4138_ssl.MemoryBIO.read
4139 size as len: int = -1
4140 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004141
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004142Read up to size bytes from the memory BIO.
4143
4144If size is not specified, read the entire buffer.
4145If the return value is an empty bytes instance, this means either
4146EOF or that no data is available. Use the "eof" property to
4147distinguish between the two.
4148[clinic start generated code]*/
4149
4150static PyObject *
4151_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4152/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4153{
4154 int avail, nbytes;
4155 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004156
Segev Finer5cff6372017-07-27 01:19:17 +03004157 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004158 if ((len < 0) || (len > avail))
4159 len = avail;
4160
4161 result = PyBytes_FromStringAndSize(NULL, len);
4162 if ((result == NULL) || (len == 0))
4163 return result;
4164
4165 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4166 /* There should never be any short reads but check anyway. */
4167 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4168 Py_DECREF(result);
4169 return NULL;
4170 }
4171
4172 return result;
4173}
4174
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004175/*[clinic input]
4176_ssl.MemoryBIO.write
4177 b: Py_buffer
4178 /
4179
4180Writes the bytes b into the memory BIO.
4181
4182Returns the number of bytes written.
4183[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184
4185static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004186_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4187/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004188{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004189 int nbytes;
4190
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004191 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004192 PyErr_Format(PyExc_OverflowError,
4193 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195 }
4196
4197 if (self->eof_written) {
4198 PyErr_SetString(PySSLErrorObject,
4199 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004200 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 }
4202
Segev Finer5cff6372017-07-27 01:19:17 +03004203 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004204 if (nbytes < 0) {
4205 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004206 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004207 }
4208
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004209 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004210}
4211
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004212/*[clinic input]
4213_ssl.MemoryBIO.write_eof
4214
4215Write an EOF marker to the memory BIO.
4216
4217When all data has been read, the "eof" property will be True.
4218[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004219
4220static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004221_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4222/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004223{
4224 self->eof_written = 1;
4225 /* After an EOF is written, a zero return from read() should be a real EOF
4226 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4227 BIO_clear_retry_flags(self->bio);
4228 BIO_set_mem_eof_return(self->bio, 0);
4229
4230 Py_RETURN_NONE;
4231}
4232
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004233static PyGetSetDef memory_bio_getsetlist[] = {
4234 {"pending", (getter) memory_bio_get_pending, NULL,
4235 PySSL_memory_bio_pending_doc},
4236 {"eof", (getter) memory_bio_get_eof, NULL,
4237 PySSL_memory_bio_eof_doc},
4238 {NULL}, /* sentinel */
4239};
4240
4241static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004242 _SSL_MEMORYBIO_READ_METHODDEF
4243 _SSL_MEMORYBIO_WRITE_METHODDEF
4244 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004245 {NULL, NULL} /* sentinel */
4246};
4247
4248static PyTypeObject PySSLMemoryBIO_Type = {
4249 PyVarObject_HEAD_INIT(NULL, 0)
4250 "_ssl.MemoryBIO", /*tp_name*/
4251 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4252 0, /*tp_itemsize*/
4253 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4254 0, /*tp_print*/
4255 0, /*tp_getattr*/
4256 0, /*tp_setattr*/
4257 0, /*tp_reserved*/
4258 0, /*tp_repr*/
4259 0, /*tp_as_number*/
4260 0, /*tp_as_sequence*/
4261 0, /*tp_as_mapping*/
4262 0, /*tp_hash*/
4263 0, /*tp_call*/
4264 0, /*tp_str*/
4265 0, /*tp_getattro*/
4266 0, /*tp_setattro*/
4267 0, /*tp_as_buffer*/
4268 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4269 0, /*tp_doc*/
4270 0, /*tp_traverse*/
4271 0, /*tp_clear*/
4272 0, /*tp_richcompare*/
4273 0, /*tp_weaklistoffset*/
4274 0, /*tp_iter*/
4275 0, /*tp_iternext*/
4276 memory_bio_methods, /*tp_methods*/
4277 0, /*tp_members*/
4278 memory_bio_getsetlist, /*tp_getset*/
4279 0, /*tp_base*/
4280 0, /*tp_dict*/
4281 0, /*tp_descr_get*/
4282 0, /*tp_descr_set*/
4283 0, /*tp_dictoffset*/
4284 0, /*tp_init*/
4285 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004286 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004287};
4288
Antoine Pitrou152efa22010-05-16 18:19:27 +00004289
Christian Heimes99a65702016-09-10 23:44:53 +02004290/*
4291 * SSL Session object
4292 */
4293
4294static void
4295PySSLSession_dealloc(PySSLSession *self)
4296{
INADA Naokia6296d32017-08-24 14:55:17 +09004297 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004298 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004299 Py_XDECREF(self->ctx);
4300 if (self->session != NULL) {
4301 SSL_SESSION_free(self->session);
4302 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004303 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004304}
4305
4306static PyObject *
4307PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4308{
4309 int result;
4310
4311 if (left == NULL || right == NULL) {
4312 PyErr_BadInternalCall();
4313 return NULL;
4314 }
4315
4316 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4317 Py_RETURN_NOTIMPLEMENTED;
4318 }
4319
4320 if (left == right) {
4321 result = 0;
4322 } else {
4323 const unsigned char *left_id, *right_id;
4324 unsigned int left_len, right_len;
4325 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4326 &left_len);
4327 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4328 &right_len);
4329 if (left_len == right_len) {
4330 result = memcmp(left_id, right_id, left_len);
4331 } else {
4332 result = 1;
4333 }
4334 }
4335
4336 switch (op) {
4337 case Py_EQ:
4338 if (result == 0) {
4339 Py_RETURN_TRUE;
4340 } else {
4341 Py_RETURN_FALSE;
4342 }
4343 break;
4344 case Py_NE:
4345 if (result != 0) {
4346 Py_RETURN_TRUE;
4347 } else {
4348 Py_RETURN_FALSE;
4349 }
4350 break;
4351 case Py_LT:
4352 case Py_LE:
4353 case Py_GT:
4354 case Py_GE:
4355 Py_RETURN_NOTIMPLEMENTED;
4356 break;
4357 default:
4358 PyErr_BadArgument();
4359 return NULL;
4360 }
4361}
4362
4363static int
4364PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4365{
4366 Py_VISIT(self->ctx);
4367 return 0;
4368}
4369
4370static int
4371PySSLSession_clear(PySSLSession *self)
4372{
4373 Py_CLEAR(self->ctx);
4374 return 0;
4375}
4376
4377
4378static PyObject *
4379PySSLSession_get_time(PySSLSession *self, void *closure) {
4380 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4381}
4382
4383PyDoc_STRVAR(PySSLSession_get_time_doc,
4384"Session creation time (seconds since epoch).");
4385
4386
4387static PyObject *
4388PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4389 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4390}
4391
4392PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4393"Session timeout (delta in seconds).");
4394
4395
4396static PyObject *
4397PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4398 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4399 return PyLong_FromUnsignedLong(hint);
4400}
4401
4402PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4403"Ticket life time hint.");
4404
4405
4406static PyObject *
4407PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4408 const unsigned char *id;
4409 unsigned int len;
4410 id = SSL_SESSION_get_id(self->session, &len);
4411 return PyBytes_FromStringAndSize((const char *)id, len);
4412}
4413
4414PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4415"Session id");
4416
4417
4418static PyObject *
4419PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4420 if (SSL_SESSION_has_ticket(self->session)) {
4421 Py_RETURN_TRUE;
4422 } else {
4423 Py_RETURN_FALSE;
4424 }
4425}
4426
4427PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4428"Does the session contain a ticket?");
4429
4430
4431static PyGetSetDef PySSLSession_getsetlist[] = {
4432 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4433 PySSLSession_get_has_ticket_doc},
4434 {"id", (getter) PySSLSession_get_session_id, NULL,
4435 PySSLSession_get_session_id_doc},
4436 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4437 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4438 {"time", (getter) PySSLSession_get_time, NULL,
4439 PySSLSession_get_time_doc},
4440 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4441 PySSLSession_get_timeout_doc},
4442 {NULL}, /* sentinel */
4443};
4444
4445static PyTypeObject PySSLSession_Type = {
4446 PyVarObject_HEAD_INIT(NULL, 0)
4447 "_ssl.Session", /*tp_name*/
4448 sizeof(PySSLSession), /*tp_basicsize*/
4449 0, /*tp_itemsize*/
4450 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4451 0, /*tp_print*/
4452 0, /*tp_getattr*/
4453 0, /*tp_setattr*/
4454 0, /*tp_reserved*/
4455 0, /*tp_repr*/
4456 0, /*tp_as_number*/
4457 0, /*tp_as_sequence*/
4458 0, /*tp_as_mapping*/
4459 0, /*tp_hash*/
4460 0, /*tp_call*/
4461 0, /*tp_str*/
4462 0, /*tp_getattro*/
4463 0, /*tp_setattro*/
4464 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004465 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004466 0, /*tp_doc*/
4467 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4468 (inquiry)PySSLSession_clear, /*tp_clear*/
4469 PySSLSession_richcompare, /*tp_richcompare*/
4470 0, /*tp_weaklistoffset*/
4471 0, /*tp_iter*/
4472 0, /*tp_iternext*/
4473 0, /*tp_methods*/
4474 0, /*tp_members*/
4475 PySSLSession_getsetlist, /*tp_getset*/
4476};
4477
4478
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004479/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004480/*[clinic input]
4481_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004482 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004483 entropy: double
4484 /
4485
4486Mix string into the OpenSSL PRNG state.
4487
4488entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304489string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004490[clinic start generated code]*/
4491
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004492static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004493_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004494/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004495{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004496 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004497 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004498
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004499 buf = (const char *)view->buf;
4500 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004501 do {
4502 written = Py_MIN(len, INT_MAX);
4503 RAND_add(buf, (int)written, entropy);
4504 buf += written;
4505 len -= written;
4506 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004507 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004508}
4509
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004510static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004511PySSL_RAND(int len, int pseudo)
4512{
4513 int ok;
4514 PyObject *bytes;
4515 unsigned long err;
4516 const char *errstr;
4517 PyObject *v;
4518
Victor Stinner1e81a392013-12-19 16:47:04 +01004519 if (len < 0) {
4520 PyErr_SetString(PyExc_ValueError, "num must be positive");
4521 return NULL;
4522 }
4523
Victor Stinner99c8b162011-05-24 12:05:19 +02004524 bytes = PyBytes_FromStringAndSize(NULL, len);
4525 if (bytes == NULL)
4526 return NULL;
4527 if (pseudo) {
4528 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4529 if (ok == 0 || ok == 1)
4530 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4531 }
4532 else {
4533 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4534 if (ok == 1)
4535 return bytes;
4536 }
4537 Py_DECREF(bytes);
4538
4539 err = ERR_get_error();
4540 errstr = ERR_reason_error_string(err);
4541 v = Py_BuildValue("(ks)", err, errstr);
4542 if (v != NULL) {
4543 PyErr_SetObject(PySSLErrorObject, v);
4544 Py_DECREF(v);
4545 }
4546 return NULL;
4547}
4548
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004549/*[clinic input]
4550_ssl.RAND_bytes
4551 n: int
4552 /
4553
4554Generate n cryptographically strong pseudo-random bytes.
4555[clinic start generated code]*/
4556
Victor Stinner99c8b162011-05-24 12:05:19 +02004557static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004558_ssl_RAND_bytes_impl(PyObject *module, int n)
4559/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004560{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004561 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004562}
4563
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004564/*[clinic input]
4565_ssl.RAND_pseudo_bytes
4566 n: int
4567 /
4568
4569Generate n pseudo-random bytes.
4570
4571Return a pair (bytes, is_cryptographic). is_cryptographic is True
4572if the bytes generated are cryptographically strong.
4573[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004574
4575static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004576_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4577/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004578{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004579 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004580}
4581
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004582/*[clinic input]
4583_ssl.RAND_status
4584
4585Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4586
4587It is necessary to seed the PRNG with RAND_add() on some platforms before
4588using the ssl() function.
4589[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004590
4591static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004592_ssl_RAND_status_impl(PyObject *module)
4593/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004594{
Christian Heimes217cfd12007-12-02 14:31:20 +00004595 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004596}
4597
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004598#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004599/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004600/*[clinic input]
4601_ssl.RAND_egd
4602 path: object(converter="PyUnicode_FSConverter")
4603 /
4604
4605Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4606
4607Returns number of bytes read. Raises SSLError if connection to EGD
4608fails or if it does not provide enough data to seed PRNG.
4609[clinic start generated code]*/
4610
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004611static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004612_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4613/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004614{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004615 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004616 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004617 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004618 PyErr_SetString(PySSLErrorObject,
4619 "EGD connection failed or EGD did not return "
4620 "enough data to seed the PRNG");
4621 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004622 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004623 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004624}
Christian Heimesa5d07652016-09-24 10:48:05 +02004625/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004626#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004627
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004628
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004629
4630/*[clinic input]
4631_ssl.get_default_verify_paths
4632
4633Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4634
4635The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4636[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004637
4638static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004639_ssl_get_default_verify_paths_impl(PyObject *module)
4640/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004641{
4642 PyObject *ofile_env = NULL;
4643 PyObject *ofile = NULL;
4644 PyObject *odir_env = NULL;
4645 PyObject *odir = NULL;
4646
Benjamin Petersond113c962015-07-18 10:59:13 -07004647#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004648 const char *tmp = (info); \
4649 target = NULL; \
4650 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4651 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4652 target = PyBytes_FromString(tmp); } \
4653 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004654 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004655
Benjamin Petersond113c962015-07-18 10:59:13 -07004656 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4657 CONVERT(X509_get_default_cert_file(), ofile);
4658 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4659 CONVERT(X509_get_default_cert_dir(), odir);
4660#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004661
Christian Heimes200bb1b2013-06-14 15:14:29 +02004662 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004663
4664 error:
4665 Py_XDECREF(ofile_env);
4666 Py_XDECREF(ofile);
4667 Py_XDECREF(odir_env);
4668 Py_XDECREF(odir);
4669 return NULL;
4670}
4671
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004672static PyObject*
4673asn1obj2py(ASN1_OBJECT *obj)
4674{
4675 int nid;
4676 const char *ln, *sn;
4677 char buf[100];
Victor Stinnercd752982014-07-07 21:52:29 +02004678 Py_ssize_t buflen;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004679
4680 nid = OBJ_obj2nid(obj);
4681 if (nid == NID_undef) {
4682 PyErr_Format(PyExc_ValueError, "Unknown object");
4683 return NULL;
4684 }
4685 sn = OBJ_nid2sn(nid);
4686 ln = OBJ_nid2ln(nid);
4687 buflen = OBJ_obj2txt(buf, sizeof(buf), obj, 1);
4688 if (buflen < 0) {
4689 _setSSLError(NULL, 0, __FILE__, __LINE__);
4690 return NULL;
4691 }
4692 if (buflen) {
4693 return Py_BuildValue("isss#", nid, sn, ln, buf, buflen);
4694 } else {
4695 return Py_BuildValue("issO", nid, sn, ln, Py_None);
4696 }
4697}
4698
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004699/*[clinic input]
4700_ssl.txt2obj
4701 txt: str
4702 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004703
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004704Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4705
4706By default objects are looked up by OID. With name=True short and
4707long name are also matched.
4708[clinic start generated code]*/
4709
4710static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004711_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4712/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004713{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004714 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004715 ASN1_OBJECT *obj;
4716
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004717 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4718 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004719 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004720 return NULL;
4721 }
4722 result = asn1obj2py(obj);
4723 ASN1_OBJECT_free(obj);
4724 return result;
4725}
4726
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004727/*[clinic input]
4728_ssl.nid2obj
4729 nid: int
4730 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004731
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004732Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4733[clinic start generated code]*/
4734
4735static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004736_ssl_nid2obj_impl(PyObject *module, int nid)
4737/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004738{
4739 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004740 ASN1_OBJECT *obj;
4741
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004742 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004743 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004744 return NULL;
4745 }
4746 obj = OBJ_nid2obj(nid);
4747 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004748 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004749 return NULL;
4750 }
4751 result = asn1obj2py(obj);
4752 ASN1_OBJECT_free(obj);
4753 return result;
4754}
4755
Christian Heimes46bebee2013-06-09 19:03:31 +02004756#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004757
4758static PyObject*
4759certEncodingType(DWORD encodingType)
4760{
4761 static PyObject *x509_asn = NULL;
4762 static PyObject *pkcs_7_asn = NULL;
4763
4764 if (x509_asn == NULL) {
4765 x509_asn = PyUnicode_InternFromString("x509_asn");
4766 if (x509_asn == NULL)
4767 return NULL;
4768 }
4769 if (pkcs_7_asn == NULL) {
4770 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4771 if (pkcs_7_asn == NULL)
4772 return NULL;
4773 }
4774 switch(encodingType) {
4775 case X509_ASN_ENCODING:
4776 Py_INCREF(x509_asn);
4777 return x509_asn;
4778 case PKCS_7_ASN_ENCODING:
4779 Py_INCREF(pkcs_7_asn);
4780 return pkcs_7_asn;
4781 default:
4782 return PyLong_FromLong(encodingType);
4783 }
4784}
4785
4786static PyObject*
4787parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4788{
4789 CERT_ENHKEY_USAGE *usage;
4790 DWORD size, error, i;
4791 PyObject *retval;
4792
4793 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4794 error = GetLastError();
4795 if (error == CRYPT_E_NOT_FOUND) {
4796 Py_RETURN_TRUE;
4797 }
4798 return PyErr_SetFromWindowsErr(error);
4799 }
4800
4801 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4802 if (usage == NULL) {
4803 return PyErr_NoMemory();
4804 }
4805
4806 /* Now get the actual enhanced usage property */
4807 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4808 PyMem_Free(usage);
4809 error = GetLastError();
4810 if (error == CRYPT_E_NOT_FOUND) {
4811 Py_RETURN_TRUE;
4812 }
4813 return PyErr_SetFromWindowsErr(error);
4814 }
4815 retval = PySet_New(NULL);
4816 if (retval == NULL) {
4817 goto error;
4818 }
4819 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4820 if (usage->rgpszUsageIdentifier[i]) {
4821 PyObject *oid;
4822 int err;
4823 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4824 if (oid == NULL) {
4825 Py_CLEAR(retval);
4826 goto error;
4827 }
4828 err = PySet_Add(retval, oid);
4829 Py_DECREF(oid);
4830 if (err == -1) {
4831 Py_CLEAR(retval);
4832 goto error;
4833 }
4834 }
4835 }
4836 error:
4837 PyMem_Free(usage);
4838 return retval;
4839}
4840
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004841/*[clinic input]
4842_ssl.enum_certificates
4843 store_name: str
4844
4845Retrieve certificates from Windows' cert store.
4846
4847store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4848more cert storages, too. The function returns a list of (bytes,
4849encoding_type, trust) tuples. The encoding_type flag can be interpreted
4850with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4851a set of OIDs or the boolean True.
4852[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004853
Christian Heimes46bebee2013-06-09 19:03:31 +02004854static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004855_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4856/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004857{
Christian Heimes46bebee2013-06-09 19:03:31 +02004858 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004859 PCCERT_CONTEXT pCertCtx = NULL;
4860 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004861 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004862
Christian Heimes44109d72013-11-22 01:51:30 +01004863 result = PyList_New(0);
4864 if (result == NULL) {
4865 return NULL;
4866 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004867 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4868 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4869 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004870 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004871 Py_DECREF(result);
4872 return PyErr_SetFromWindowsErr(GetLastError());
4873 }
4874
Christian Heimes44109d72013-11-22 01:51:30 +01004875 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4876 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4877 pCertCtx->cbCertEncoded);
4878 if (!cert) {
4879 Py_CLEAR(result);
4880 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004881 }
Christian Heimes44109d72013-11-22 01:51:30 +01004882 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4883 Py_CLEAR(result);
4884 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004885 }
Christian Heimes44109d72013-11-22 01:51:30 +01004886 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4887 if (keyusage == Py_True) {
4888 Py_DECREF(keyusage);
4889 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004890 }
Christian Heimes44109d72013-11-22 01:51:30 +01004891 if (keyusage == NULL) {
4892 Py_CLEAR(result);
4893 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004894 }
Christian Heimes44109d72013-11-22 01:51:30 +01004895 if ((tup = PyTuple_New(3)) == NULL) {
4896 Py_CLEAR(result);
4897 break;
4898 }
4899 PyTuple_SET_ITEM(tup, 0, cert);
4900 cert = NULL;
4901 PyTuple_SET_ITEM(tup, 1, enc);
4902 enc = NULL;
4903 PyTuple_SET_ITEM(tup, 2, keyusage);
4904 keyusage = NULL;
4905 if (PyList_Append(result, tup) < 0) {
4906 Py_CLEAR(result);
4907 break;
4908 }
4909 Py_CLEAR(tup);
4910 }
4911 if (pCertCtx) {
4912 /* loop ended with an error, need to clean up context manually */
4913 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004914 }
4915
4916 /* In error cases cert, enc and tup may not be NULL */
4917 Py_XDECREF(cert);
4918 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004919 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004920 Py_XDECREF(tup);
4921
4922 if (!CertCloseStore(hStore, 0)) {
4923 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004924 Py_XDECREF(result);
4925 return PyErr_SetFromWindowsErr(GetLastError());
4926 }
4927 return result;
4928}
4929
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004930/*[clinic input]
4931_ssl.enum_crls
4932 store_name: str
4933
4934Retrieve CRLs from Windows' cert store.
4935
4936store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4937more cert storages, too. The function returns a list of (bytes,
4938encoding_type) tuples. The encoding_type flag can be interpreted with
4939X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4940[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004941
4942static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004943_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4944/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004945{
Christian Heimes44109d72013-11-22 01:51:30 +01004946 HCERTSTORE hStore = NULL;
4947 PCCRL_CONTEXT pCrlCtx = NULL;
4948 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4949 PyObject *result = NULL;
4950
Christian Heimes44109d72013-11-22 01:51:30 +01004951 result = PyList_New(0);
4952 if (result == NULL) {
4953 return NULL;
4954 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004955 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4956 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4957 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004958 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004959 Py_DECREF(result);
4960 return PyErr_SetFromWindowsErr(GetLastError());
4961 }
Christian Heimes44109d72013-11-22 01:51:30 +01004962
4963 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4964 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4965 pCrlCtx->cbCrlEncoded);
4966 if (!crl) {
4967 Py_CLEAR(result);
4968 break;
4969 }
4970 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4971 Py_CLEAR(result);
4972 break;
4973 }
4974 if ((tup = PyTuple_New(2)) == NULL) {
4975 Py_CLEAR(result);
4976 break;
4977 }
4978 PyTuple_SET_ITEM(tup, 0, crl);
4979 crl = NULL;
4980 PyTuple_SET_ITEM(tup, 1, enc);
4981 enc = NULL;
4982
4983 if (PyList_Append(result, tup) < 0) {
4984 Py_CLEAR(result);
4985 break;
4986 }
4987 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004988 }
Christian Heimes44109d72013-11-22 01:51:30 +01004989 if (pCrlCtx) {
4990 /* loop ended with an error, need to clean up context manually */
4991 CertFreeCRLContext(pCrlCtx);
4992 }
4993
4994 /* In error cases cert, enc and tup may not be NULL */
4995 Py_XDECREF(crl);
4996 Py_XDECREF(enc);
4997 Py_XDECREF(tup);
4998
4999 if (!CertCloseStore(hStore, 0)) {
5000 /* This error case might shadow another exception.*/
5001 Py_XDECREF(result);
5002 return PyErr_SetFromWindowsErr(GetLastError());
5003 }
5004 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005005}
Christian Heimes44109d72013-11-22 01:51:30 +01005006
5007#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005008
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005009/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005010static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005011 _SSL__TEST_DECODE_CERT_METHODDEF
5012 _SSL_RAND_ADD_METHODDEF
5013 _SSL_RAND_BYTES_METHODDEF
5014 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5015 _SSL_RAND_EGD_METHODDEF
5016 _SSL_RAND_STATUS_METHODDEF
5017 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5018 _SSL_ENUM_CERTIFICATES_METHODDEF
5019 _SSL_ENUM_CRLS_METHODDEF
5020 _SSL_TXT2OBJ_METHODDEF
5021 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005022 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005023};
5024
5025
Christian Heimes598894f2016-09-05 23:19:05 +02005026#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005027
5028/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005029 * of the Python C thread library
5030 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5031 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005032
5033static PyThread_type_lock *_ssl_locks = NULL;
5034
Christian Heimes4d98ca92013-08-19 17:36:29 +02005035#if OPENSSL_VERSION_NUMBER >= 0x10000000
5036/* use new CRYPTO_THREADID API. */
5037static void
5038_ssl_threadid_callback(CRYPTO_THREADID *id)
5039{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005040 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005041}
5042#else
5043/* deprecated CRYPTO_set_id_callback() API. */
5044static unsigned long
5045_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005046 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005047}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005048#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005049
Bill Janssen6e027db2007-11-15 22:23:56 +00005050static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005051 (int mode, int n, const char *file, int line) {
5052 /* this function is needed to perform locking on shared data
5053 structures. (Note that OpenSSL uses a number of global data
5054 structures that will be implicitly shared whenever multiple
5055 threads use OpenSSL.) Multi-threaded applications will
5056 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005057
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005058 locking_function() must be able to handle up to
5059 CRYPTO_num_locks() different mutex locks. It sets the n-th
5060 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005062 file and line are the file number of the function setting the
5063 lock. They can be useful for debugging.
5064 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005065
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005066 if ((_ssl_locks == NULL) ||
5067 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5068 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005069
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005070 if (mode & CRYPTO_LOCK) {
5071 PyThread_acquire_lock(_ssl_locks[n], 1);
5072 } else {
5073 PyThread_release_lock(_ssl_locks[n]);
5074 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005075}
5076
5077static int _setup_ssl_threads(void) {
5078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005079 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005080
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005081 if (_ssl_locks == NULL) {
5082 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005083 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5084 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005085 if (_ssl_locks == NULL) {
5086 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005087 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005088 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005089 for (i = 0; i < _ssl_locks_count; i++) {
5090 _ssl_locks[i] = PyThread_allocate_lock();
5091 if (_ssl_locks[i] == NULL) {
5092 unsigned int j;
5093 for (j = 0; j < i; j++) {
5094 PyThread_free_lock(_ssl_locks[j]);
5095 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005096 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005097 return 0;
5098 }
5099 }
5100 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005101#if OPENSSL_VERSION_NUMBER >= 0x10000000
5102 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5103#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005104 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005105#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005106 }
5107 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005108}
5109
Christian Heimes598894f2016-09-05 23:19:05 +02005110#endif /* HAVE_OPENSSL_CRYPTO_LOCK for WITH_THREAD && OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005111
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005112PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005113"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005114for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005115
Martin v. Löwis1a214512008-06-11 05:26:20 +00005116
5117static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005118 PyModuleDef_HEAD_INIT,
5119 "_ssl",
5120 module_doc,
5121 -1,
5122 PySSL_methods,
5123 NULL,
5124 NULL,
5125 NULL,
5126 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005127};
5128
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005129
5130static void
5131parse_openssl_version(unsigned long libver,
5132 unsigned int *major, unsigned int *minor,
5133 unsigned int *fix, unsigned int *patch,
5134 unsigned int *status)
5135{
5136 *status = libver & 0xF;
5137 libver >>= 4;
5138 *patch = libver & 0xFF;
5139 libver >>= 8;
5140 *fix = libver & 0xFF;
5141 libver >>= 8;
5142 *minor = libver & 0xFF;
5143 libver >>= 8;
5144 *major = libver & 0xFF;
5145}
5146
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005147PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005148PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005149{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005150 PyObject *m, *d, *r;
5151 unsigned long libver;
5152 unsigned int major, minor, fix, patch, status;
5153 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005154 struct py_ssl_error_code *errcode;
5155 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005156
Antoine Pitrou152efa22010-05-16 18:19:27 +00005157 if (PyType_Ready(&PySSLContext_Type) < 0)
5158 return NULL;
5159 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005160 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005161 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5162 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005163 if (PyType_Ready(&PySSLSession_Type) < 0)
5164 return NULL;
5165
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005166
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005167 m = PyModule_Create(&_sslmodule);
5168 if (m == NULL)
5169 return NULL;
5170 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005171
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005172 /* Load _socket module and its C API */
5173 socket_api = PySocketModule_ImportModuleAndAPI();
5174 if (!socket_api)
5175 return NULL;
5176 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005177
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005178 /* Init OpenSSL */
5179 SSL_load_error_strings();
5180 SSL_library_init();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005181#ifdef WITH_THREAD
Christian Heimes598894f2016-09-05 23:19:05 +02005182#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005183 /* note that this will start threading if not already started */
5184 if (!_setup_ssl_threads()) {
5185 return NULL;
5186 }
Christian Heimes598894f2016-09-05 23:19:05 +02005187#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5188 /* OpenSSL 1.1.0 builtin thread support is enabled */
5189 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005190#endif
Christian Heimes598894f2016-09-05 23:19:05 +02005191#endif /* WITH_THREAD */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005192 OpenSSL_add_all_algorithms();
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005193
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005194 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005195 sslerror_type_slots[0].pfunc = PyExc_OSError;
5196 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005197 if (PySSLErrorObject == NULL)
5198 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005199
Antoine Pitrou41032a62011-10-27 23:56:55 +02005200 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5201 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5202 PySSLErrorObject, NULL);
5203 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5204 "ssl.SSLWantReadError", SSLWantReadError_doc,
5205 PySSLErrorObject, NULL);
5206 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5207 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5208 PySSLErrorObject, NULL);
5209 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5210 "ssl.SSLSyscallError", SSLSyscallError_doc,
5211 PySSLErrorObject, NULL);
5212 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5213 "ssl.SSLEOFError", SSLEOFError_doc,
5214 PySSLErrorObject, NULL);
5215 if (PySSLZeroReturnErrorObject == NULL
5216 || PySSLWantReadErrorObject == NULL
5217 || PySSLWantWriteErrorObject == NULL
5218 || PySSLSyscallErrorObject == NULL
5219 || PySSLEOFErrorObject == NULL)
5220 return NULL;
5221 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5222 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5223 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5224 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5225 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5226 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005227 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005228 if (PyDict_SetItemString(d, "_SSLContext",
5229 (PyObject *)&PySSLContext_Type) != 0)
5230 return NULL;
5231 if (PyDict_SetItemString(d, "_SSLSocket",
5232 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005233 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005234 if (PyDict_SetItemString(d, "MemoryBIO",
5235 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5236 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005237 if (PyDict_SetItemString(d, "SSLSession",
5238 (PyObject *)&PySSLSession_Type) != 0)
5239 return NULL;
5240
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005241 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5242 PY_SSL_ERROR_ZERO_RETURN);
5243 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5244 PY_SSL_ERROR_WANT_READ);
5245 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5246 PY_SSL_ERROR_WANT_WRITE);
5247 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5248 PY_SSL_ERROR_WANT_X509_LOOKUP);
5249 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5250 PY_SSL_ERROR_SYSCALL);
5251 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5252 PY_SSL_ERROR_SSL);
5253 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5254 PY_SSL_ERROR_WANT_CONNECT);
5255 /* non ssl.h errorcodes */
5256 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5257 PY_SSL_ERROR_EOF);
5258 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5259 PY_SSL_ERROR_INVALID_ERROR_CODE);
5260 /* cert requirements */
5261 PyModule_AddIntConstant(m, "CERT_NONE",
5262 PY_SSL_CERT_NONE);
5263 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5264 PY_SSL_CERT_OPTIONAL);
5265 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5266 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005267 /* CRL verification for verification_flags */
5268 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5269 0);
5270 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5271 X509_V_FLAG_CRL_CHECK);
5272 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5273 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5274 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5275 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005276#ifdef X509_V_FLAG_TRUSTED_FIRST
5277 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5278 X509_V_FLAG_TRUSTED_FIRST);
5279#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005280
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005281 /* Alert Descriptions from ssl.h */
5282 /* note RESERVED constants no longer intended for use have been removed */
5283 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5284
5285#define ADD_AD_CONSTANT(s) \
5286 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5287 SSL_AD_##s)
5288
5289 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5290 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5291 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5292 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5293 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5294 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5295 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5296 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5297 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5298 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5299 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5300 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5301 ADD_AD_CONSTANT(UNKNOWN_CA);
5302 ADD_AD_CONSTANT(ACCESS_DENIED);
5303 ADD_AD_CONSTANT(DECODE_ERROR);
5304 ADD_AD_CONSTANT(DECRYPT_ERROR);
5305 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5306 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5307 ADD_AD_CONSTANT(INTERNAL_ERROR);
5308 ADD_AD_CONSTANT(USER_CANCELLED);
5309 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005310 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005311#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5312 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5313#endif
5314#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5315 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5316#endif
5317#ifdef SSL_AD_UNRECOGNIZED_NAME
5318 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5319#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005320#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5321 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5322#endif
5323#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5324 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5325#endif
5326#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5327 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5328#endif
5329
5330#undef ADD_AD_CONSTANT
5331
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005332 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005333#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005334 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5335 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005336#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005337#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005338 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5339 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005340#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005341 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005342 PY_SSL_VERSION_TLS);
5343 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5344 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005345 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5346 PY_SSL_VERSION_TLS_CLIENT);
5347 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5348 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005349 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5350 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005351#if HAVE_TLSv1_2
5352 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5353 PY_SSL_VERSION_TLS1_1);
5354 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5355 PY_SSL_VERSION_TLS1_2);
5356#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005357
Antoine Pitroub5218772010-05-21 09:56:06 +00005358 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005359 PyModule_AddIntConstant(m, "OP_ALL",
5360 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005361 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5362 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5363 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005364#if HAVE_TLSv1_2
5365 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5366 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5367#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005368 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5369 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005370 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005371 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005372#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005373 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005374#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005375#ifdef SSL_OP_NO_COMPRESSION
5376 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5377 SSL_OP_NO_COMPRESSION);
5378#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005379
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005380#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005381 r = Py_True;
5382#else
5383 r = Py_False;
5384#endif
5385 Py_INCREF(r);
5386 PyModule_AddObject(m, "HAS_SNI", r);
5387
Antoine Pitroud6494802011-07-21 01:11:30 +02005388 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005389 Py_INCREF(r);
5390 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5391
Antoine Pitrou501da612011-12-21 09:27:41 +01005392#ifdef OPENSSL_NO_ECDH
5393 r = Py_False;
5394#else
5395 r = Py_True;
5396#endif
5397 Py_INCREF(r);
5398 PyModule_AddObject(m, "HAS_ECDH", r);
5399
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005400#ifdef OPENSSL_NPN_NEGOTIATED
5401 r = Py_True;
5402#else
5403 r = Py_False;
5404#endif
5405 Py_INCREF(r);
5406 PyModule_AddObject(m, "HAS_NPN", r);
5407
Benjamin Petersoncca27322015-01-23 16:35:37 -05005408#ifdef HAVE_ALPN
5409 r = Py_True;
5410#else
5411 r = Py_False;
5412#endif
5413 Py_INCREF(r);
5414 PyModule_AddObject(m, "HAS_ALPN", r);
5415
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005416 /* Mappings for error codes */
5417 err_codes_to_names = PyDict_New();
5418 err_names_to_codes = PyDict_New();
5419 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5420 return NULL;
5421 errcode = error_codes;
5422 while (errcode->mnemonic != NULL) {
5423 PyObject *mnemo, *key;
5424 mnemo = PyUnicode_FromString(errcode->mnemonic);
5425 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5426 if (mnemo == NULL || key == NULL)
5427 return NULL;
5428 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5429 return NULL;
5430 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5431 return NULL;
5432 Py_DECREF(key);
5433 Py_DECREF(mnemo);
5434 errcode++;
5435 }
5436 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5437 return NULL;
5438 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5439 return NULL;
5440
5441 lib_codes_to_names = PyDict_New();
5442 if (lib_codes_to_names == NULL)
5443 return NULL;
5444 libcode = library_codes;
5445 while (libcode->library != NULL) {
5446 PyObject *mnemo, *key;
5447 key = PyLong_FromLong(libcode->code);
5448 mnemo = PyUnicode_FromString(libcode->library);
5449 if (key == NULL || mnemo == NULL)
5450 return NULL;
5451 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5452 return NULL;
5453 Py_DECREF(key);
5454 Py_DECREF(mnemo);
5455 libcode++;
5456 }
5457 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5458 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005459
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005460 /* OpenSSL version */
5461 /* SSLeay() gives us the version of the library linked against,
5462 which could be different from the headers version.
5463 */
5464 libver = SSLeay();
5465 r = PyLong_FromUnsignedLong(libver);
5466 if (r == NULL)
5467 return NULL;
5468 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5469 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005470 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005471 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5472 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5473 return NULL;
5474 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5475 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5476 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005477
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005478 libver = OPENSSL_VERSION_NUMBER;
5479 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5480 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5481 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5482 return NULL;
5483
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005484 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005485}