blob: b8509acc3f14e6248eac4a6577713e89d0833c27 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066
67/* SSL error object */
68static PyObject *PySSLErrorObject;
69static PyObject *PySSLZeroReturnErrorObject;
70static PyObject *PySSLWantReadErrorObject;
71static PyObject *PySSLWantWriteErrorObject;
72static PyObject *PySSLSyscallErrorObject;
73static PyObject *PySSLEOFErrorObject;
74
75/* Error mappings */
76static PyObject *err_codes_to_names;
77static PyObject *err_names_to_codes;
78static PyObject *lib_codes_to_names;
79
80struct py_ssl_error_code {
81 const char *mnemonic;
82 int library, reason;
83};
84struct py_ssl_library_code {
85 const char *library;
86 int code;
87};
88
Steve Dower68d663c2017-07-17 11:15:48 +020089#if defined(MS_WINDOWS) && defined(Py_DEBUG)
90/* Debug builds on Windows rely on getting errno directly from OpenSSL.
91 * However, because it uses a different CRT, we need to transfer the
92 * value of errno from OpenSSL into our debug CRT.
93 *
94 * Don't be fooled - this is horribly ugly code. The only reasonable
95 * alternative is to do both debug and release builds of OpenSSL, which
96 * requires much uglier code to transform their automatically generated
97 * makefile. This is the lesser of all the evils.
98 */
99
100static void _PySSLFixErrno(void) {
101 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
102 if (!ucrtbase) {
103 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
104 * have a catastrophic failure, but this function is not the
105 * place to raise it. */
106 return;
107 }
108
109 typedef int *(__stdcall *errno_func)(void);
110 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
111 if (ssl_errno) {
112 errno = *ssl_errno();
113 *ssl_errno() = 0;
114 } else {
115 errno = ENOTRECOVERABLE;
116 }
117}
118
119#undef _PySSL_FIX_ERRNO
120#define _PySSL_FIX_ERRNO _PySSLFixErrno()
121#endif
122
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100123/* Include generated data (error codes) */
124#include "_ssl_data.h"
125
Christian Heimes598894f2016-09-05 23:19:05 +0200126#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
127# define OPENSSL_VERSION_1_1 1
128#endif
129
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100130/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
131 http://www.openssl.org/news/changelog.html
132 */
133#if OPENSSL_VERSION_NUMBER >= 0x10001000L
134# define HAVE_TLSv1_2 1
135#else
136# define HAVE_TLSv1_2 0
137#endif
138
Christian Heimes470fba12013-11-28 15:12:15 +0100139/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100140 * This includes the SSL_set_SSL_CTX() function.
141 */
142#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
143# define HAVE_SNI 1
144#else
145# define HAVE_SNI 0
146#endif
147
Benjamin Petersond3308222015-09-27 00:09:02 -0700148#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500149# define HAVE_ALPN
150#endif
151
Victor Stinner524714e2016-07-22 17:43:59 +0200152#ifndef INVALID_SOCKET /* MS defines this */
153#define INVALID_SOCKET (-1)
154#endif
155
Christian Heimes598894f2016-09-05 23:19:05 +0200156#ifdef OPENSSL_VERSION_1_1
157/* OpenSSL 1.1.0+ */
158#ifndef OPENSSL_NO_SSL2
159#define OPENSSL_NO_SSL2
160#endif
161#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200162#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200163
164#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200165#define TLS_client_method SSLv23_client_method
166#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200167
168static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
169{
170 return ne->set;
171}
172
173#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200174/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200175static int COMP_get_type(const COMP_METHOD *meth)
176{
177 return meth->type;
178}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200179/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200180#endif
181
182static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
183{
184 return ctx->default_passwd_callback;
185}
186
187static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
188{
189 return ctx->default_passwd_callback_userdata;
190}
191
192static int X509_OBJECT_get_type(X509_OBJECT *x)
193{
194 return x->type;
195}
196
197static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
198{
199 return x->data.x509;
200}
201
202static int BIO_up_ref(BIO *b)
203{
204 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
205 return 1;
206}
207
208static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
209 return store->objs;
210}
211
212static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
213{
214 return store->param;
215}
Christian Heimes99a65702016-09-10 23:44:53 +0200216
217static int
218SSL_SESSION_has_ticket(const SSL_SESSION *s)
219{
220 return (s->tlsext_ticklen > 0) ? 1 : 0;
221}
222
223static unsigned long
224SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
225{
226 return s->tlsext_tick_lifetime_hint;
227}
228
Christian Heimes598894f2016-09-05 23:19:05 +0200229#endif /* OpenSSL < 1.1.0 or LibreSSL */
230
231
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000232enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000233 /* these mirror ssl.h */
234 PY_SSL_ERROR_NONE,
235 PY_SSL_ERROR_SSL,
236 PY_SSL_ERROR_WANT_READ,
237 PY_SSL_ERROR_WANT_WRITE,
238 PY_SSL_ERROR_WANT_X509_LOOKUP,
239 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
240 PY_SSL_ERROR_ZERO_RETURN,
241 PY_SSL_ERROR_WANT_CONNECT,
242 /* start of non ssl.h errorcodes */
243 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
244 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
245 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000246};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000247
Thomas Woutersed03b412007-08-28 21:37:11 +0000248enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000249 PY_SSL_CLIENT,
250 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000251};
252
253enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000254 PY_SSL_CERT_NONE,
255 PY_SSL_CERT_OPTIONAL,
256 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000257};
258
259enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000260 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200261 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200262 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100263#if HAVE_TLSv1_2
264 PY_SSL_VERSION_TLS1,
265 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200266 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100267#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200268 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000269#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200270 PY_SSL_VERSION_TLS_CLIENT=0x10,
271 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100272};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200273
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000274/* serves as a flag to see whether we've initialized the SSL thread support. */
275/* 0 means no, greater than 0 means yes */
276
277static unsigned int _ssl_locks_count = 0;
278
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000279/* SSL socket object */
280
281#define X509_NAME_MAXLEN 256
282
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000283/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
284 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
285 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
286#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000287# define HAVE_SSL_CTX_CLEAR_OPTIONS
288#else
289# undef HAVE_SSL_CTX_CLEAR_OPTIONS
290#endif
291
Antoine Pitroud6494802011-07-21 01:11:30 +0200292/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
293 * older SSL, but let's be safe */
294#define PySSL_CB_MAXLEN 128
295
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100296
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000297typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000298 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000299 SSL_CTX *ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +0200300#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500301 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100302 int npn_protocols_len;
303#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500304#ifdef HAVE_ALPN
305 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300306 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500307#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100308#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200309 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100310#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100311 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000312} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000313
Antoine Pitrou152efa22010-05-16 18:19:27 +0000314typedef struct {
315 PyObject_HEAD
316 PyObject *Socket; /* weakref to socket on which we're layered */
317 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100318 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200319 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200320 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200321 PyObject *owner; /* Python level "owner" passed to servername callback */
322 PyObject *server_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000323} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000324
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200325typedef struct {
326 PyObject_HEAD
327 BIO *bio;
328 int eof_written;
329} PySSLMemoryBIO;
330
Christian Heimes99a65702016-09-10 23:44:53 +0200331typedef struct {
332 PyObject_HEAD
333 SSL_SESSION *session;
334 PySSLContext *ctx;
335} PySSLSession;
336
Antoine Pitrou152efa22010-05-16 18:19:27 +0000337static PyTypeObject PySSLContext_Type;
338static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200339static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200340static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000341
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300342/*[clinic input]
343module _ssl
344class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
345class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
346class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200347class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300348[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200349/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300350
351#include "clinic/_ssl.c.h"
352
Victor Stinner14690702015-04-06 22:46:13 +0200353static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000354
Christian Heimes99a65702016-09-10 23:44:53 +0200355
Antoine Pitrou152efa22010-05-16 18:19:27 +0000356#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
357#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200358#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200359#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000360
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000361typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000362 SOCKET_IS_NONBLOCKING,
363 SOCKET_IS_BLOCKING,
364 SOCKET_HAS_TIMED_OUT,
365 SOCKET_HAS_BEEN_CLOSED,
366 SOCKET_TOO_LARGE_FOR_SELECT,
367 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000368} timeout_state;
369
Thomas Woutersed03b412007-08-28 21:37:11 +0000370/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000371#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200372#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000373
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200374/* Get the socket from a PySSLSocket, if it has one */
375#define GET_SOCKET(obj) ((obj)->Socket ? \
376 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200377
Victor Stinner14690702015-04-06 22:46:13 +0200378/* If sock is NULL, use a timeout of 0 second */
379#define GET_SOCKET_TIMEOUT(sock) \
380 ((sock != NULL) ? (sock)->sock_timeout : 0)
381
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200382/*
383 * SSL errors.
384 */
385
386PyDoc_STRVAR(SSLError_doc,
387"An error occurred in the SSL implementation.");
388
389PyDoc_STRVAR(SSLZeroReturnError_doc,
390"SSL/TLS session closed cleanly.");
391
392PyDoc_STRVAR(SSLWantReadError_doc,
393"Non-blocking SSL socket needs to read more data\n"
394"before the requested operation can be completed.");
395
396PyDoc_STRVAR(SSLWantWriteError_doc,
397"Non-blocking SSL socket needs to write more data\n"
398"before the requested operation can be completed.");
399
400PyDoc_STRVAR(SSLSyscallError_doc,
401"System error when attempting SSL operation.");
402
403PyDoc_STRVAR(SSLEOFError_doc,
404"SSL/TLS connection terminated abruptly.");
405
406static PyObject *
407SSLError_str(PyOSErrorObject *self)
408{
409 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
410 Py_INCREF(self->strerror);
411 return self->strerror;
412 }
413 else
414 return PyObject_Str(self->args);
415}
416
417static PyType_Slot sslerror_type_slots[] = {
418 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
419 {Py_tp_doc, SSLError_doc},
420 {Py_tp_str, SSLError_str},
421 {0, 0},
422};
423
424static PyType_Spec sslerror_type_spec = {
425 "ssl.SSLError",
426 sizeof(PyOSErrorObject),
427 0,
428 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
429 sslerror_type_slots
430};
431
432static void
433fill_and_set_sslerror(PyObject *type, int ssl_errno, const char *errstr,
434 int lineno, unsigned long errcode)
435{
436 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
437 PyObject *init_value, *msg, *key;
438 _Py_IDENTIFIER(reason);
439 _Py_IDENTIFIER(library);
440
441 if (errcode != 0) {
442 int lib, reason;
443
444 lib = ERR_GET_LIB(errcode);
445 reason = ERR_GET_REASON(errcode);
446 key = Py_BuildValue("ii", lib, reason);
447 if (key == NULL)
448 goto fail;
449 reason_obj = PyDict_GetItem(err_codes_to_names, key);
450 Py_DECREF(key);
451 if (reason_obj == NULL) {
452 /* XXX if reason < 100, it might reflect a library number (!!) */
453 PyErr_Clear();
454 }
455 key = PyLong_FromLong(lib);
456 if (key == NULL)
457 goto fail;
458 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
459 Py_DECREF(key);
460 if (lib_obj == NULL) {
461 PyErr_Clear();
462 }
463 if (errstr == NULL)
464 errstr = ERR_reason_error_string(errcode);
465 }
466 if (errstr == NULL)
467 errstr = "unknown error";
468
469 if (reason_obj && lib_obj)
470 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
471 lib_obj, reason_obj, errstr, lineno);
472 else if (lib_obj)
473 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
474 lib_obj, errstr, lineno);
475 else
476 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200477 if (msg == NULL)
478 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100479
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200480 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100481 if (init_value == NULL)
482 goto fail;
483
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200484 err_value = PyObject_CallObject(type, init_value);
485 Py_DECREF(init_value);
486 if (err_value == NULL)
487 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100488
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200489 if (reason_obj == NULL)
490 reason_obj = Py_None;
491 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
492 goto fail;
493 if (lib_obj == NULL)
494 lib_obj = Py_None;
495 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
496 goto fail;
497 PyErr_SetObject(type, err_value);
498fail:
499 Py_XDECREF(err_value);
500}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000501
502static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200503PySSL_SetError(PySSLSocket *obj, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000504{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200505 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200506 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000507 int err;
508 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200509 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000511 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200512 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000513
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000514 if (obj->ssl != NULL) {
515 err = SSL_get_error(obj->ssl, ret);
Thomas Woutersed03b412007-08-28 21:37:11 +0000516
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000517 switch (err) {
518 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200519 errstr = "TLS/SSL connection has been closed (EOF)";
520 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000521 p = PY_SSL_ERROR_ZERO_RETURN;
522 break;
523 case SSL_ERROR_WANT_READ:
524 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200525 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000526 p = PY_SSL_ERROR_WANT_READ;
527 break;
528 case SSL_ERROR_WANT_WRITE:
529 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200530 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000531 errstr = "The operation did not complete (write)";
532 break;
533 case SSL_ERROR_WANT_X509_LOOKUP:
534 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000535 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000536 break;
537 case SSL_ERROR_WANT_CONNECT:
538 p = PY_SSL_ERROR_WANT_CONNECT;
539 errstr = "The operation did not complete (connect)";
540 break;
541 case SSL_ERROR_SYSCALL:
542 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000543 if (e == 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200544 PySocketSockObject *s = GET_SOCKET(obj);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000545 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000546 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200547 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000548 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200549 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000550 /* underlying BIO reported an I/O error */
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000551 Py_INCREF(s);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000552 ERR_clear_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200553 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000554 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200555 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000556 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000557 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200558 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000559 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000560 }
561 } else {
562 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000563 }
564 break;
565 }
566 case SSL_ERROR_SSL:
567 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000568 p = PY_SSL_ERROR_SSL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569 if (e == 0)
570 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000571 errstr = "A failure in the SSL library occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000572 break;
573 }
574 default:
575 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
576 errstr = "Invalid error code";
577 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000578 }
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200579 fill_and_set_sslerror(type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000580 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000581 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000582}
583
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000584static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200585_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000586
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200587 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000588 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200589 else
590 errcode = 0;
591 fill_and_set_sslerror(PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000592 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000593 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000594}
595
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200596/*
597 * SSL objects
598 */
599
Antoine Pitrou152efa22010-05-16 18:19:27 +0000600static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100601newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000602 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200603 char *server_hostname,
604 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000605{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000606 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100607 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200608 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000609
Antoine Pitrou152efa22010-05-16 18:19:27 +0000610 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000611 if (self == NULL)
612 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000613
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000615 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100616 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700617 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200618 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200619 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700620 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200621 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700622 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
623 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200624 if (hostname == NULL) {
625 Py_DECREF(self);
626 return NULL;
627 }
628 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700629 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200630
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 /* Make sure the SSL error state is initialized */
632 (void) ERR_get_state();
633 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000634
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000635 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000636 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000637 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200638 SSL_set_app_data(self->ssl, self);
639 if (sock) {
640 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
641 } else {
642 /* BIOs are reference counted and SSL_set_bio borrows our reference.
643 * To prevent a double free in memory_bio_dealloc() we need to take an
644 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200645 BIO_up_ref(inbio->bio);
646 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200647 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
648 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200649 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000650#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200651 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000652#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200653 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000654
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100655#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000656 if (server_hostname != NULL)
657 SSL_set_tlsext_host_name(self->ssl, server_hostname);
658#endif
659
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000660 /* If the socket is in non-blocking mode or timeout mode, set the BIO
661 * to non-blocking mode (blocking is the default)
662 */
Victor Stinnere2452312015-03-28 03:00:46 +0100663 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
665 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
666 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000667
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000668 PySSL_BEGIN_ALLOW_THREADS
669 if (socket_type == PY_SSL_CLIENT)
670 SSL_set_connect_state(self->ssl);
671 else
672 SSL_set_accept_state(self->ssl);
673 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000674
Antoine Pitroud6494802011-07-21 01:11:30 +0200675 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200676 if (sock != NULL) {
677 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
678 if (self->Socket == NULL) {
679 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200680 return NULL;
681 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100682 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000683 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000684}
685
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000686/* SSL object methods */
687
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300688/*[clinic input]
689_ssl._SSLSocket.do_handshake
690[clinic start generated code]*/
691
692static PyObject *
693_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
694/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000695{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 int ret;
697 int err;
698 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200699 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200700 _PyTime_t timeout, deadline = 0;
701 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000702
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200703 if (sock) {
704 if (((PyObject*)sock) == Py_None) {
705 _setSSLError("Underlying socket connection gone",
706 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
707 return NULL;
708 }
709 Py_INCREF(sock);
710
711 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100712 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200713 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
714 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000716
Victor Stinner14690702015-04-06 22:46:13 +0200717 timeout = GET_SOCKET_TIMEOUT(sock);
718 has_timeout = (timeout > 0);
719 if (has_timeout)
720 deadline = _PyTime_GetMonotonicClock() + timeout;
721
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000722 /* Actually negotiate SSL connection */
723 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000724 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000725 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000726 ret = SSL_do_handshake(self->ssl);
727 err = SSL_get_error(self->ssl, ret);
728 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200729
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000730 if (PyErr_CheckSignals())
731 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200732
Victor Stinner14690702015-04-06 22:46:13 +0200733 if (has_timeout)
734 timeout = deadline - _PyTime_GetMonotonicClock();
735
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000736 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200737 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000738 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200739 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 } else {
741 sockstate = SOCKET_OPERATION_OK;
742 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200743
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000745 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000746 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000747 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000748 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
749 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000750 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000751 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000752 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
753 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000754 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000755 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000756 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
757 break;
758 }
759 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200760 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 if (ret < 1)
762 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000763
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200764 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000765
766error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200767 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000768 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000769}
770
Thomas Woutersed03b412007-08-28 21:37:11 +0000771static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300772_asn1obj2py(const ASN1_OBJECT *name, int no_name)
773{
774 char buf[X509_NAME_MAXLEN];
775 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300777 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000778
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300779 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000780 if (buflen < 0) {
781 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300782 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000783 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300784 /* initial buffer is too small for oid + terminating null byte */
785 if (buflen > X509_NAME_MAXLEN - 1) {
786 /* make OBJ_obj2txt() calculate the required buflen */
787 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
788 /* allocate len + 1 for terminating NULL byte */
789 namebuf = PyMem_Malloc(buflen + 1);
790 if (namebuf == NULL) {
791 PyErr_NoMemory();
792 return NULL;
793 }
794 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
795 if (buflen < 0) {
796 _setSSLError(NULL, 0, __FILE__, __LINE__);
797 goto done;
798 }
799 }
800 if (!buflen && no_name) {
801 Py_INCREF(Py_None);
802 name_obj = Py_None;
803 }
804 else {
805 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
806 }
807
808 done:
809 if (buf != namebuf) {
810 PyMem_Free(namebuf);
811 }
812 return name_obj;
813}
814
815static PyObject *
816_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
817{
818 Py_ssize_t buflen;
819 unsigned char *valuebuf = NULL;
820 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000821
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000822 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
823 if (buflen < 0) {
824 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300825 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000826 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300827 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000828 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000830}
831
832static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000833_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000834{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000835 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
836 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
837 PyObject *rdnt;
838 PyObject *attr = NULL; /* tuple to hold an attribute */
839 int entry_count = X509_NAME_entry_count(xname);
840 X509_NAME_ENTRY *entry;
841 ASN1_OBJECT *name;
842 ASN1_STRING *value;
843 int index_counter;
844 int rdn_level = -1;
845 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000846
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 dn = PyList_New(0);
848 if (dn == NULL)
849 return NULL;
850 /* now create another tuple to hold the top-level RDN */
851 rdn = PyList_New(0);
852 if (rdn == NULL)
853 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000854
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000855 for (index_counter = 0;
856 index_counter < entry_count;
857 index_counter++)
858 {
859 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000860
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 /* check to see if we've gotten to a new RDN */
862 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200863 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000864 /* yes, new RDN */
865 /* add old RDN to DN */
866 rdnt = PyList_AsTuple(rdn);
867 Py_DECREF(rdn);
868 if (rdnt == NULL)
869 goto fail0;
870 retcode = PyList_Append(dn, rdnt);
871 Py_DECREF(rdnt);
872 if (retcode < 0)
873 goto fail0;
874 /* create new RDN */
875 rdn = PyList_New(0);
876 if (rdn == NULL)
877 goto fail0;
878 }
879 }
Christian Heimes598894f2016-09-05 23:19:05 +0200880 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000881
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 /* now add this attribute to the current RDN */
883 name = X509_NAME_ENTRY_get_object(entry);
884 value = X509_NAME_ENTRY_get_data(entry);
885 attr = _create_tuple_for_attribute(name, value);
886 /*
887 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
888 entry->set,
889 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
890 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
891 */
892 if (attr == NULL)
893 goto fail1;
894 retcode = PyList_Append(rdn, attr);
895 Py_DECREF(attr);
896 if (retcode < 0)
897 goto fail1;
898 }
899 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +0100900 if (rdn != NULL) {
901 if (PyList_GET_SIZE(rdn) > 0) {
902 rdnt = PyList_AsTuple(rdn);
903 Py_DECREF(rdn);
904 if (rdnt == NULL)
905 goto fail0;
906 retcode = PyList_Append(dn, rdnt);
907 Py_DECREF(rdnt);
908 if (retcode < 0)
909 goto fail0;
910 }
911 else {
912 Py_DECREF(rdn);
913 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000914 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000915
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000916 /* convert list to tuple */
917 rdnt = PyList_AsTuple(dn);
918 Py_DECREF(dn);
919 if (rdnt == NULL)
920 return NULL;
921 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000922
923 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000925
926 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000927 Py_XDECREF(dn);
928 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000929}
930
931static PyObject *
932_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +0000933
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000934 /* this code follows the procedure outlined in
935 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
936 function to extract the STACK_OF(GENERAL_NAME),
937 then iterates through the stack to add the
938 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000939
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400940 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000941 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +0200942 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000943 GENERAL_NAMES *names = NULL;
944 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000945 BIO *biobuf = NULL;
946 char buf[2048];
947 char *vptr;
948 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000949
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000950 if (certificate == NULL)
951 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000952
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000953 /* get a memory buffer */
954 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Alex Gaynorb87c0df2017-06-06 07:53:11 -0400956 names = (GENERAL_NAMES *)X509_get_ext_d2i(
957 certificate, NID_subject_alt_name, NULL, NULL);
958 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000959 if (peer_alt_names == Py_None) {
960 peer_alt_names = PyList_New(0);
961 if (peer_alt_names == NULL)
962 goto fail;
963 }
Guido van Rossumf06628b2007-11-21 20:01:53 +0000964
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000965 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +0200967 int gntype;
968 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +0200971 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +0200972 switch (gntype) {
973 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000974 /* we special-case DirName as a tuple of
975 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000976
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000977 t = PyTuple_New(2);
978 if (t == NULL) {
979 goto fail;
980 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000982 v = PyUnicode_FromString("DirName");
983 if (v == NULL) {
984 Py_DECREF(t);
985 goto fail;
986 }
987 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000989 v = _create_tuple_for_X509_NAME (name->d.dirn);
990 if (v == NULL) {
991 Py_DECREF(t);
992 goto fail;
993 }
994 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +0200995 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000996
Christian Heimes824f7f32013-08-17 00:54:47 +0200997 case GEN_EMAIL:
998 case GEN_DNS:
999 case GEN_URI:
1000 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1001 correctly, CVE-2013-4238 */
1002 t = PyTuple_New(2);
1003 if (t == NULL)
1004 goto fail;
1005 switch (gntype) {
1006 case GEN_EMAIL:
1007 v = PyUnicode_FromString("email");
1008 as = name->d.rfc822Name;
1009 break;
1010 case GEN_DNS:
1011 v = PyUnicode_FromString("DNS");
1012 as = name->d.dNSName;
1013 break;
1014 case GEN_URI:
1015 v = PyUnicode_FromString("URI");
1016 as = name->d.uniformResourceIdentifier;
1017 break;
1018 }
1019 if (v == NULL) {
1020 Py_DECREF(t);
1021 goto fail;
1022 }
1023 PyTuple_SET_ITEM(t, 0, v);
1024 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1025 ASN1_STRING_length(as));
1026 if (v == NULL) {
1027 Py_DECREF(t);
1028 goto fail;
1029 }
1030 PyTuple_SET_ITEM(t, 1, v);
1031 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001032
Christian Heimes1c03abd2016-09-06 23:25:35 +02001033 case GEN_RID:
1034 t = PyTuple_New(2);
1035 if (t == NULL)
1036 goto fail;
1037
1038 v = PyUnicode_FromString("Registered ID");
1039 if (v == NULL) {
1040 Py_DECREF(t);
1041 goto fail;
1042 }
1043 PyTuple_SET_ITEM(t, 0, v);
1044
1045 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1046 if (len < 0) {
1047 Py_DECREF(t);
1048 _setSSLError(NULL, 0, __FILE__, __LINE__);
1049 goto fail;
1050 } else if (len >= (int)sizeof(buf)) {
1051 v = PyUnicode_FromString("<INVALID>");
1052 } else {
1053 v = PyUnicode_FromStringAndSize(buf, len);
1054 }
1055 if (v == NULL) {
1056 Py_DECREF(t);
1057 goto fail;
1058 }
1059 PyTuple_SET_ITEM(t, 1, v);
1060 break;
1061
Christian Heimes824f7f32013-08-17 00:54:47 +02001062 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001063 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001064 switch (gntype) {
1065 /* check for new general name type */
1066 case GEN_OTHERNAME:
1067 case GEN_X400:
1068 case GEN_EDIPARTY:
1069 case GEN_IPADD:
1070 case GEN_RID:
1071 break;
1072 default:
1073 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1074 "Unknown general name type %d",
1075 gntype) == -1) {
1076 goto fail;
1077 }
1078 break;
1079 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001080 (void) BIO_reset(biobuf);
1081 GENERAL_NAME_print(biobuf, name);
1082 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1083 if (len < 0) {
1084 _setSSLError(NULL, 0, __FILE__, __LINE__);
1085 goto fail;
1086 }
1087 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001088 if (vptr == NULL) {
1089 PyErr_Format(PyExc_ValueError,
1090 "Invalid value %.200s",
1091 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001092 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001093 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001094 t = PyTuple_New(2);
1095 if (t == NULL)
1096 goto fail;
1097 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1098 if (v == NULL) {
1099 Py_DECREF(t);
1100 goto fail;
1101 }
1102 PyTuple_SET_ITEM(t, 0, v);
1103 v = PyUnicode_FromStringAndSize((vptr + 1),
1104 (len - (vptr - buf + 1)));
1105 if (v == NULL) {
1106 Py_DECREF(t);
1107 goto fail;
1108 }
1109 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001110 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001111 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001112
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001113 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001114
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001115 if (PyList_Append(peer_alt_names, t) < 0) {
1116 Py_DECREF(t);
1117 goto fail;
1118 }
1119 Py_DECREF(t);
1120 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001121 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001122 }
1123 BIO_free(biobuf);
1124 if (peer_alt_names != Py_None) {
1125 v = PyList_AsTuple(peer_alt_names);
1126 Py_DECREF(peer_alt_names);
1127 return v;
1128 } else {
1129 return peer_alt_names;
1130 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001131
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001132
1133 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001134 if (biobuf != NULL)
1135 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001136
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001137 if (peer_alt_names != Py_None) {
1138 Py_XDECREF(peer_alt_names);
1139 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001140
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001141 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001142}
1143
1144static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001145_get_aia_uri(X509 *certificate, int nid) {
1146 PyObject *lst = NULL, *ostr = NULL;
1147 int i, result;
1148 AUTHORITY_INFO_ACCESS *info;
1149
1150 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001151 if (info == NULL)
1152 return Py_None;
1153 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1154 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001155 return Py_None;
1156 }
1157
1158 if ((lst = PyList_New(0)) == NULL) {
1159 goto fail;
1160 }
1161
1162 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1163 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1164 ASN1_IA5STRING *uri;
1165
1166 if ((OBJ_obj2nid(ad->method) != nid) ||
1167 (ad->location->type != GEN_URI)) {
1168 continue;
1169 }
1170 uri = ad->location->d.uniformResourceIdentifier;
1171 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1172 uri->length);
1173 if (ostr == NULL) {
1174 goto fail;
1175 }
1176 result = PyList_Append(lst, ostr);
1177 Py_DECREF(ostr);
1178 if (result < 0) {
1179 goto fail;
1180 }
1181 }
1182 AUTHORITY_INFO_ACCESS_free(info);
1183
1184 /* convert to tuple or None */
1185 if (PyList_Size(lst) == 0) {
1186 Py_DECREF(lst);
1187 return Py_None;
1188 } else {
1189 PyObject *tup;
1190 tup = PyList_AsTuple(lst);
1191 Py_DECREF(lst);
1192 return tup;
1193 }
1194
1195 fail:
1196 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001197 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001198 return NULL;
1199}
1200
1201static PyObject *
1202_get_crl_dp(X509 *certificate) {
1203 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001204 int i, j;
1205 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001206
Christian Heimes598894f2016-09-05 23:19:05 +02001207 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001208
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001209 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001210 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001211
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001212 lst = PyList_New(0);
1213 if (lst == NULL)
1214 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001215
1216 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1217 DIST_POINT *dp;
1218 STACK_OF(GENERAL_NAME) *gns;
1219
1220 dp = sk_DIST_POINT_value(dps, i);
1221 gns = dp->distpoint->name.fullname;
1222
1223 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1224 GENERAL_NAME *gn;
1225 ASN1_IA5STRING *uri;
1226 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001227 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001228
1229 gn = sk_GENERAL_NAME_value(gns, j);
1230 if (gn->type != GEN_URI) {
1231 continue;
1232 }
1233 uri = gn->d.uniformResourceIdentifier;
1234 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1235 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001236 if (ouri == NULL)
1237 goto done;
1238
1239 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001240 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001241 if (err < 0)
1242 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001243 }
1244 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001245
1246 /* Convert to tuple. */
1247 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1248
1249 done:
1250 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001251 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001252 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001253}
1254
1255static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001256_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001257
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001258 PyObject *retval = NULL;
1259 BIO *biobuf = NULL;
1260 PyObject *peer;
1261 PyObject *peer_alt_names = NULL;
1262 PyObject *issuer;
1263 PyObject *version;
1264 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001265 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001266 ASN1_INTEGER *serialNumber;
1267 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001268 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001269 ASN1_TIME *notBefore, *notAfter;
1270 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001271
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001272 retval = PyDict_New();
1273 if (retval == NULL)
1274 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001276 peer = _create_tuple_for_X509_NAME(
1277 X509_get_subject_name(certificate));
1278 if (peer == NULL)
1279 goto fail0;
1280 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1281 Py_DECREF(peer);
1282 goto fail0;
1283 }
1284 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001285
Antoine Pitroufb046912010-11-09 20:21:19 +00001286 issuer = _create_tuple_for_X509_NAME(
1287 X509_get_issuer_name(certificate));
1288 if (issuer == NULL)
1289 goto fail0;
1290 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001291 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001292 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001293 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001294 Py_DECREF(issuer);
1295
1296 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001297 if (version == NULL)
1298 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001299 if (PyDict_SetItemString(retval, "version", version) < 0) {
1300 Py_DECREF(version);
1301 goto fail0;
1302 }
1303 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001304
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001305 /* get a memory buffer */
1306 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001307
Antoine Pitroufb046912010-11-09 20:21:19 +00001308 (void) BIO_reset(biobuf);
1309 serialNumber = X509_get_serialNumber(certificate);
1310 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1311 i2a_ASN1_INTEGER(biobuf, serialNumber);
1312 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1313 if (len < 0) {
1314 _setSSLError(NULL, 0, __FILE__, __LINE__);
1315 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001316 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001317 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1318 if (sn_obj == NULL)
1319 goto fail1;
1320 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1321 Py_DECREF(sn_obj);
1322 goto fail1;
1323 }
1324 Py_DECREF(sn_obj);
1325
1326 (void) BIO_reset(biobuf);
1327 notBefore = X509_get_notBefore(certificate);
1328 ASN1_TIME_print(biobuf, notBefore);
1329 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1330 if (len < 0) {
1331 _setSSLError(NULL, 0, __FILE__, __LINE__);
1332 goto fail1;
1333 }
1334 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1335 if (pnotBefore == NULL)
1336 goto fail1;
1337 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1338 Py_DECREF(pnotBefore);
1339 goto fail1;
1340 }
1341 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001343 (void) BIO_reset(biobuf);
1344 notAfter = X509_get_notAfter(certificate);
1345 ASN1_TIME_print(biobuf, notAfter);
1346 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1347 if (len < 0) {
1348 _setSSLError(NULL, 0, __FILE__, __LINE__);
1349 goto fail1;
1350 }
1351 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1352 if (pnotAfter == NULL)
1353 goto fail1;
1354 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1355 Py_DECREF(pnotAfter);
1356 goto fail1;
1357 }
1358 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001361
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001362 peer_alt_names = _get_peer_alt_names(certificate);
1363 if (peer_alt_names == NULL)
1364 goto fail1;
1365 else if (peer_alt_names != Py_None) {
1366 if (PyDict_SetItemString(retval, "subjectAltName",
1367 peer_alt_names) < 0) {
1368 Py_DECREF(peer_alt_names);
1369 goto fail1;
1370 }
1371 Py_DECREF(peer_alt_names);
1372 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001373
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001374 /* Authority Information Access: OCSP URIs */
1375 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1376 if (obj == NULL) {
1377 goto fail1;
1378 } else if (obj != Py_None) {
1379 result = PyDict_SetItemString(retval, "OCSP", obj);
1380 Py_DECREF(obj);
1381 if (result < 0) {
1382 goto fail1;
1383 }
1384 }
1385
1386 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1387 if (obj == NULL) {
1388 goto fail1;
1389 } else if (obj != Py_None) {
1390 result = PyDict_SetItemString(retval, "caIssuers", obj);
1391 Py_DECREF(obj);
1392 if (result < 0) {
1393 goto fail1;
1394 }
1395 }
1396
1397 /* CDP (CRL distribution points) */
1398 obj = _get_crl_dp(certificate);
1399 if (obj == NULL) {
1400 goto fail1;
1401 } else if (obj != Py_None) {
1402 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1403 Py_DECREF(obj);
1404 if (result < 0) {
1405 goto fail1;
1406 }
1407 }
1408
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001409 BIO_free(biobuf);
1410 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001411
1412 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001413 if (biobuf != NULL)
1414 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001415 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001416 Py_XDECREF(retval);
1417 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001418}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001419
Christian Heimes9a5395a2013-06-17 15:44:12 +02001420static PyObject *
1421_certificate_to_der(X509 *certificate)
1422{
1423 unsigned char *bytes_buf = NULL;
1424 int len;
1425 PyObject *retval;
1426
1427 bytes_buf = NULL;
1428 len = i2d_X509(certificate, &bytes_buf);
1429 if (len < 0) {
1430 _setSSLError(NULL, 0, __FILE__, __LINE__);
1431 return NULL;
1432 }
1433 /* this is actually an immutable bytes sequence */
1434 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1435 OPENSSL_free(bytes_buf);
1436 return retval;
1437}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001438
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001439/*[clinic input]
1440_ssl._test_decode_cert
1441 path: object(converter="PyUnicode_FSConverter")
1442 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001443
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001444[clinic start generated code]*/
1445
1446static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001447_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1448/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001449{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001450 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001451 X509 *x=NULL;
1452 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001453
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001454 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1455 PyErr_SetString(PySSLErrorObject,
1456 "Can't malloc memory to read file");
1457 goto fail0;
1458 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001459
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001460 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001461 PyErr_SetString(PySSLErrorObject,
1462 "Can't open file");
1463 goto fail0;
1464 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001465
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001466 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1467 if (x == NULL) {
1468 PyErr_SetString(PySSLErrorObject,
1469 "Error decoding PEM-encoded file");
1470 goto fail0;
1471 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001472
Antoine Pitroufb046912010-11-09 20:21:19 +00001473 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001474 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001475
1476 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001477 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001478 if (cert != NULL) BIO_free(cert);
1479 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001480}
1481
1482
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001483/*[clinic input]
1484_ssl._SSLSocket.peer_certificate
1485 der as binary_mode: bool = False
1486 /
1487
1488Returns the certificate for the peer.
1489
1490If no certificate was provided, returns None. If a certificate was
1491provided, but not validated, returns an empty dictionary. Otherwise
1492returns a dict containing information about the peer certificate.
1493
1494If the optional argument is True, returns a DER-encoded copy of the
1495peer certificate, or None if no certificate was provided. This will
1496return the certificate even if it wasn't validated.
1497[clinic start generated code]*/
1498
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001499static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001500_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1501/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001502{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001503 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001504 X509 *peer_cert;
1505 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001506
Christian Heimes66dc33b2017-05-23 16:02:02 -07001507 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001508 PyErr_SetString(PyExc_ValueError,
1509 "handshake not done yet");
1510 return NULL;
1511 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001512 peer_cert = SSL_get_peer_certificate(self->ssl);
1513 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001514 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001515
Antoine Pitrou721738f2012-08-15 23:20:39 +02001516 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001517 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001518 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001519 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001520 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001521 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001522 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001523 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001524 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001526 X509_free(peer_cert);
1527 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001528}
1529
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001530static PyObject *
1531cipher_to_tuple(const SSL_CIPHER *cipher)
1532{
1533 const char *cipher_name, *cipher_protocol;
1534 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001535 if (retval == NULL)
1536 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001537
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001538 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001539 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001540 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001541 PyTuple_SET_ITEM(retval, 0, Py_None);
1542 } else {
1543 v = PyUnicode_FromString(cipher_name);
1544 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001545 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001546 PyTuple_SET_ITEM(retval, 0, v);
1547 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001548
1549 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001550 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001551 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 PyTuple_SET_ITEM(retval, 1, Py_None);
1553 } else {
1554 v = PyUnicode_FromString(cipher_protocol);
1555 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001556 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001557 PyTuple_SET_ITEM(retval, 1, v);
1558 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001559
1560 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001561 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001562 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001564
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001565 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001566
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001567 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 Py_DECREF(retval);
1569 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001570}
1571
Christian Heimes25bfcd52016-09-06 00:04:45 +02001572#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1573static PyObject *
1574cipher_to_dict(const SSL_CIPHER *cipher)
1575{
1576 const char *cipher_name, *cipher_protocol;
1577
1578 unsigned long cipher_id;
1579 int alg_bits, strength_bits, len;
1580 char buf[512] = {0};
1581#if OPENSSL_VERSION_1_1
1582 int aead, nid;
1583 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1584#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001585
1586 /* can be NULL */
1587 cipher_name = SSL_CIPHER_get_name(cipher);
1588 cipher_protocol = SSL_CIPHER_get_version(cipher);
1589 cipher_id = SSL_CIPHER_get_id(cipher);
1590 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001591 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1592 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001593 if (len > 1 && buf[len-1] == '\n')
1594 buf[len-1] = '\0';
1595 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1596
1597#if OPENSSL_VERSION_1_1
1598 aead = SSL_CIPHER_is_aead(cipher);
1599 nid = SSL_CIPHER_get_cipher_nid(cipher);
1600 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1601 nid = SSL_CIPHER_get_digest_nid(cipher);
1602 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1603 nid = SSL_CIPHER_get_kx_nid(cipher);
1604 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1605 nid = SSL_CIPHER_get_auth_nid(cipher);
1606 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1607#endif
1608
Victor Stinner410b9882016-09-12 12:00:23 +02001609 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001610 "{sksssssssisi"
1611#if OPENSSL_VERSION_1_1
1612 "sOssssssss"
1613#endif
1614 "}",
1615 "id", cipher_id,
1616 "name", cipher_name,
1617 "protocol", cipher_protocol,
1618 "description", buf,
1619 "strength_bits", strength_bits,
1620 "alg_bits", alg_bits
1621#if OPENSSL_VERSION_1_1
1622 ,"aead", aead ? Py_True : Py_False,
1623 "symmetric", skcipher,
1624 "digest", digest,
1625 "kea", kx,
1626 "auth", auth
1627#endif
1628 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001629}
1630#endif
1631
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001632/*[clinic input]
1633_ssl._SSLSocket.shared_ciphers
1634[clinic start generated code]*/
1635
1636static PyObject *
1637_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1638/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001639{
1640 STACK_OF(SSL_CIPHER) *ciphers;
1641 int i;
1642 PyObject *res;
1643
Christian Heimes598894f2016-09-05 23:19:05 +02001644 ciphers = SSL_get_ciphers(self->ssl);
1645 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001646 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001647 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1648 if (!res)
1649 return NULL;
1650 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1651 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1652 if (!tup) {
1653 Py_DECREF(res);
1654 return NULL;
1655 }
1656 PyList_SET_ITEM(res, i, tup);
1657 }
1658 return res;
1659}
1660
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001661/*[clinic input]
1662_ssl._SSLSocket.cipher
1663[clinic start generated code]*/
1664
1665static PyObject *
1666_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1667/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001668{
1669 const SSL_CIPHER *current;
1670
1671 if (self->ssl == NULL)
1672 Py_RETURN_NONE;
1673 current = SSL_get_current_cipher(self->ssl);
1674 if (current == NULL)
1675 Py_RETURN_NONE;
1676 return cipher_to_tuple(current);
1677}
1678
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001679/*[clinic input]
1680_ssl._SSLSocket.version
1681[clinic start generated code]*/
1682
1683static PyObject *
1684_ssl__SSLSocket_version_impl(PySSLSocket *self)
1685/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001686{
1687 const char *version;
1688
1689 if (self->ssl == NULL)
1690 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001691 if (!SSL_is_init_finished(self->ssl)) {
1692 /* handshake not finished */
1693 Py_RETURN_NONE;
1694 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001695 version = SSL_get_version(self->ssl);
1696 if (!strcmp(version, "unknown"))
1697 Py_RETURN_NONE;
1698 return PyUnicode_FromString(version);
1699}
1700
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001701#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001702/*[clinic input]
1703_ssl._SSLSocket.selected_npn_protocol
1704[clinic start generated code]*/
1705
1706static PyObject *
1707_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1708/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1709{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001710 const unsigned char *out;
1711 unsigned int outlen;
1712
Victor Stinner4569cd52013-06-23 14:58:43 +02001713 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001714 &out, &outlen);
1715
1716 if (out == NULL)
1717 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001718 return PyUnicode_FromStringAndSize((char *)out, outlen);
1719}
1720#endif
1721
1722#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001723/*[clinic input]
1724_ssl._SSLSocket.selected_alpn_protocol
1725[clinic start generated code]*/
1726
1727static PyObject *
1728_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1729/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1730{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001731 const unsigned char *out;
1732 unsigned int outlen;
1733
1734 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1735
1736 if (out == NULL)
1737 Py_RETURN_NONE;
1738 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001739}
1740#endif
1741
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001742/*[clinic input]
1743_ssl._SSLSocket.compression
1744[clinic start generated code]*/
1745
1746static PyObject *
1747_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1748/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1749{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001750#ifdef OPENSSL_NO_COMP
1751 Py_RETURN_NONE;
1752#else
1753 const COMP_METHOD *comp_method;
1754 const char *short_name;
1755
1756 if (self->ssl == NULL)
1757 Py_RETURN_NONE;
1758 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001759 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001760 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001761 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001762 if (short_name == NULL)
1763 Py_RETURN_NONE;
1764 return PyUnicode_DecodeFSDefault(short_name);
1765#endif
1766}
1767
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001768static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1769 Py_INCREF(self->ctx);
1770 return self->ctx;
1771}
1772
1773static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1774 void *closure) {
1775
1776 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001777#if !HAVE_SNI
1778 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1779 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001780 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001781#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001782 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001783 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001784 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001785#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001786 } else {
1787 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1788 return -1;
1789 }
1790
1791 return 0;
1792}
1793
1794PyDoc_STRVAR(PySSL_set_context_doc,
1795"_setter_context(ctx)\n\
1796\
1797This changes the context associated with the SSLSocket. This is typically\n\
1798used from within a callback function set by the set_servername_callback\n\
1799on the SSLContext to change the certificate information associated with the\n\
1800SSLSocket before the cryptographic exchange handshake messages\n");
1801
1802
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001803static PyObject *
1804PySSL_get_server_side(PySSLSocket *self, void *c)
1805{
1806 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1807}
1808
1809PyDoc_STRVAR(PySSL_get_server_side_doc,
1810"Whether this is a server-side socket.");
1811
1812static PyObject *
1813PySSL_get_server_hostname(PySSLSocket *self, void *c)
1814{
1815 if (self->server_hostname == NULL)
1816 Py_RETURN_NONE;
1817 Py_INCREF(self->server_hostname);
1818 return self->server_hostname;
1819}
1820
1821PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1822"The currently set server hostname (for SNI).");
1823
1824static PyObject *
1825PySSL_get_owner(PySSLSocket *self, void *c)
1826{
1827 PyObject *owner;
1828
1829 if (self->owner == NULL)
1830 Py_RETURN_NONE;
1831
1832 owner = PyWeakref_GetObject(self->owner);
1833 Py_INCREF(owner);
1834 return owner;
1835}
1836
1837static int
1838PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1839{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001840 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001841 if (self->owner == NULL)
1842 return -1;
1843 return 0;
1844}
1845
1846PyDoc_STRVAR(PySSL_get_owner_doc,
1847"The Python-level owner of this object.\
1848Passed as \"self\" in servername callback.");
1849
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001850
Antoine Pitrou152efa22010-05-16 18:19:27 +00001851static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001852{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001853 if (self->ssl)
1854 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001855 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001856 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001857 Py_XDECREF(self->server_hostname);
1858 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001859 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001860}
1861
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001862/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001863 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001864 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001865 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001866
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001867static int
Victor Stinner14690702015-04-06 22:46:13 +02001868PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001869{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001870 int rc;
1871#ifdef HAVE_POLL
1872 struct pollfd pollfd;
1873 _PyTime_t ms;
1874#else
1875 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001876 fd_set fds;
1877 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001878#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001879
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001880 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001881 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001882 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001883 else if (timeout < 0) {
1884 if (s->sock_timeout > 0)
1885 return SOCKET_HAS_TIMED_OUT;
1886 else
1887 return SOCKET_IS_BLOCKING;
1888 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001889
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001890 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001891 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001892 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001893
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001894 /* Prefer poll, if available, since you can poll() any fd
1895 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001896#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001897 pollfd.fd = s->sock_fd;
1898 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001899
Victor Stinner14690702015-04-06 22:46:13 +02001900 /* timeout is in seconds, poll() uses milliseconds */
1901 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001902 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001903
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001904 PySSL_BEGIN_ALLOW_THREADS
1905 rc = poll(&pollfd, 1, (int)ms);
1906 PySSL_END_ALLOW_THREADS
1907#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001908 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02001909 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001910 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00001911
Victor Stinner14690702015-04-06 22:46:13 +02001912 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01001913
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001914 FD_ZERO(&fds);
1915 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001916
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001917 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001918 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001919 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001920 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001921 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001922 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001923 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001924 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00001925#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001926
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001927 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
1928 (when we are able to write or when there's something to read) */
1929 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001930}
1931
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001932/*[clinic input]
1933_ssl._SSLSocket.write
1934 b: Py_buffer
1935 /
1936
1937Writes the bytes-like object b into the SSL object.
1938
1939Returns the number of bytes written.
1940[clinic start generated code]*/
1941
1942static PyObject *
1943_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
1944/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001945{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001946 int len;
1947 int sockstate;
1948 int err;
1949 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001950 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02001951 _PyTime_t timeout, deadline = 0;
1952 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00001953
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001954 if (sock != NULL) {
1955 if (((PyObject*)sock) == Py_None) {
1956 _setSSLError("Underlying socket connection gone",
1957 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
1958 return NULL;
1959 }
1960 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 }
1962
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001963 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02001964 PyErr_Format(PyExc_OverflowError,
1965 "string longer than %d bytes", INT_MAX);
1966 goto error;
1967 }
1968
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001969 if (sock != NULL) {
1970 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01001971 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001972 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
1973 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
1974 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001975
Victor Stinner14690702015-04-06 22:46:13 +02001976 timeout = GET_SOCKET_TIMEOUT(sock);
1977 has_timeout = (timeout > 0);
1978 if (has_timeout)
1979 deadline = _PyTime_GetMonotonicClock() + timeout;
1980
1981 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00001983 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 "The write operation timed out");
1985 goto error;
1986 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
1987 PyErr_SetString(PySSLErrorObject,
1988 "Underlying socket has been closed.");
1989 goto error;
1990 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
1991 PyErr_SetString(PySSLErrorObject,
1992 "Underlying socket too large for select().");
1993 goto error;
1994 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001997 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001998 len = SSL_write(self->ssl, b->buf, (int)b->len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 err = SSL_get_error(self->ssl, len);
2000 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002001
2002 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002003 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002004
Victor Stinner14690702015-04-06 22:46:13 +02002005 if (has_timeout)
2006 timeout = deadline - _PyTime_GetMonotonicClock();
2007
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002008 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002009 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002011 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 } else {
2013 sockstate = SOCKET_OPERATION_OK;
2014 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002017 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002018 "The write operation timed out");
2019 goto error;
2020 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2021 PyErr_SetString(PySSLErrorObject,
2022 "Underlying socket has been closed.");
2023 goto error;
2024 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2025 break;
2026 }
2027 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002028
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002029 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002030 if (len > 0)
2031 return PyLong_FromLong(len);
2032 else
2033 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002034
2035error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002036 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002037 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002038}
2039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002040/*[clinic input]
2041_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002042
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002043Returns the number of already decrypted bytes available for read, pending on the connection.
2044[clinic start generated code]*/
2045
2046static PyObject *
2047_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2048/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002049{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002050 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002052 PySSL_BEGIN_ALLOW_THREADS
2053 count = SSL_pending(self->ssl);
2054 PySSL_END_ALLOW_THREADS
2055 if (count < 0)
2056 return PySSL_SetError(self, count, __FILE__, __LINE__);
2057 else
2058 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002059}
2060
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002061/*[clinic input]
2062_ssl._SSLSocket.read
2063 size as len: int
2064 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002065 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002066 ]
2067 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002069Read up to size bytes from the SSL socket.
2070[clinic start generated code]*/
2071
2072static PyObject *
2073_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2074 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002075/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002076{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002078 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002079 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002080 int sockstate;
2081 int err;
2082 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002083 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002084 _PyTime_t timeout, deadline = 0;
2085 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002086
Martin Panter5503d472016-03-27 05:35:19 +00002087 if (!group_right_1 && len < 0) {
2088 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2089 return NULL;
2090 }
2091
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002092 if (sock != NULL) {
2093 if (((PyObject*)sock) == Py_None) {
2094 _setSSLError("Underlying socket connection gone",
2095 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2096 return NULL;
2097 }
2098 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002099 }
2100
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002101 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002102 dest = PyBytes_FromStringAndSize(NULL, len);
2103 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002104 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002105 if (len == 0) {
2106 Py_XDECREF(sock);
2107 return dest;
2108 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002109 mem = PyBytes_AS_STRING(dest);
2110 }
2111 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002112 mem = buffer->buf;
2113 if (len <= 0 || len > buffer->len) {
2114 len = (int) buffer->len;
2115 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002116 PyErr_SetString(PyExc_OverflowError,
2117 "maximum length can't fit in a C 'int'");
2118 goto error;
2119 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002120 if (len == 0) {
2121 count = 0;
2122 goto done;
2123 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002124 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002125 }
2126
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002127 if (sock != NULL) {
2128 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002129 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002130 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2131 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2132 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133
Victor Stinner14690702015-04-06 22:46:13 +02002134 timeout = GET_SOCKET_TIMEOUT(sock);
2135 has_timeout = (timeout > 0);
2136 if (has_timeout)
2137 deadline = _PyTime_GetMonotonicClock() + timeout;
2138
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002139 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 PySSL_BEGIN_ALLOW_THREADS
2141 count = SSL_read(self->ssl, mem, len);
2142 err = SSL_get_error(self->ssl, count);
2143 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002144
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002145 if (PyErr_CheckSignals())
2146 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002147
Victor Stinner14690702015-04-06 22:46:13 +02002148 if (has_timeout)
2149 timeout = deadline - _PyTime_GetMonotonicClock();
2150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002151 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002152 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002154 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002155 } else if (err == SSL_ERROR_ZERO_RETURN &&
2156 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002157 {
2158 count = 0;
2159 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002161 else
2162 sockstate = SOCKET_OPERATION_OK;
2163
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002164 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002165 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002166 "The read operation timed out");
2167 goto error;
2168 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2169 break;
2170 }
2171 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002172
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002173 if (count <= 0) {
2174 PySSL_SetError(self, count, __FILE__, __LINE__);
2175 goto error;
2176 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002177
2178done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002179 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002180 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002181 _PyBytes_Resize(&dest, count);
2182 return dest;
2183 }
2184 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002185 return PyLong_FromLong(count);
2186 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002187
2188error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002189 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002190 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002191 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002192 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002193}
2194
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002195/*[clinic input]
2196_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002197
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002198Does the SSL shutdown handshake with the remote end.
2199
2200Returns the underlying socket object.
2201[clinic start generated code]*/
2202
2203static PyObject *
2204_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2205/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002206{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002207 int err, ssl_err, sockstate, nonblocking;
2208 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002209 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002210 _PyTime_t timeout, deadline = 0;
2211 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002212
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002213 if (sock != NULL) {
2214 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002215 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002216 _setSSLError("Underlying socket connection gone",
2217 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2218 return NULL;
2219 }
2220 Py_INCREF(sock);
2221
2222 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002223 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002224 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2225 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002226 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002227
Victor Stinner14690702015-04-06 22:46:13 +02002228 timeout = GET_SOCKET_TIMEOUT(sock);
2229 has_timeout = (timeout > 0);
2230 if (has_timeout)
2231 deadline = _PyTime_GetMonotonicClock() + timeout;
2232
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002233 while (1) {
2234 PySSL_BEGIN_ALLOW_THREADS
2235 /* Disable read-ahead so that unwrap can work correctly.
2236 * Otherwise OpenSSL might read in too much data,
2237 * eating clear text data that happens to be
2238 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002239 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002240 * function is used and the shutdown_seen_zero != 0
2241 * condition is met.
2242 */
2243 if (self->shutdown_seen_zero)
2244 SSL_set_read_ahead(self->ssl, 0);
2245 err = SSL_shutdown(self->ssl);
2246 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002247
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002248 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2249 if (err > 0)
2250 break;
2251 if (err == 0) {
2252 /* Don't loop endlessly; instead preserve legacy
2253 behaviour of trying SSL_shutdown() only twice.
2254 This looks necessary for OpenSSL < 0.9.8m */
2255 if (++zeros > 1)
2256 break;
2257 /* Shutdown was sent, now try receiving */
2258 self->shutdown_seen_zero = 1;
2259 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002260 }
2261
Victor Stinner14690702015-04-06 22:46:13 +02002262 if (has_timeout)
2263 timeout = deadline - _PyTime_GetMonotonicClock();
2264
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 /* Possibly retry shutdown until timeout or failure */
2266 ssl_err = SSL_get_error(self->ssl, err);
2267 if (ssl_err == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002268 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 else if (ssl_err == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002270 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 else
2272 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002273
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002274 if (sockstate == SOCKET_HAS_TIMED_OUT) {
2275 if (ssl_err == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002276 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002277 "The read operation timed out");
2278 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002279 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002280 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002281 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002282 }
2283 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2284 PyErr_SetString(PySSLErrorObject,
2285 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002286 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002287 }
2288 else if (sockstate != SOCKET_OPERATION_OK)
2289 /* Retain the SSL error code */
2290 break;
2291 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002292
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002293 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002294 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002295 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002296 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002297 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002298 /* It's already INCREF'ed */
2299 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002300 else
2301 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002302
2303error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002304 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002305 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002306}
2307
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002308/*[clinic input]
2309_ssl._SSLSocket.tls_unique_cb
2310
2311Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2312
2313If the TLS handshake is not yet complete, None is returned.
2314[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002315
Antoine Pitroud6494802011-07-21 01:11:30 +02002316static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002317_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2318/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002319{
2320 PyObject *retval = NULL;
2321 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002322 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002323
2324 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2325 /* if session is resumed XOR we are the client */
2326 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2327 }
2328 else {
2329 /* if a new session XOR we are the server */
2330 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2331 }
2332
2333 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002334 if (len == 0)
2335 Py_RETURN_NONE;
2336
2337 retval = PyBytes_FromStringAndSize(buf, len);
2338
2339 return retval;
2340}
2341
Christian Heimes99a65702016-09-10 23:44:53 +02002342#ifdef OPENSSL_VERSION_1_1
2343
2344static SSL_SESSION*
2345_ssl_session_dup(SSL_SESSION *session) {
2346 SSL_SESSION *newsession = NULL;
2347 int slen;
2348 unsigned char *senc = NULL, *p;
2349 const unsigned char *const_p;
2350
2351 if (session == NULL) {
2352 PyErr_SetString(PyExc_ValueError, "Invalid session");
2353 goto error;
2354 }
2355
2356 /* get length */
2357 slen = i2d_SSL_SESSION(session, NULL);
2358 if (slen == 0 || slen > 0xFF00) {
2359 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2360 goto error;
2361 }
2362 if ((senc = PyMem_Malloc(slen)) == NULL) {
2363 PyErr_NoMemory();
2364 goto error;
2365 }
2366 p = senc;
2367 if (!i2d_SSL_SESSION(session, &p)) {
2368 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2369 goto error;
2370 }
2371 const_p = senc;
2372 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2373 if (session == NULL) {
2374 goto error;
2375 }
2376 PyMem_Free(senc);
2377 return newsession;
2378 error:
2379 if (senc != NULL) {
2380 PyMem_Free(senc);
2381 }
2382 return NULL;
2383}
2384#endif
2385
2386static PyObject *
2387PySSL_get_session(PySSLSocket *self, void *closure) {
2388 /* get_session can return sessions from a server-side connection,
2389 * it does not check for handshake done or client socket. */
2390 PySSLSession *pysess;
2391 SSL_SESSION *session;
2392
2393#ifdef OPENSSL_VERSION_1_1
2394 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2395 * https://github.com/openssl/openssl/issues/1550 */
2396 session = SSL_get0_session(self->ssl); /* borrowed reference */
2397 if (session == NULL) {
2398 Py_RETURN_NONE;
2399 }
2400 if ((session = _ssl_session_dup(session)) == NULL) {
2401 return NULL;
2402 }
2403#else
2404 session = SSL_get1_session(self->ssl);
2405 if (session == NULL) {
2406 Py_RETURN_NONE;
2407 }
2408#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002409 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002410 if (pysess == NULL) {
2411 SSL_SESSION_free(session);
2412 return NULL;
2413 }
2414
2415 assert(self->ctx);
2416 pysess->ctx = self->ctx;
2417 Py_INCREF(pysess->ctx);
2418 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002419 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002420 return (PyObject *)pysess;
2421}
2422
2423static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2424 void *closure)
2425 {
2426 PySSLSession *pysess;
2427#ifdef OPENSSL_VERSION_1_1
2428 SSL_SESSION *session;
2429#endif
2430 int result;
2431
2432 if (!PySSLSession_Check(value)) {
2433 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2434 return -1;
2435 }
2436 pysess = (PySSLSession *)value;
2437
2438 if (self->ctx->ctx != pysess->ctx->ctx) {
2439 PyErr_SetString(PyExc_ValueError,
2440 "Session refers to a different SSLContext.");
2441 return -1;
2442 }
2443 if (self->socket_type != PY_SSL_CLIENT) {
2444 PyErr_SetString(PyExc_ValueError,
2445 "Cannot set session for server-side SSLSocket.");
2446 return -1;
2447 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002448 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002449 PyErr_SetString(PyExc_ValueError,
2450 "Cannot set session after handshake.");
2451 return -1;
2452 }
2453#ifdef OPENSSL_VERSION_1_1
2454 /* duplicate session */
2455 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2456 return -1;
2457 }
2458 result = SSL_set_session(self->ssl, session);
2459 /* free duplicate, SSL_set_session() bumps ref count */
2460 SSL_SESSION_free(session);
2461#else
2462 result = SSL_set_session(self->ssl, pysess->session);
2463#endif
2464 if (result == 0) {
2465 _setSSLError(NULL, 0, __FILE__, __LINE__);
2466 return -1;
2467 }
2468 return 0;
2469}
2470
2471PyDoc_STRVAR(PySSL_set_session_doc,
2472"_setter_session(session)\n\
2473\
2474Get / set SSLSession.");
2475
2476static PyObject *
2477PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2478 if (SSL_session_reused(self->ssl)) {
2479 Py_RETURN_TRUE;
2480 } else {
2481 Py_RETURN_FALSE;
2482 }
2483}
2484
2485PyDoc_STRVAR(PySSL_get_session_reused_doc,
2486"Was the client session reused during handshake?");
2487
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002488static PyGetSetDef ssl_getsetlist[] = {
2489 {"context", (getter) PySSL_get_context,
2490 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002491 {"server_side", (getter) PySSL_get_server_side, NULL,
2492 PySSL_get_server_side_doc},
2493 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2494 PySSL_get_server_hostname_doc},
2495 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2496 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002497 {"session", (getter) PySSL_get_session,
2498 (setter) PySSL_set_session, PySSL_set_session_doc},
2499 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2500 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002501 {NULL}, /* sentinel */
2502};
2503
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002504static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002505 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2506 _SSL__SSLSOCKET_WRITE_METHODDEF
2507 _SSL__SSLSOCKET_READ_METHODDEF
2508 _SSL__SSLSOCKET_PENDING_METHODDEF
2509 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2510 _SSL__SSLSOCKET_CIPHER_METHODDEF
2511 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2512 _SSL__SSLSOCKET_VERSION_METHODDEF
2513 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2514 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2515 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2516 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2517 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002518 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002519};
2520
Antoine Pitrou152efa22010-05-16 18:19:27 +00002521static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002522 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002523 "_ssl._SSLSocket", /*tp_name*/
2524 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002525 0, /*tp_itemsize*/
2526 /* methods */
2527 (destructor)PySSL_dealloc, /*tp_dealloc*/
2528 0, /*tp_print*/
2529 0, /*tp_getattr*/
2530 0, /*tp_setattr*/
2531 0, /*tp_reserved*/
2532 0, /*tp_repr*/
2533 0, /*tp_as_number*/
2534 0, /*tp_as_sequence*/
2535 0, /*tp_as_mapping*/
2536 0, /*tp_hash*/
2537 0, /*tp_call*/
2538 0, /*tp_str*/
2539 0, /*tp_getattro*/
2540 0, /*tp_setattro*/
2541 0, /*tp_as_buffer*/
2542 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2543 0, /*tp_doc*/
2544 0, /*tp_traverse*/
2545 0, /*tp_clear*/
2546 0, /*tp_richcompare*/
2547 0, /*tp_weaklistoffset*/
2548 0, /*tp_iter*/
2549 0, /*tp_iternext*/
2550 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002551 0, /*tp_members*/
2552 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002553};
2554
Antoine Pitrou152efa22010-05-16 18:19:27 +00002555
2556/*
2557 * _SSLContext objects
2558 */
2559
Christian Heimes5fe668c2016-09-12 00:01:11 +02002560static int
2561_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2562{
2563 int mode;
2564 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2565
2566 switch(n) {
2567 case PY_SSL_CERT_NONE:
2568 mode = SSL_VERIFY_NONE;
2569 break;
2570 case PY_SSL_CERT_OPTIONAL:
2571 mode = SSL_VERIFY_PEER;
2572 break;
2573 case PY_SSL_CERT_REQUIRED:
2574 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2575 break;
2576 default:
2577 PyErr_SetString(PyExc_ValueError,
2578 "invalid value for verify_mode");
2579 return -1;
2580 }
2581 /* keep current verify cb */
2582 verify_cb = SSL_CTX_get_verify_callback(ctx);
2583 SSL_CTX_set_verify(ctx, mode, verify_cb);
2584 return 0;
2585}
2586
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002587/*[clinic input]
2588@classmethod
2589_ssl._SSLContext.__new__
2590 protocol as proto_version: int
2591 /
2592[clinic start generated code]*/
2593
Antoine Pitrou152efa22010-05-16 18:19:27 +00002594static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002595_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2596/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002597{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002598 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002599 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002600 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002601 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002602#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002603 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002604#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002605
Antoine Pitrou152efa22010-05-16 18:19:27 +00002606 PySSL_BEGIN_ALLOW_THREADS
2607 if (proto_version == PY_SSL_VERSION_TLS1)
2608 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002609#if HAVE_TLSv1_2
2610 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2611 ctx = SSL_CTX_new(TLSv1_1_method());
2612 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2613 ctx = SSL_CTX_new(TLSv1_2_method());
2614#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002615#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002616 else if (proto_version == PY_SSL_VERSION_SSL3)
2617 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002618#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002619#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002620 else if (proto_version == PY_SSL_VERSION_SSL2)
2621 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002622#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002623 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002624 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002625 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2626 ctx = SSL_CTX_new(TLS_client_method());
2627 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2628 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002629 else
2630 proto_version = -1;
2631 PySSL_END_ALLOW_THREADS
2632
2633 if (proto_version == -1) {
2634 PyErr_SetString(PyExc_ValueError,
2635 "invalid protocol version");
2636 return NULL;
2637 }
2638 if (ctx == NULL) {
2639 PyErr_SetString(PySSLErrorObject,
2640 "failed to allocate SSL context");
2641 return NULL;
2642 }
2643
2644 assert(type != NULL && type->tp_alloc != NULL);
2645 self = (PySSLContext *) type->tp_alloc(type, 0);
2646 if (self == NULL) {
2647 SSL_CTX_free(ctx);
2648 return NULL;
2649 }
2650 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002651#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002652 self->npn_protocols = NULL;
2653#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002654#ifdef HAVE_ALPN
2655 self->alpn_protocols = NULL;
2656#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002657#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002658 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002659#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002660 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002661 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2662 self->check_hostname = 1;
2663 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2664 Py_DECREF(self);
2665 return NULL;
2666 }
2667 } else {
2668 self->check_hostname = 0;
2669 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2670 Py_DECREF(self);
2671 return NULL;
2672 }
2673 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002674 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002675 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2676 if (proto_version != PY_SSL_VERSION_SSL2)
2677 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002678 if (proto_version != PY_SSL_VERSION_SSL3)
2679 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002680 /* Minimal security flags for server and client side context.
2681 * Client sockets ignore server-side parameters. */
2682#ifdef SSL_OP_NO_COMPRESSION
2683 options |= SSL_OP_NO_COMPRESSION;
2684#endif
2685#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2686 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2687#endif
2688#ifdef SSL_OP_SINGLE_DH_USE
2689 options |= SSL_OP_SINGLE_DH_USE;
2690#endif
2691#ifdef SSL_OP_SINGLE_ECDH_USE
2692 options |= SSL_OP_SINGLE_ECDH_USE;
2693#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002694 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002695
Christian Heimes358cfd42016-09-10 22:43:48 +02002696 /* A bare minimum cipher list without completly broken cipher suites.
2697 * It's far from perfect but gives users a better head start. */
2698 if (proto_version != PY_SSL_VERSION_SSL2) {
2699 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2700 } else {
2701 /* SSLv2 needs MD5 */
2702 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2703 }
2704 if (result == 0) {
2705 Py_DECREF(self);
2706 ERR_clear_error();
2707 PyErr_SetString(PySSLErrorObject,
2708 "No cipher can be selected.");
2709 return NULL;
2710 }
2711
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002712#if defined(SSL_MODE_RELEASE_BUFFERS)
2713 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2714 usage for no cost at all. However, don't do this for OpenSSL versions
2715 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2716 2014-0198. I can't find exactly which beta fixed this CVE, so be
2717 conservative and assume it wasn't fixed until release. We do this check
2718 at runtime to avoid problems from the dynamic linker.
2719 See #25672 for more on this. */
2720 libver = SSLeay();
2721 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2722 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2723 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2724 }
2725#endif
2726
2727
Donald Stufft8ae264c2017-03-02 11:45:29 -05002728#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002729 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2730 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002731 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2732 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002733#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002734 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2735#else
2736 {
2737 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2738 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2739 EC_KEY_free(key);
2740 }
2741#endif
2742#endif
2743
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002744#define SID_CTX "Python"
2745 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2746 sizeof(SID_CTX));
2747#undef SID_CTX
2748
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002749#ifdef X509_V_FLAG_TRUSTED_FIRST
2750 {
2751 /* Improve trust chain building when cross-signed intermediate
2752 certificates are present. See https://bugs.python.org/issue23476. */
2753 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2754 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2755 }
2756#endif
2757
Antoine Pitrou152efa22010-05-16 18:19:27 +00002758 return (PyObject *)self;
2759}
2760
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002761static int
2762context_traverse(PySSLContext *self, visitproc visit, void *arg)
2763{
2764#ifndef OPENSSL_NO_TLSEXT
2765 Py_VISIT(self->set_hostname);
2766#endif
2767 return 0;
2768}
2769
2770static int
2771context_clear(PySSLContext *self)
2772{
2773#ifndef OPENSSL_NO_TLSEXT
2774 Py_CLEAR(self->set_hostname);
2775#endif
2776 return 0;
2777}
2778
Antoine Pitrou152efa22010-05-16 18:19:27 +00002779static void
2780context_dealloc(PySSLContext *self)
2781{
INADA Naokia6296d32017-08-24 14:55:17 +09002782 /* bpo-31095: UnTrack is needed before calling any callbacks */
2783 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002784 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002785 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002786#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002787 PyMem_FREE(self->npn_protocols);
2788#endif
2789#ifdef HAVE_ALPN
2790 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002791#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002792 Py_TYPE(self)->tp_free(self);
2793}
2794
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002795/*[clinic input]
2796_ssl._SSLContext.set_ciphers
2797 cipherlist: str
2798 /
2799[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002800
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002801static PyObject *
2802_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2803/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2804{
2805 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002806 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002807 /* Clearing the error queue is necessary on some OpenSSL versions,
2808 otherwise the error will be reported again when another SSL call
2809 is done. */
2810 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002811 PyErr_SetString(PySSLErrorObject,
2812 "No cipher can be selected.");
2813 return NULL;
2814 }
2815 Py_RETURN_NONE;
2816}
2817
Christian Heimes25bfcd52016-09-06 00:04:45 +02002818#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2819/*[clinic input]
2820_ssl._SSLContext.get_ciphers
2821[clinic start generated code]*/
2822
2823static PyObject *
2824_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2825/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2826{
2827 SSL *ssl = NULL;
2828 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002829 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002830 int i=0;
2831 PyObject *result = NULL, *dct;
2832
2833 ssl = SSL_new(self->ctx);
2834 if (ssl == NULL) {
2835 _setSSLError(NULL, 0, __FILE__, __LINE__);
2836 goto exit;
2837 }
2838 sk = SSL_get_ciphers(ssl);
2839
2840 result = PyList_New(sk_SSL_CIPHER_num(sk));
2841 if (result == NULL) {
2842 goto exit;
2843 }
2844
2845 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2846 cipher = sk_SSL_CIPHER_value(sk, i);
2847 dct = cipher_to_dict(cipher);
2848 if (dct == NULL) {
2849 Py_CLEAR(result);
2850 goto exit;
2851 }
2852 PyList_SET_ITEM(result, i, dct);
2853 }
2854
2855 exit:
2856 if (ssl != NULL)
2857 SSL_free(ssl);
2858 return result;
2859
2860}
2861#endif
2862
2863
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002864#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002865static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002866do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2867 const unsigned char *server_protocols, unsigned int server_protocols_len,
2868 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002869{
Benjamin Peterson88615022015-01-23 17:30:26 -05002870 int ret;
2871 if (client_protocols == NULL) {
2872 client_protocols = (unsigned char *)"";
2873 client_protocols_len = 0;
2874 }
2875 if (server_protocols == NULL) {
2876 server_protocols = (unsigned char *)"";
2877 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002878 }
2879
Benjamin Peterson88615022015-01-23 17:30:26 -05002880 ret = SSL_select_next_proto(out, outlen,
2881 server_protocols, server_protocols_len,
2882 client_protocols, client_protocols_len);
2883 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2884 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002885
2886 return SSL_TLSEXT_ERR_OK;
2887}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002888#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002889
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002890#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002891/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2892static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002893_advertiseNPN_cb(SSL *s,
2894 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002895 void *args)
2896{
2897 PySSLContext *ssl_ctx = (PySSLContext *) args;
2898
2899 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002900 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002901 *len = 0;
2902 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002903 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002904 *len = ssl_ctx->npn_protocols_len;
2905 }
2906
2907 return SSL_TLSEXT_ERR_OK;
2908}
2909/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2910static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002911_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002912 unsigned char **out, unsigned char *outlen,
2913 const unsigned char *server, unsigned int server_len,
2914 void *args)
2915{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002916 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002917 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002918 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002919}
2920#endif
2921
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002922/*[clinic input]
2923_ssl._SSLContext._set_npn_protocols
2924 protos: Py_buffer
2925 /
2926[clinic start generated code]*/
2927
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002928static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002929_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2930 Py_buffer *protos)
2931/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002932{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002933#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002934 PyMem_Free(self->npn_protocols);
2935 self->npn_protocols = PyMem_Malloc(protos->len);
2936 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002937 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002938 memcpy(self->npn_protocols, protos->buf, protos->len);
2939 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002940
2941 /* set both server and client callbacks, because the context can
2942 * be used to create both types of sockets */
2943 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2944 _advertiseNPN_cb,
2945 self);
2946 SSL_CTX_set_next_proto_select_cb(self->ctx,
2947 _selectNPN_cb,
2948 self);
2949
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002950 Py_RETURN_NONE;
2951#else
2952 PyErr_SetString(PyExc_NotImplementedError,
2953 "The NPN extension requires OpenSSL 1.0.1 or later.");
2954 return NULL;
2955#endif
2956}
2957
Benjamin Petersoncca27322015-01-23 16:35:37 -05002958#ifdef HAVE_ALPN
2959static int
2960_selectALPN_cb(SSL *s,
2961 const unsigned char **out, unsigned char *outlen,
2962 const unsigned char *client_protocols, unsigned int client_protocols_len,
2963 void *args)
2964{
2965 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002966 return do_protocol_selection(1, (unsigned char **)out, outlen,
2967 ctx->alpn_protocols, ctx->alpn_protocols_len,
2968 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002969}
2970#endif
2971
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002972/*[clinic input]
2973_ssl._SSLContext._set_alpn_protocols
2974 protos: Py_buffer
2975 /
2976[clinic start generated code]*/
2977
Benjamin Petersoncca27322015-01-23 16:35:37 -05002978static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002979_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2980 Py_buffer *protos)
2981/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002982{
2983#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03002984 if (protos->len > UINT_MAX) {
2985 PyErr_Format(PyExc_OverflowError,
2986 "protocols longer than %d bytes", UINT_MAX);
2987 return NULL;
2988 }
2989
Benjamin Petersoncca27322015-01-23 16:35:37 -05002990 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002991 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002992 if (!self->alpn_protocols)
2993 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002994 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03002995 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002996
2997 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2998 return PyErr_NoMemory();
2999 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3000
Benjamin Petersoncca27322015-01-23 16:35:37 -05003001 Py_RETURN_NONE;
3002#else
3003 PyErr_SetString(PyExc_NotImplementedError,
3004 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3005 return NULL;
3006#endif
3007}
3008
Antoine Pitrou152efa22010-05-16 18:19:27 +00003009static PyObject *
3010get_verify_mode(PySSLContext *self, void *c)
3011{
3012 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3013 case SSL_VERIFY_NONE:
3014 return PyLong_FromLong(PY_SSL_CERT_NONE);
3015 case SSL_VERIFY_PEER:
3016 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3017 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3018 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3019 }
3020 PyErr_SetString(PySSLErrorObject,
3021 "invalid return value from SSL_CTX_get_verify_mode");
3022 return NULL;
3023}
3024
3025static int
3026set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3027{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003028 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003029 if (!PyArg_Parse(arg, "i", &n))
3030 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003031 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003032 PyErr_SetString(PyExc_ValueError,
3033 "Cannot set verify_mode to CERT_NONE when "
3034 "check_hostname is enabled.");
3035 return -1;
3036 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003037 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003038}
3039
3040static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003041get_verify_flags(PySSLContext *self, void *c)
3042{
3043 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003044 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003045 unsigned long flags;
3046
3047 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003048 param = X509_STORE_get0_param(store);
3049 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003050 return PyLong_FromUnsignedLong(flags);
3051}
3052
3053static int
3054set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3055{
3056 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003057 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003058 unsigned long new_flags, flags, set, clear;
3059
3060 if (!PyArg_Parse(arg, "k", &new_flags))
3061 return -1;
3062 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003063 param = X509_STORE_get0_param(store);
3064 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003065 clear = flags & ~new_flags;
3066 set = ~flags & new_flags;
3067 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003068 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003069 _setSSLError(NULL, 0, __FILE__, __LINE__);
3070 return -1;
3071 }
3072 }
3073 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003074 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003075 _setSSLError(NULL, 0, __FILE__, __LINE__);
3076 return -1;
3077 }
3078 }
3079 return 0;
3080}
3081
3082static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003083get_options(PySSLContext *self, void *c)
3084{
3085 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3086}
3087
3088static int
3089set_options(PySSLContext *self, PyObject *arg, void *c)
3090{
3091 long new_opts, opts, set, clear;
3092 if (!PyArg_Parse(arg, "l", &new_opts))
3093 return -1;
3094 opts = SSL_CTX_get_options(self->ctx);
3095 clear = opts & ~new_opts;
3096 set = ~opts & new_opts;
3097 if (clear) {
3098#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3099 SSL_CTX_clear_options(self->ctx, clear);
3100#else
3101 PyErr_SetString(PyExc_ValueError,
3102 "can't clear options before OpenSSL 0.9.8m");
3103 return -1;
3104#endif
3105 }
3106 if (set)
3107 SSL_CTX_set_options(self->ctx, set);
3108 return 0;
3109}
3110
Christian Heimes1aa9a752013-12-02 02:41:19 +01003111static PyObject *
3112get_check_hostname(PySSLContext *self, void *c)
3113{
3114 return PyBool_FromLong(self->check_hostname);
3115}
3116
3117static int
3118set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3119{
3120 int check_hostname;
3121 if (!PyArg_Parse(arg, "p", &check_hostname))
3122 return -1;
3123 if (check_hostname &&
3124 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3125 PyErr_SetString(PyExc_ValueError,
3126 "check_hostname needs a SSL context with either "
3127 "CERT_OPTIONAL or CERT_REQUIRED");
3128 return -1;
3129 }
3130 self->check_hostname = check_hostname;
3131 return 0;
3132}
3133
3134
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003135typedef struct {
3136 PyThreadState *thread_state;
3137 PyObject *callable;
3138 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003139 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003140 int error;
3141} _PySSLPasswordInfo;
3142
3143static int
3144_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3145 const char *bad_type_error)
3146{
3147 /* Set the password and size fields of a _PySSLPasswordInfo struct
3148 from a unicode, bytes, or byte array object.
3149 The password field will be dynamically allocated and must be freed
3150 by the caller */
3151 PyObject *password_bytes = NULL;
3152 const char *data = NULL;
3153 Py_ssize_t size;
3154
3155 if (PyUnicode_Check(password)) {
3156 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3157 if (!password_bytes) {
3158 goto error;
3159 }
3160 data = PyBytes_AS_STRING(password_bytes);
3161 size = PyBytes_GET_SIZE(password_bytes);
3162 } else if (PyBytes_Check(password)) {
3163 data = PyBytes_AS_STRING(password);
3164 size = PyBytes_GET_SIZE(password);
3165 } else if (PyByteArray_Check(password)) {
3166 data = PyByteArray_AS_STRING(password);
3167 size = PyByteArray_GET_SIZE(password);
3168 } else {
3169 PyErr_SetString(PyExc_TypeError, bad_type_error);
3170 goto error;
3171 }
3172
Victor Stinner9ee02032013-06-23 15:08:23 +02003173 if (size > (Py_ssize_t)INT_MAX) {
3174 PyErr_Format(PyExc_ValueError,
3175 "password cannot be longer than %d bytes", INT_MAX);
3176 goto error;
3177 }
3178
Victor Stinner11ebff22013-07-07 17:07:52 +02003179 PyMem_Free(pw_info->password);
3180 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003181 if (!pw_info->password) {
3182 PyErr_SetString(PyExc_MemoryError,
3183 "unable to allocate password buffer");
3184 goto error;
3185 }
3186 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003187 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003188
3189 Py_XDECREF(password_bytes);
3190 return 1;
3191
3192error:
3193 Py_XDECREF(password_bytes);
3194 return 0;
3195}
3196
3197static int
3198_password_callback(char *buf, int size, int rwflag, void *userdata)
3199{
3200 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3201 PyObject *fn_ret = NULL;
3202
3203 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3204
3205 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003206 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003207 if (!fn_ret) {
3208 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3209 core python API, so we could use it to add a frame here */
3210 goto error;
3211 }
3212
3213 if (!_pwinfo_set(pw_info, fn_ret,
3214 "password callback must return a string")) {
3215 goto error;
3216 }
3217 Py_CLEAR(fn_ret);
3218 }
3219
3220 if (pw_info->size > size) {
3221 PyErr_Format(PyExc_ValueError,
3222 "password cannot be longer than %d bytes", size);
3223 goto error;
3224 }
3225
3226 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3227 memcpy(buf, pw_info->password, pw_info->size);
3228 return pw_info->size;
3229
3230error:
3231 Py_XDECREF(fn_ret);
3232 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3233 pw_info->error = 1;
3234 return -1;
3235}
3236
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003237/*[clinic input]
3238_ssl._SSLContext.load_cert_chain
3239 certfile: object
3240 keyfile: object = NULL
3241 password: object = NULL
3242
3243[clinic start generated code]*/
3244
Antoine Pitroub5218772010-05-21 09:56:06 +00003245static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003246_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3247 PyObject *keyfile, PyObject *password)
3248/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003249{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003250 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003251 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3252 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003253 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003254 int r;
3255
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003256 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003257 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003258 if (keyfile == Py_None)
3259 keyfile = NULL;
3260 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3261 PyErr_SetString(PyExc_TypeError,
3262 "certfile should be a valid filesystem path");
3263 return NULL;
3264 }
3265 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3266 PyErr_SetString(PyExc_TypeError,
3267 "keyfile should be a valid filesystem path");
3268 goto error;
3269 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003270 if (password && password != Py_None) {
3271 if (PyCallable_Check(password)) {
3272 pw_info.callable = password;
3273 } else if (!_pwinfo_set(&pw_info, password,
3274 "password should be a string or callable")) {
3275 goto error;
3276 }
3277 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3278 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3279 }
3280 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003281 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3282 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003283 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003284 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003285 if (pw_info.error) {
3286 ERR_clear_error();
3287 /* the password callback has already set the error information */
3288 }
3289 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003290 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003291 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003292 }
3293 else {
3294 _setSSLError(NULL, 0, __FILE__, __LINE__);
3295 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003296 goto error;
3297 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003298 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003299 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003300 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3301 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003302 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3303 Py_CLEAR(keyfile_bytes);
3304 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003305 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003306 if (pw_info.error) {
3307 ERR_clear_error();
3308 /* the password callback has already set the error information */
3309 }
3310 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003311 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003312 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003313 }
3314 else {
3315 _setSSLError(NULL, 0, __FILE__, __LINE__);
3316 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003317 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003318 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003319 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003320 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003321 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003322 if (r != 1) {
3323 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003324 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003325 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003326 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3327 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003328 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003329 Py_RETURN_NONE;
3330
3331error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003332 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3333 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003334 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003335 Py_XDECREF(keyfile_bytes);
3336 Py_XDECREF(certfile_bytes);
3337 return NULL;
3338}
3339
Christian Heimesefff7062013-11-21 03:35:02 +01003340/* internal helper function, returns -1 on error
3341 */
3342static int
3343_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3344 int filetype)
3345{
3346 BIO *biobuf = NULL;
3347 X509_STORE *store;
3348 int retval = 0, err, loaded = 0;
3349
3350 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3351
3352 if (len <= 0) {
3353 PyErr_SetString(PyExc_ValueError,
3354 "Empty certificate data");
3355 return -1;
3356 } else if (len > INT_MAX) {
3357 PyErr_SetString(PyExc_OverflowError,
3358 "Certificate data is too long.");
3359 return -1;
3360 }
3361
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003362 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003363 if (biobuf == NULL) {
3364 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3365 return -1;
3366 }
3367
3368 store = SSL_CTX_get_cert_store(self->ctx);
3369 assert(store != NULL);
3370
3371 while (1) {
3372 X509 *cert = NULL;
3373 int r;
3374
3375 if (filetype == SSL_FILETYPE_ASN1) {
3376 cert = d2i_X509_bio(biobuf, NULL);
3377 } else {
3378 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003379 SSL_CTX_get_default_passwd_cb(self->ctx),
3380 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3381 );
Christian Heimesefff7062013-11-21 03:35:02 +01003382 }
3383 if (cert == NULL) {
3384 break;
3385 }
3386 r = X509_STORE_add_cert(store, cert);
3387 X509_free(cert);
3388 if (!r) {
3389 err = ERR_peek_last_error();
3390 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3391 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3392 /* cert already in hash table, not an error */
3393 ERR_clear_error();
3394 } else {
3395 break;
3396 }
3397 }
3398 loaded++;
3399 }
3400
3401 err = ERR_peek_last_error();
3402 if ((filetype == SSL_FILETYPE_ASN1) &&
3403 (loaded > 0) &&
3404 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3405 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3406 /* EOF ASN1 file, not an error */
3407 ERR_clear_error();
3408 retval = 0;
3409 } else if ((filetype == SSL_FILETYPE_PEM) &&
3410 (loaded > 0) &&
3411 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3412 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3413 /* EOF PEM file, not an error */
3414 ERR_clear_error();
3415 retval = 0;
3416 } else {
3417 _setSSLError(NULL, 0, __FILE__, __LINE__);
3418 retval = -1;
3419 }
3420
3421 BIO_free(biobuf);
3422 return retval;
3423}
3424
3425
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003426/*[clinic input]
3427_ssl._SSLContext.load_verify_locations
3428 cafile: object = NULL
3429 capath: object = NULL
3430 cadata: object = NULL
3431
3432[clinic start generated code]*/
3433
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003435_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3436 PyObject *cafile,
3437 PyObject *capath,
3438 PyObject *cadata)
3439/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003440{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003441 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3442 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003443 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003444
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003445 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003446 if (cafile == Py_None)
3447 cafile = NULL;
3448 if (capath == Py_None)
3449 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003450 if (cadata == Py_None)
3451 cadata = NULL;
3452
3453 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003454 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003455 "cafile, capath and cadata cannot be all omitted");
3456 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003457 }
3458 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3459 PyErr_SetString(PyExc_TypeError,
3460 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003461 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003462 }
3463 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003464 PyErr_SetString(PyExc_TypeError,
3465 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003466 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003467 }
Christian Heimesefff7062013-11-21 03:35:02 +01003468
3469 /* validata cadata type and load cadata */
3470 if (cadata) {
3471 Py_buffer buf;
3472 PyObject *cadata_ascii = NULL;
3473
3474 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3475 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3476 PyBuffer_Release(&buf);
3477 PyErr_SetString(PyExc_TypeError,
3478 "cadata should be a contiguous buffer with "
3479 "a single dimension");
3480 goto error;
3481 }
3482 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3483 PyBuffer_Release(&buf);
3484 if (r == -1) {
3485 goto error;
3486 }
3487 } else {
3488 PyErr_Clear();
3489 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3490 if (cadata_ascii == NULL) {
3491 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003492 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003493 "bytes-like object");
3494 goto error;
3495 }
3496 r = _add_ca_certs(self,
3497 PyBytes_AS_STRING(cadata_ascii),
3498 PyBytes_GET_SIZE(cadata_ascii),
3499 SSL_FILETYPE_PEM);
3500 Py_DECREF(cadata_ascii);
3501 if (r == -1) {
3502 goto error;
3503 }
3504 }
3505 }
3506
3507 /* load cafile or capath */
3508 if (cafile || capath) {
3509 if (cafile)
3510 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3511 if (capath)
3512 capath_buf = PyBytes_AS_STRING(capath_bytes);
3513 PySSL_BEGIN_ALLOW_THREADS
3514 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3515 PySSL_END_ALLOW_THREADS
3516 if (r != 1) {
3517 ok = 0;
3518 if (errno != 0) {
3519 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003520 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003521 }
3522 else {
3523 _setSSLError(NULL, 0, __FILE__, __LINE__);
3524 }
3525 goto error;
3526 }
3527 }
3528 goto end;
3529
3530 error:
3531 ok = 0;
3532 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003533 Py_XDECREF(cafile_bytes);
3534 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003535 if (ok) {
3536 Py_RETURN_NONE;
3537 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003538 return NULL;
3539 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003540}
3541
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003542/*[clinic input]
3543_ssl._SSLContext.load_dh_params
3544 path as filepath: object
3545 /
3546
3547[clinic start generated code]*/
3548
Antoine Pitrou152efa22010-05-16 18:19:27 +00003549static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003550_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3551/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003552{
3553 FILE *f;
3554 DH *dh;
3555
Victor Stinnerdaf45552013-08-28 00:53:59 +02003556 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003557 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003558 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003559
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003560 errno = 0;
3561 PySSL_BEGIN_ALLOW_THREADS
3562 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003563 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003564 PySSL_END_ALLOW_THREADS
3565 if (dh == NULL) {
3566 if (errno != 0) {
3567 ERR_clear_error();
3568 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3569 }
3570 else {
3571 _setSSLError(NULL, 0, __FILE__, __LINE__);
3572 }
3573 return NULL;
3574 }
3575 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3576 _setSSLError(NULL, 0, __FILE__, __LINE__);
3577 DH_free(dh);
3578 Py_RETURN_NONE;
3579}
3580
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003581/*[clinic input]
3582_ssl._SSLContext._wrap_socket
3583 sock: object(subclass_of="PySocketModule.Sock_Type")
3584 server_side: int
3585 server_hostname as hostname_obj: object = None
3586
3587[clinic start generated code]*/
3588
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003589static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003590_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3591 int server_side, PyObject *hostname_obj)
3592/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003593{
Antoine Pitroud5323212010-10-22 18:19:07 +00003594 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003595 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003596
Antoine Pitroud5323212010-10-22 18:19:07 +00003597 /* server_hostname is either None (or absent), or to be encoded
3598 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003599 if (hostname_obj != Py_None) {
3600 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003601 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003602 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003603
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003604 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3605 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003606 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003607 if (hostname != NULL)
3608 PyMem_Free(hostname);
3609 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003610}
3611
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003612/*[clinic input]
3613_ssl._SSLContext._wrap_bio
3614 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3615 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3616 server_side: int
3617 server_hostname as hostname_obj: object = None
3618
3619[clinic start generated code]*/
3620
Antoine Pitroub0182c82010-10-12 20:09:02 +00003621static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003622_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3623 PySSLMemoryBIO *outgoing, int server_side,
3624 PyObject *hostname_obj)
3625/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003627 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003628 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003629
3630 /* server_hostname is either None (or absent), or to be encoded
3631 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003632 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003633 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3634 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003635 }
3636
3637 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3638 incoming, outgoing);
3639
3640 PyMem_Free(hostname);
3641 return res;
3642}
3643
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003644/*[clinic input]
3645_ssl._SSLContext.session_stats
3646[clinic start generated code]*/
3647
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003648static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003649_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3650/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003651{
3652 int r;
3653 PyObject *value, *stats = PyDict_New();
3654 if (!stats)
3655 return NULL;
3656
3657#define ADD_STATS(SSL_NAME, KEY_NAME) \
3658 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3659 if (value == NULL) \
3660 goto error; \
3661 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3662 Py_DECREF(value); \
3663 if (r < 0) \
3664 goto error;
3665
3666 ADD_STATS(number, "number");
3667 ADD_STATS(connect, "connect");
3668 ADD_STATS(connect_good, "connect_good");
3669 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3670 ADD_STATS(accept, "accept");
3671 ADD_STATS(accept_good, "accept_good");
3672 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3673 ADD_STATS(accept, "accept");
3674 ADD_STATS(hits, "hits");
3675 ADD_STATS(misses, "misses");
3676 ADD_STATS(timeouts, "timeouts");
3677 ADD_STATS(cache_full, "cache_full");
3678
3679#undef ADD_STATS
3680
3681 return stats;
3682
3683error:
3684 Py_DECREF(stats);
3685 return NULL;
3686}
3687
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003688/*[clinic input]
3689_ssl._SSLContext.set_default_verify_paths
3690[clinic start generated code]*/
3691
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003692static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003693_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3694/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003695{
3696 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3697 _setSSLError(NULL, 0, __FILE__, __LINE__);
3698 return NULL;
3699 }
3700 Py_RETURN_NONE;
3701}
3702
Antoine Pitrou501da612011-12-21 09:27:41 +01003703#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003704/*[clinic input]
3705_ssl._SSLContext.set_ecdh_curve
3706 name: object
3707 /
3708
3709[clinic start generated code]*/
3710
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003711static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003712_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3713/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003714{
3715 PyObject *name_bytes;
3716 int nid;
3717 EC_KEY *key;
3718
3719 if (!PyUnicode_FSConverter(name, &name_bytes))
3720 return NULL;
3721 assert(PyBytes_Check(name_bytes));
3722 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3723 Py_DECREF(name_bytes);
3724 if (nid == 0) {
3725 PyErr_Format(PyExc_ValueError,
3726 "unknown elliptic curve name %R", name);
3727 return NULL;
3728 }
3729 key = EC_KEY_new_by_curve_name(nid);
3730 if (key == NULL) {
3731 _setSSLError(NULL, 0, __FILE__, __LINE__);
3732 return NULL;
3733 }
3734 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3735 EC_KEY_free(key);
3736 Py_RETURN_NONE;
3737}
Antoine Pitrou501da612011-12-21 09:27:41 +01003738#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003739
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003740#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003741static int
3742_servername_callback(SSL *s, int *al, void *args)
3743{
3744 int ret;
3745 PySSLContext *ssl_ctx = (PySSLContext *) args;
3746 PySSLSocket *ssl;
3747 PyObject *servername_o;
3748 PyObject *servername_idna;
3749 PyObject *result;
3750 /* The high-level ssl.SSLSocket object */
3751 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003752 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003753 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003754
3755 if (ssl_ctx->set_hostname == NULL) {
3756 /* remove race condition in this the call back while if removing the
3757 * callback is in progress */
3758 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003759 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003760 }
3761
3762 ssl = SSL_get_app_data(s);
3763 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003764
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003765 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003766 * SSL connection and that has a .context attribute that can be changed to
3767 * identify the requested hostname. Since the official API is the Python
3768 * level API we want to pass the callback a Python level object rather than
3769 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3770 * SSLObject) that will be passed. Otherwise if there's a socket then that
3771 * will be passed. If both do not exist only then the C-level object is
3772 * passed. */
3773 if (ssl->owner)
3774 ssl_socket = PyWeakref_GetObject(ssl->owner);
3775 else if (ssl->Socket)
3776 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3777 else
3778 ssl_socket = (PyObject *) ssl;
3779
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003780 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003781 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003782 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003783
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003784 if (servername == NULL) {
3785 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3786 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003787 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003788 else {
3789 servername_o = PyBytes_FromString(servername);
3790 if (servername_o == NULL) {
3791 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3792 goto error;
3793 }
3794 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3795 if (servername_idna == NULL) {
3796 PyErr_WriteUnraisable(servername_o);
3797 Py_DECREF(servername_o);
3798 goto error;
3799 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003800 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003801 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3802 servername_idna, ssl_ctx, NULL);
3803 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003804 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003805 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003806
3807 if (result == NULL) {
3808 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3809 *al = SSL_AD_HANDSHAKE_FAILURE;
3810 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3811 }
3812 else {
3813 if (result != Py_None) {
3814 *al = (int) PyLong_AsLong(result);
3815 if (PyErr_Occurred()) {
3816 PyErr_WriteUnraisable(result);
3817 *al = SSL_AD_INTERNAL_ERROR;
3818 }
3819 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3820 }
3821 else {
3822 ret = SSL_TLSEXT_ERR_OK;
3823 }
3824 Py_DECREF(result);
3825 }
3826
3827 PyGILState_Release(gstate);
3828 return ret;
3829
3830error:
3831 Py_DECREF(ssl_socket);
3832 *al = SSL_AD_INTERNAL_ERROR;
3833 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3834 PyGILState_Release(gstate);
3835 return ret;
3836}
Antoine Pitroua5963382013-03-30 16:39:00 +01003837#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003838
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003839/*[clinic input]
3840_ssl._SSLContext.set_servername_callback
3841 method as cb: object
3842 /
3843
3844Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3845
3846If the argument is None then the callback is disabled. The method is called
3847with the SSLSocket, the server name as a string, and the SSLContext object.
3848See RFC 6066 for details of the SNI extension.
3849[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003850
3851static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003852_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3853/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003854{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003855#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003856 Py_CLEAR(self->set_hostname);
3857 if (cb == Py_None) {
3858 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3859 }
3860 else {
3861 if (!PyCallable_Check(cb)) {
3862 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3863 PyErr_SetString(PyExc_TypeError,
3864 "not a callable object");
3865 return NULL;
3866 }
3867 Py_INCREF(cb);
3868 self->set_hostname = cb;
3869 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3870 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3871 }
3872 Py_RETURN_NONE;
3873#else
3874 PyErr_SetString(PyExc_NotImplementedError,
3875 "The TLS extension servername callback, "
3876 "SSL_CTX_set_tlsext_servername_callback, "
3877 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003878 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003879#endif
3880}
3881
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003882/*[clinic input]
3883_ssl._SSLContext.cert_store_stats
3884
3885Returns quantities of loaded X.509 certificates.
3886
3887X.509 certificates with a CA extension and certificate revocation lists
3888inside the context's cert store.
3889
3890NOTE: Certificates in a capath directory aren't loaded unless they have
3891been used at least once.
3892[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003893
3894static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003895_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3896/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003897{
3898 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003899 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003900 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003901 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003902
3903 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003904 objs = X509_STORE_get0_objects(store);
3905 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3906 obj = sk_X509_OBJECT_value(objs, i);
3907 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003908 case X509_LU_X509:
3909 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003910 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003911 ca++;
3912 }
3913 break;
3914 case X509_LU_CRL:
3915 crl++;
3916 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003917 default:
3918 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3919 * As far as I can tell they are internal states and never
3920 * stored in a cert store */
3921 break;
3922 }
3923 }
3924 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3925 "x509_ca", ca);
3926}
3927
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003928/*[clinic input]
3929_ssl._SSLContext.get_ca_certs
3930 binary_form: bool = False
3931
3932Returns a list of dicts with information of loaded CA certs.
3933
3934If the optional argument is True, returns a DER-encoded copy of the CA
3935certificate.
3936
3937NOTE: Certificates in a capath directory aren't loaded unless they have
3938been used at least once.
3939[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003940
3941static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003942_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3943/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003944{
3945 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003946 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003947 PyObject *ci = NULL, *rlist = NULL;
3948 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003949
3950 if ((rlist = PyList_New(0)) == NULL) {
3951 return NULL;
3952 }
3953
3954 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003955 objs = X509_STORE_get0_objects(store);
3956 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003957 X509_OBJECT *obj;
3958 X509 *cert;
3959
Christian Heimes598894f2016-09-05 23:19:05 +02003960 obj = sk_X509_OBJECT_value(objs, i);
3961 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003962 /* not a x509 cert */
3963 continue;
3964 }
3965 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003966 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003967 if (!X509_check_ca(cert)) {
3968 continue;
3969 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003970 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003971 ci = _certificate_to_der(cert);
3972 } else {
3973 ci = _decode_certificate(cert);
3974 }
3975 if (ci == NULL) {
3976 goto error;
3977 }
3978 if (PyList_Append(rlist, ci) == -1) {
3979 goto error;
3980 }
3981 Py_CLEAR(ci);
3982 }
3983 return rlist;
3984
3985 error:
3986 Py_XDECREF(ci);
3987 Py_XDECREF(rlist);
3988 return NULL;
3989}
3990
3991
Antoine Pitrou152efa22010-05-16 18:19:27 +00003992static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003993 {"check_hostname", (getter) get_check_hostname,
3994 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003995 {"options", (getter) get_options,
3996 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003997 {"verify_flags", (getter) get_verify_flags,
3998 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003999 {"verify_mode", (getter) get_verify_mode,
4000 (setter) set_verify_mode, NULL},
4001 {NULL}, /* sentinel */
4002};
4003
4004static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004005 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4006 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4007 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4008 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4009 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4010 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4011 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4012 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4013 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4014 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4015 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4016 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4017 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4018 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004019 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004020 {NULL, NULL} /* sentinel */
4021};
4022
4023static PyTypeObject PySSLContext_Type = {
4024 PyVarObject_HEAD_INIT(NULL, 0)
4025 "_ssl._SSLContext", /*tp_name*/
4026 sizeof(PySSLContext), /*tp_basicsize*/
4027 0, /*tp_itemsize*/
4028 (destructor)context_dealloc, /*tp_dealloc*/
4029 0, /*tp_print*/
4030 0, /*tp_getattr*/
4031 0, /*tp_setattr*/
4032 0, /*tp_reserved*/
4033 0, /*tp_repr*/
4034 0, /*tp_as_number*/
4035 0, /*tp_as_sequence*/
4036 0, /*tp_as_mapping*/
4037 0, /*tp_hash*/
4038 0, /*tp_call*/
4039 0, /*tp_str*/
4040 0, /*tp_getattro*/
4041 0, /*tp_setattro*/
4042 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004043 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004044 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004045 (traverseproc) context_traverse, /*tp_traverse*/
4046 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004047 0, /*tp_richcompare*/
4048 0, /*tp_weaklistoffset*/
4049 0, /*tp_iter*/
4050 0, /*tp_iternext*/
4051 context_methods, /*tp_methods*/
4052 0, /*tp_members*/
4053 context_getsetlist, /*tp_getset*/
4054 0, /*tp_base*/
4055 0, /*tp_dict*/
4056 0, /*tp_descr_get*/
4057 0, /*tp_descr_set*/
4058 0, /*tp_dictoffset*/
4059 0, /*tp_init*/
4060 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004061 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004062};
4063
4064
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004065/*
4066 * MemoryBIO objects
4067 */
4068
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004069/*[clinic input]
4070@classmethod
4071_ssl.MemoryBIO.__new__
4072
4073[clinic start generated code]*/
4074
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004075static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004076_ssl_MemoryBIO_impl(PyTypeObject *type)
4077/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004078{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004079 BIO *bio;
4080 PySSLMemoryBIO *self;
4081
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004082 bio = BIO_new(BIO_s_mem());
4083 if (bio == NULL) {
4084 PyErr_SetString(PySSLErrorObject,
4085 "failed to allocate BIO");
4086 return NULL;
4087 }
4088 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4089 * just that no data is currently available. The SSL routines should retry
4090 * the read, which we can achieve by calling BIO_set_retry_read(). */
4091 BIO_set_retry_read(bio);
4092 BIO_set_mem_eof_return(bio, -1);
4093
4094 assert(type != NULL && type->tp_alloc != NULL);
4095 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4096 if (self == NULL) {
4097 BIO_free(bio);
4098 return NULL;
4099 }
4100 self->bio = bio;
4101 self->eof_written = 0;
4102
4103 return (PyObject *) self;
4104}
4105
4106static void
4107memory_bio_dealloc(PySSLMemoryBIO *self)
4108{
4109 BIO_free(self->bio);
4110 Py_TYPE(self)->tp_free(self);
4111}
4112
4113static PyObject *
4114memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4115{
Segev Finer5cff6372017-07-27 01:19:17 +03004116 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004117}
4118
4119PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4120"The number of bytes pending in the memory BIO.");
4121
4122static PyObject *
4123memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4124{
4125 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4126 && self->eof_written);
4127}
4128
4129PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4130"Whether the memory BIO is at EOF.");
4131
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004132/*[clinic input]
4133_ssl.MemoryBIO.read
4134 size as len: int = -1
4135 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004136
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004137Read up to size bytes from the memory BIO.
4138
4139If size is not specified, read the entire buffer.
4140If the return value is an empty bytes instance, this means either
4141EOF or that no data is available. Use the "eof" property to
4142distinguish between the two.
4143[clinic start generated code]*/
4144
4145static PyObject *
4146_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4147/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4148{
4149 int avail, nbytes;
4150 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004151
Segev Finer5cff6372017-07-27 01:19:17 +03004152 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004153 if ((len < 0) || (len > avail))
4154 len = avail;
4155
4156 result = PyBytes_FromStringAndSize(NULL, len);
4157 if ((result == NULL) || (len == 0))
4158 return result;
4159
4160 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4161 /* There should never be any short reads but check anyway. */
4162 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4163 Py_DECREF(result);
4164 return NULL;
4165 }
4166
4167 return result;
4168}
4169
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004170/*[clinic input]
4171_ssl.MemoryBIO.write
4172 b: Py_buffer
4173 /
4174
4175Writes the bytes b into the memory BIO.
4176
4177Returns the number of bytes written.
4178[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004179
4180static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4182/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184 int nbytes;
4185
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004186 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 PyErr_Format(PyExc_OverflowError,
4188 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004189 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004190 }
4191
4192 if (self->eof_written) {
4193 PyErr_SetString(PySSLErrorObject,
4194 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004195 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004196 }
4197
Segev Finer5cff6372017-07-27 01:19:17 +03004198 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004199 if (nbytes < 0) {
4200 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004201 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004202 }
4203
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004204 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004205}
4206
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004207/*[clinic input]
4208_ssl.MemoryBIO.write_eof
4209
4210Write an EOF marker to the memory BIO.
4211
4212When all data has been read, the "eof" property will be True.
4213[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004214
4215static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004216_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4217/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004218{
4219 self->eof_written = 1;
4220 /* After an EOF is written, a zero return from read() should be a real EOF
4221 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4222 BIO_clear_retry_flags(self->bio);
4223 BIO_set_mem_eof_return(self->bio, 0);
4224
4225 Py_RETURN_NONE;
4226}
4227
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004228static PyGetSetDef memory_bio_getsetlist[] = {
4229 {"pending", (getter) memory_bio_get_pending, NULL,
4230 PySSL_memory_bio_pending_doc},
4231 {"eof", (getter) memory_bio_get_eof, NULL,
4232 PySSL_memory_bio_eof_doc},
4233 {NULL}, /* sentinel */
4234};
4235
4236static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004237 _SSL_MEMORYBIO_READ_METHODDEF
4238 _SSL_MEMORYBIO_WRITE_METHODDEF
4239 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004240 {NULL, NULL} /* sentinel */
4241};
4242
4243static PyTypeObject PySSLMemoryBIO_Type = {
4244 PyVarObject_HEAD_INIT(NULL, 0)
4245 "_ssl.MemoryBIO", /*tp_name*/
4246 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4247 0, /*tp_itemsize*/
4248 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4249 0, /*tp_print*/
4250 0, /*tp_getattr*/
4251 0, /*tp_setattr*/
4252 0, /*tp_reserved*/
4253 0, /*tp_repr*/
4254 0, /*tp_as_number*/
4255 0, /*tp_as_sequence*/
4256 0, /*tp_as_mapping*/
4257 0, /*tp_hash*/
4258 0, /*tp_call*/
4259 0, /*tp_str*/
4260 0, /*tp_getattro*/
4261 0, /*tp_setattro*/
4262 0, /*tp_as_buffer*/
4263 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4264 0, /*tp_doc*/
4265 0, /*tp_traverse*/
4266 0, /*tp_clear*/
4267 0, /*tp_richcompare*/
4268 0, /*tp_weaklistoffset*/
4269 0, /*tp_iter*/
4270 0, /*tp_iternext*/
4271 memory_bio_methods, /*tp_methods*/
4272 0, /*tp_members*/
4273 memory_bio_getsetlist, /*tp_getset*/
4274 0, /*tp_base*/
4275 0, /*tp_dict*/
4276 0, /*tp_descr_get*/
4277 0, /*tp_descr_set*/
4278 0, /*tp_dictoffset*/
4279 0, /*tp_init*/
4280 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004281 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004282};
4283
Antoine Pitrou152efa22010-05-16 18:19:27 +00004284
Christian Heimes99a65702016-09-10 23:44:53 +02004285/*
4286 * SSL Session object
4287 */
4288
4289static void
4290PySSLSession_dealloc(PySSLSession *self)
4291{
INADA Naokia6296d32017-08-24 14:55:17 +09004292 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004293 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004294 Py_XDECREF(self->ctx);
4295 if (self->session != NULL) {
4296 SSL_SESSION_free(self->session);
4297 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004298 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004299}
4300
4301static PyObject *
4302PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4303{
4304 int result;
4305
4306 if (left == NULL || right == NULL) {
4307 PyErr_BadInternalCall();
4308 return NULL;
4309 }
4310
4311 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4312 Py_RETURN_NOTIMPLEMENTED;
4313 }
4314
4315 if (left == right) {
4316 result = 0;
4317 } else {
4318 const unsigned char *left_id, *right_id;
4319 unsigned int left_len, right_len;
4320 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4321 &left_len);
4322 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4323 &right_len);
4324 if (left_len == right_len) {
4325 result = memcmp(left_id, right_id, left_len);
4326 } else {
4327 result = 1;
4328 }
4329 }
4330
4331 switch (op) {
4332 case Py_EQ:
4333 if (result == 0) {
4334 Py_RETURN_TRUE;
4335 } else {
4336 Py_RETURN_FALSE;
4337 }
4338 break;
4339 case Py_NE:
4340 if (result != 0) {
4341 Py_RETURN_TRUE;
4342 } else {
4343 Py_RETURN_FALSE;
4344 }
4345 break;
4346 case Py_LT:
4347 case Py_LE:
4348 case Py_GT:
4349 case Py_GE:
4350 Py_RETURN_NOTIMPLEMENTED;
4351 break;
4352 default:
4353 PyErr_BadArgument();
4354 return NULL;
4355 }
4356}
4357
4358static int
4359PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4360{
4361 Py_VISIT(self->ctx);
4362 return 0;
4363}
4364
4365static int
4366PySSLSession_clear(PySSLSession *self)
4367{
4368 Py_CLEAR(self->ctx);
4369 return 0;
4370}
4371
4372
4373static PyObject *
4374PySSLSession_get_time(PySSLSession *self, void *closure) {
4375 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4376}
4377
4378PyDoc_STRVAR(PySSLSession_get_time_doc,
4379"Session creation time (seconds since epoch).");
4380
4381
4382static PyObject *
4383PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4384 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4385}
4386
4387PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4388"Session timeout (delta in seconds).");
4389
4390
4391static PyObject *
4392PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4393 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4394 return PyLong_FromUnsignedLong(hint);
4395}
4396
4397PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4398"Ticket life time hint.");
4399
4400
4401static PyObject *
4402PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4403 const unsigned char *id;
4404 unsigned int len;
4405 id = SSL_SESSION_get_id(self->session, &len);
4406 return PyBytes_FromStringAndSize((const char *)id, len);
4407}
4408
4409PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4410"Session id");
4411
4412
4413static PyObject *
4414PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4415 if (SSL_SESSION_has_ticket(self->session)) {
4416 Py_RETURN_TRUE;
4417 } else {
4418 Py_RETURN_FALSE;
4419 }
4420}
4421
4422PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4423"Does the session contain a ticket?");
4424
4425
4426static PyGetSetDef PySSLSession_getsetlist[] = {
4427 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4428 PySSLSession_get_has_ticket_doc},
4429 {"id", (getter) PySSLSession_get_session_id, NULL,
4430 PySSLSession_get_session_id_doc},
4431 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4432 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4433 {"time", (getter) PySSLSession_get_time, NULL,
4434 PySSLSession_get_time_doc},
4435 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4436 PySSLSession_get_timeout_doc},
4437 {NULL}, /* sentinel */
4438};
4439
4440static PyTypeObject PySSLSession_Type = {
4441 PyVarObject_HEAD_INIT(NULL, 0)
4442 "_ssl.Session", /*tp_name*/
4443 sizeof(PySSLSession), /*tp_basicsize*/
4444 0, /*tp_itemsize*/
4445 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4446 0, /*tp_print*/
4447 0, /*tp_getattr*/
4448 0, /*tp_setattr*/
4449 0, /*tp_reserved*/
4450 0, /*tp_repr*/
4451 0, /*tp_as_number*/
4452 0, /*tp_as_sequence*/
4453 0, /*tp_as_mapping*/
4454 0, /*tp_hash*/
4455 0, /*tp_call*/
4456 0, /*tp_str*/
4457 0, /*tp_getattro*/
4458 0, /*tp_setattro*/
4459 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004460 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004461 0, /*tp_doc*/
4462 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4463 (inquiry)PySSLSession_clear, /*tp_clear*/
4464 PySSLSession_richcompare, /*tp_richcompare*/
4465 0, /*tp_weaklistoffset*/
4466 0, /*tp_iter*/
4467 0, /*tp_iternext*/
4468 0, /*tp_methods*/
4469 0, /*tp_members*/
4470 PySSLSession_getsetlist, /*tp_getset*/
4471};
4472
4473
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004474/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004475/*[clinic input]
4476_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004477 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004478 entropy: double
4479 /
4480
4481Mix string into the OpenSSL PRNG state.
4482
4483entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304484string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004485[clinic start generated code]*/
4486
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004487static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004488_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004489/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004490{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004491 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004492 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004493
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004494 buf = (const char *)view->buf;
4495 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004496 do {
4497 written = Py_MIN(len, INT_MAX);
4498 RAND_add(buf, (int)written, entropy);
4499 buf += written;
4500 len -= written;
4501 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004502 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004503}
4504
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004505static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004506PySSL_RAND(int len, int pseudo)
4507{
4508 int ok;
4509 PyObject *bytes;
4510 unsigned long err;
4511 const char *errstr;
4512 PyObject *v;
4513
Victor Stinner1e81a392013-12-19 16:47:04 +01004514 if (len < 0) {
4515 PyErr_SetString(PyExc_ValueError, "num must be positive");
4516 return NULL;
4517 }
4518
Victor Stinner99c8b162011-05-24 12:05:19 +02004519 bytes = PyBytes_FromStringAndSize(NULL, len);
4520 if (bytes == NULL)
4521 return NULL;
4522 if (pseudo) {
4523 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4524 if (ok == 0 || ok == 1)
4525 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4526 }
4527 else {
4528 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4529 if (ok == 1)
4530 return bytes;
4531 }
4532 Py_DECREF(bytes);
4533
4534 err = ERR_get_error();
4535 errstr = ERR_reason_error_string(err);
4536 v = Py_BuildValue("(ks)", err, errstr);
4537 if (v != NULL) {
4538 PyErr_SetObject(PySSLErrorObject, v);
4539 Py_DECREF(v);
4540 }
4541 return NULL;
4542}
4543
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004544/*[clinic input]
4545_ssl.RAND_bytes
4546 n: int
4547 /
4548
4549Generate n cryptographically strong pseudo-random bytes.
4550[clinic start generated code]*/
4551
Victor Stinner99c8b162011-05-24 12:05:19 +02004552static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004553_ssl_RAND_bytes_impl(PyObject *module, int n)
4554/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004555{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004556 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004557}
4558
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004559/*[clinic input]
4560_ssl.RAND_pseudo_bytes
4561 n: int
4562 /
4563
4564Generate n pseudo-random bytes.
4565
4566Return a pair (bytes, is_cryptographic). is_cryptographic is True
4567if the bytes generated are cryptographically strong.
4568[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004569
4570static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004571_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4572/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004573{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004574 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004575}
4576
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004577/*[clinic input]
4578_ssl.RAND_status
4579
4580Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4581
4582It is necessary to seed the PRNG with RAND_add() on some platforms before
4583using the ssl() function.
4584[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004585
4586static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004587_ssl_RAND_status_impl(PyObject *module)
4588/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004589{
Christian Heimes217cfd12007-12-02 14:31:20 +00004590 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004591}
4592
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004593#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004594/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004595/*[clinic input]
4596_ssl.RAND_egd
4597 path: object(converter="PyUnicode_FSConverter")
4598 /
4599
4600Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4601
4602Returns number of bytes read. Raises SSLError if connection to EGD
4603fails or if it does not provide enough data to seed PRNG.
4604[clinic start generated code]*/
4605
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004606static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004607_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4608/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004609{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004610 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004611 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004612 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004613 PyErr_SetString(PySSLErrorObject,
4614 "EGD connection failed or EGD did not return "
4615 "enough data to seed the PRNG");
4616 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004617 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004618 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004619}
Christian Heimesa5d07652016-09-24 10:48:05 +02004620/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004621#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004622
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004623
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004624
4625/*[clinic input]
4626_ssl.get_default_verify_paths
4627
4628Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4629
4630The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4631[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004632
4633static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004634_ssl_get_default_verify_paths_impl(PyObject *module)
4635/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004636{
4637 PyObject *ofile_env = NULL;
4638 PyObject *ofile = NULL;
4639 PyObject *odir_env = NULL;
4640 PyObject *odir = NULL;
4641
Benjamin Petersond113c962015-07-18 10:59:13 -07004642#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004643 const char *tmp = (info); \
4644 target = NULL; \
4645 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4646 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4647 target = PyBytes_FromString(tmp); } \
4648 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004649 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004650
Benjamin Petersond113c962015-07-18 10:59:13 -07004651 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4652 CONVERT(X509_get_default_cert_file(), ofile);
4653 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4654 CONVERT(X509_get_default_cert_dir(), odir);
4655#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004656
Christian Heimes200bb1b2013-06-14 15:14:29 +02004657 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004658
4659 error:
4660 Py_XDECREF(ofile_env);
4661 Py_XDECREF(ofile);
4662 Py_XDECREF(odir_env);
4663 Py_XDECREF(odir);
4664 return NULL;
4665}
4666
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004667static PyObject*
4668asn1obj2py(ASN1_OBJECT *obj)
4669{
4670 int nid;
4671 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004672
4673 nid = OBJ_obj2nid(obj);
4674 if (nid == NID_undef) {
4675 PyErr_Format(PyExc_ValueError, "Unknown object");
4676 return NULL;
4677 }
4678 sn = OBJ_nid2sn(nid);
4679 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004680 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004681}
4682
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004683/*[clinic input]
4684_ssl.txt2obj
4685 txt: str
4686 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004687
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004688Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4689
4690By default objects are looked up by OID. With name=True short and
4691long name are also matched.
4692[clinic start generated code]*/
4693
4694static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004695_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4696/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004697{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004698 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004699 ASN1_OBJECT *obj;
4700
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004701 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4702 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004703 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004704 return NULL;
4705 }
4706 result = asn1obj2py(obj);
4707 ASN1_OBJECT_free(obj);
4708 return result;
4709}
4710
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004711/*[clinic input]
4712_ssl.nid2obj
4713 nid: int
4714 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004715
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004716Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4717[clinic start generated code]*/
4718
4719static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004720_ssl_nid2obj_impl(PyObject *module, int nid)
4721/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004722{
4723 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004724 ASN1_OBJECT *obj;
4725
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004726 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004727 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004728 return NULL;
4729 }
4730 obj = OBJ_nid2obj(nid);
4731 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004732 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004733 return NULL;
4734 }
4735 result = asn1obj2py(obj);
4736 ASN1_OBJECT_free(obj);
4737 return result;
4738}
4739
Christian Heimes46bebee2013-06-09 19:03:31 +02004740#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004741
4742static PyObject*
4743certEncodingType(DWORD encodingType)
4744{
4745 static PyObject *x509_asn = NULL;
4746 static PyObject *pkcs_7_asn = NULL;
4747
4748 if (x509_asn == NULL) {
4749 x509_asn = PyUnicode_InternFromString("x509_asn");
4750 if (x509_asn == NULL)
4751 return NULL;
4752 }
4753 if (pkcs_7_asn == NULL) {
4754 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4755 if (pkcs_7_asn == NULL)
4756 return NULL;
4757 }
4758 switch(encodingType) {
4759 case X509_ASN_ENCODING:
4760 Py_INCREF(x509_asn);
4761 return x509_asn;
4762 case PKCS_7_ASN_ENCODING:
4763 Py_INCREF(pkcs_7_asn);
4764 return pkcs_7_asn;
4765 default:
4766 return PyLong_FromLong(encodingType);
4767 }
4768}
4769
4770static PyObject*
4771parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4772{
4773 CERT_ENHKEY_USAGE *usage;
4774 DWORD size, error, i;
4775 PyObject *retval;
4776
4777 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4778 error = GetLastError();
4779 if (error == CRYPT_E_NOT_FOUND) {
4780 Py_RETURN_TRUE;
4781 }
4782 return PyErr_SetFromWindowsErr(error);
4783 }
4784
4785 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4786 if (usage == NULL) {
4787 return PyErr_NoMemory();
4788 }
4789
4790 /* Now get the actual enhanced usage property */
4791 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4792 PyMem_Free(usage);
4793 error = GetLastError();
4794 if (error == CRYPT_E_NOT_FOUND) {
4795 Py_RETURN_TRUE;
4796 }
4797 return PyErr_SetFromWindowsErr(error);
4798 }
4799 retval = PySet_New(NULL);
4800 if (retval == NULL) {
4801 goto error;
4802 }
4803 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4804 if (usage->rgpszUsageIdentifier[i]) {
4805 PyObject *oid;
4806 int err;
4807 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4808 if (oid == NULL) {
4809 Py_CLEAR(retval);
4810 goto error;
4811 }
4812 err = PySet_Add(retval, oid);
4813 Py_DECREF(oid);
4814 if (err == -1) {
4815 Py_CLEAR(retval);
4816 goto error;
4817 }
4818 }
4819 }
4820 error:
4821 PyMem_Free(usage);
4822 return retval;
4823}
4824
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004825/*[clinic input]
4826_ssl.enum_certificates
4827 store_name: str
4828
4829Retrieve certificates from Windows' cert store.
4830
4831store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4832more cert storages, too. The function returns a list of (bytes,
4833encoding_type, trust) tuples. The encoding_type flag can be interpreted
4834with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4835a set of OIDs or the boolean True.
4836[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004837
Christian Heimes46bebee2013-06-09 19:03:31 +02004838static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004839_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4840/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004841{
Christian Heimes46bebee2013-06-09 19:03:31 +02004842 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004843 PCCERT_CONTEXT pCertCtx = NULL;
4844 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004845 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004846
Christian Heimes44109d72013-11-22 01:51:30 +01004847 result = PyList_New(0);
4848 if (result == NULL) {
4849 return NULL;
4850 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004851 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4852 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4853 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004854 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004855 Py_DECREF(result);
4856 return PyErr_SetFromWindowsErr(GetLastError());
4857 }
4858
Christian Heimes44109d72013-11-22 01:51:30 +01004859 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4860 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4861 pCertCtx->cbCertEncoded);
4862 if (!cert) {
4863 Py_CLEAR(result);
4864 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004865 }
Christian Heimes44109d72013-11-22 01:51:30 +01004866 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4867 Py_CLEAR(result);
4868 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004869 }
Christian Heimes44109d72013-11-22 01:51:30 +01004870 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4871 if (keyusage == Py_True) {
4872 Py_DECREF(keyusage);
4873 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004874 }
Christian Heimes44109d72013-11-22 01:51:30 +01004875 if (keyusage == NULL) {
4876 Py_CLEAR(result);
4877 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004878 }
Christian Heimes44109d72013-11-22 01:51:30 +01004879 if ((tup = PyTuple_New(3)) == NULL) {
4880 Py_CLEAR(result);
4881 break;
4882 }
4883 PyTuple_SET_ITEM(tup, 0, cert);
4884 cert = NULL;
4885 PyTuple_SET_ITEM(tup, 1, enc);
4886 enc = NULL;
4887 PyTuple_SET_ITEM(tup, 2, keyusage);
4888 keyusage = NULL;
4889 if (PyList_Append(result, tup) < 0) {
4890 Py_CLEAR(result);
4891 break;
4892 }
4893 Py_CLEAR(tup);
4894 }
4895 if (pCertCtx) {
4896 /* loop ended with an error, need to clean up context manually */
4897 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004898 }
4899
4900 /* In error cases cert, enc and tup may not be NULL */
4901 Py_XDECREF(cert);
4902 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004903 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004904 Py_XDECREF(tup);
4905
4906 if (!CertCloseStore(hStore, 0)) {
4907 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004908 Py_XDECREF(result);
4909 return PyErr_SetFromWindowsErr(GetLastError());
4910 }
4911 return result;
4912}
4913
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004914/*[clinic input]
4915_ssl.enum_crls
4916 store_name: str
4917
4918Retrieve CRLs from Windows' cert store.
4919
4920store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4921more cert storages, too. The function returns a list of (bytes,
4922encoding_type) tuples. The encoding_type flag can be interpreted with
4923X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4924[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004925
4926static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004927_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4928/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004929{
Christian Heimes44109d72013-11-22 01:51:30 +01004930 HCERTSTORE hStore = NULL;
4931 PCCRL_CONTEXT pCrlCtx = NULL;
4932 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4933 PyObject *result = NULL;
4934
Christian Heimes44109d72013-11-22 01:51:30 +01004935 result = PyList_New(0);
4936 if (result == NULL) {
4937 return NULL;
4938 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004939 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4940 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4941 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004942 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004943 Py_DECREF(result);
4944 return PyErr_SetFromWindowsErr(GetLastError());
4945 }
Christian Heimes44109d72013-11-22 01:51:30 +01004946
4947 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4948 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4949 pCrlCtx->cbCrlEncoded);
4950 if (!crl) {
4951 Py_CLEAR(result);
4952 break;
4953 }
4954 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4955 Py_CLEAR(result);
4956 break;
4957 }
4958 if ((tup = PyTuple_New(2)) == NULL) {
4959 Py_CLEAR(result);
4960 break;
4961 }
4962 PyTuple_SET_ITEM(tup, 0, crl);
4963 crl = NULL;
4964 PyTuple_SET_ITEM(tup, 1, enc);
4965 enc = NULL;
4966
4967 if (PyList_Append(result, tup) < 0) {
4968 Py_CLEAR(result);
4969 break;
4970 }
4971 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004972 }
Christian Heimes44109d72013-11-22 01:51:30 +01004973 if (pCrlCtx) {
4974 /* loop ended with an error, need to clean up context manually */
4975 CertFreeCRLContext(pCrlCtx);
4976 }
4977
4978 /* In error cases cert, enc and tup may not be NULL */
4979 Py_XDECREF(crl);
4980 Py_XDECREF(enc);
4981 Py_XDECREF(tup);
4982
4983 if (!CertCloseStore(hStore, 0)) {
4984 /* This error case might shadow another exception.*/
4985 Py_XDECREF(result);
4986 return PyErr_SetFromWindowsErr(GetLastError());
4987 }
4988 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004989}
Christian Heimes44109d72013-11-22 01:51:30 +01004990
4991#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004992
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004993/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004994static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004995 _SSL__TEST_DECODE_CERT_METHODDEF
4996 _SSL_RAND_ADD_METHODDEF
4997 _SSL_RAND_BYTES_METHODDEF
4998 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4999 _SSL_RAND_EGD_METHODDEF
5000 _SSL_RAND_STATUS_METHODDEF
5001 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5002 _SSL_ENUM_CERTIFICATES_METHODDEF
5003 _SSL_ENUM_CRLS_METHODDEF
5004 _SSL_TXT2OBJ_METHODDEF
5005 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005006 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005007};
5008
5009
Christian Heimes598894f2016-09-05 23:19:05 +02005010#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005011
5012/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005013 * of the Python C thread library
5014 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5015 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005016
5017static PyThread_type_lock *_ssl_locks = NULL;
5018
Christian Heimes4d98ca92013-08-19 17:36:29 +02005019#if OPENSSL_VERSION_NUMBER >= 0x10000000
5020/* use new CRYPTO_THREADID API. */
5021static void
5022_ssl_threadid_callback(CRYPTO_THREADID *id)
5023{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005024 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005025}
5026#else
5027/* deprecated CRYPTO_set_id_callback() API. */
5028static unsigned long
5029_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005030 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005031}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005032#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005033
Bill Janssen6e027db2007-11-15 22:23:56 +00005034static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005035 (int mode, int n, const char *file, int line) {
5036 /* this function is needed to perform locking on shared data
5037 structures. (Note that OpenSSL uses a number of global data
5038 structures that will be implicitly shared whenever multiple
5039 threads use OpenSSL.) Multi-threaded applications will
5040 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005041
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005042 locking_function() must be able to handle up to
5043 CRYPTO_num_locks() different mutex locks. It sets the n-th
5044 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005045
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005046 file and line are the file number of the function setting the
5047 lock. They can be useful for debugging.
5048 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005049
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005050 if ((_ssl_locks == NULL) ||
5051 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5052 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005053
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005054 if (mode & CRYPTO_LOCK) {
5055 PyThread_acquire_lock(_ssl_locks[n], 1);
5056 } else {
5057 PyThread_release_lock(_ssl_locks[n]);
5058 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005059}
5060
5061static int _setup_ssl_threads(void) {
5062
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005063 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005064
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005065 if (_ssl_locks == NULL) {
5066 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005067 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5068 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005069 if (_ssl_locks == NULL) {
5070 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005071 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005072 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005073 for (i = 0; i < _ssl_locks_count; i++) {
5074 _ssl_locks[i] = PyThread_allocate_lock();
5075 if (_ssl_locks[i] == NULL) {
5076 unsigned int j;
5077 for (j = 0; j < i; j++) {
5078 PyThread_free_lock(_ssl_locks[j]);
5079 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005080 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005081 return 0;
5082 }
5083 }
5084 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005085#if OPENSSL_VERSION_NUMBER >= 0x10000000
5086 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5087#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005088 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005089#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005090 }
5091 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005092}
5093
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005094#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005095
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005096PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005097"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005098for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005099
Martin v. Löwis1a214512008-06-11 05:26:20 +00005100
5101static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005102 PyModuleDef_HEAD_INIT,
5103 "_ssl",
5104 module_doc,
5105 -1,
5106 PySSL_methods,
5107 NULL,
5108 NULL,
5109 NULL,
5110 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005111};
5112
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005113
5114static void
5115parse_openssl_version(unsigned long libver,
5116 unsigned int *major, unsigned int *minor,
5117 unsigned int *fix, unsigned int *patch,
5118 unsigned int *status)
5119{
5120 *status = libver & 0xF;
5121 libver >>= 4;
5122 *patch = libver & 0xFF;
5123 libver >>= 8;
5124 *fix = libver & 0xFF;
5125 libver >>= 8;
5126 *minor = libver & 0xFF;
5127 libver >>= 8;
5128 *major = libver & 0xFF;
5129}
5130
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005131PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005132PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005133{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005134 PyObject *m, *d, *r;
5135 unsigned long libver;
5136 unsigned int major, minor, fix, patch, status;
5137 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005138 struct py_ssl_error_code *errcode;
5139 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005140
Antoine Pitrou152efa22010-05-16 18:19:27 +00005141 if (PyType_Ready(&PySSLContext_Type) < 0)
5142 return NULL;
5143 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005144 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005145 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5146 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005147 if (PyType_Ready(&PySSLSession_Type) < 0)
5148 return NULL;
5149
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005151 m = PyModule_Create(&_sslmodule);
5152 if (m == NULL)
5153 return NULL;
5154 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005155
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005156 /* Load _socket module and its C API */
5157 socket_api = PySocketModule_ImportModuleAndAPI();
5158 if (!socket_api)
5159 return NULL;
5160 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005161
Christian Heimesc941e622017-09-05 15:47:11 +02005162#ifndef OPENSSL_VERSION_1_1
5163 /* Load all algorithms and initialize cpuid */
5164 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005165 /* Init OpenSSL */
5166 SSL_load_error_strings();
5167 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005168#endif
5169
Christian Heimes598894f2016-09-05 23:19:05 +02005170#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005171 /* note that this will start threading if not already started */
5172 if (!_setup_ssl_threads()) {
5173 return NULL;
5174 }
Christian Heimes598894f2016-09-05 23:19:05 +02005175#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5176 /* OpenSSL 1.1.0 builtin thread support is enabled */
5177 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005178#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005179
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005180 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005181 sslerror_type_slots[0].pfunc = PyExc_OSError;
5182 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005183 if (PySSLErrorObject == NULL)
5184 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005185
Antoine Pitrou41032a62011-10-27 23:56:55 +02005186 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5187 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5188 PySSLErrorObject, NULL);
5189 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5190 "ssl.SSLWantReadError", SSLWantReadError_doc,
5191 PySSLErrorObject, NULL);
5192 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5193 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5194 PySSLErrorObject, NULL);
5195 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5196 "ssl.SSLSyscallError", SSLSyscallError_doc,
5197 PySSLErrorObject, NULL);
5198 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5199 "ssl.SSLEOFError", SSLEOFError_doc,
5200 PySSLErrorObject, NULL);
5201 if (PySSLZeroReturnErrorObject == NULL
5202 || PySSLWantReadErrorObject == NULL
5203 || PySSLWantWriteErrorObject == NULL
5204 || PySSLSyscallErrorObject == NULL
5205 || PySSLEOFErrorObject == NULL)
5206 return NULL;
5207 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5208 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5209 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5210 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5211 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5212 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005213 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005214 if (PyDict_SetItemString(d, "_SSLContext",
5215 (PyObject *)&PySSLContext_Type) != 0)
5216 return NULL;
5217 if (PyDict_SetItemString(d, "_SSLSocket",
5218 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005219 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005220 if (PyDict_SetItemString(d, "MemoryBIO",
5221 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5222 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005223 if (PyDict_SetItemString(d, "SSLSession",
5224 (PyObject *)&PySSLSession_Type) != 0)
5225 return NULL;
5226
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005227 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5228 PY_SSL_ERROR_ZERO_RETURN);
5229 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5230 PY_SSL_ERROR_WANT_READ);
5231 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5232 PY_SSL_ERROR_WANT_WRITE);
5233 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5234 PY_SSL_ERROR_WANT_X509_LOOKUP);
5235 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5236 PY_SSL_ERROR_SYSCALL);
5237 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5238 PY_SSL_ERROR_SSL);
5239 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5240 PY_SSL_ERROR_WANT_CONNECT);
5241 /* non ssl.h errorcodes */
5242 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5243 PY_SSL_ERROR_EOF);
5244 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5245 PY_SSL_ERROR_INVALID_ERROR_CODE);
5246 /* cert requirements */
5247 PyModule_AddIntConstant(m, "CERT_NONE",
5248 PY_SSL_CERT_NONE);
5249 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5250 PY_SSL_CERT_OPTIONAL);
5251 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5252 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005253 /* CRL verification for verification_flags */
5254 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5255 0);
5256 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5257 X509_V_FLAG_CRL_CHECK);
5258 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5259 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5260 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5261 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005262#ifdef X509_V_FLAG_TRUSTED_FIRST
5263 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5264 X509_V_FLAG_TRUSTED_FIRST);
5265#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005266
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005267 /* Alert Descriptions from ssl.h */
5268 /* note RESERVED constants no longer intended for use have been removed */
5269 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5270
5271#define ADD_AD_CONSTANT(s) \
5272 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5273 SSL_AD_##s)
5274
5275 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5276 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5277 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5278 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5279 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5280 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5281 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5282 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5283 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5284 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5285 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5286 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5287 ADD_AD_CONSTANT(UNKNOWN_CA);
5288 ADD_AD_CONSTANT(ACCESS_DENIED);
5289 ADD_AD_CONSTANT(DECODE_ERROR);
5290 ADD_AD_CONSTANT(DECRYPT_ERROR);
5291 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5292 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5293 ADD_AD_CONSTANT(INTERNAL_ERROR);
5294 ADD_AD_CONSTANT(USER_CANCELLED);
5295 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005296 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005297#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5298 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5299#endif
5300#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5301 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5302#endif
5303#ifdef SSL_AD_UNRECOGNIZED_NAME
5304 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5305#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005306#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5307 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5308#endif
5309#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5310 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5311#endif
5312#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5313 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5314#endif
5315
5316#undef ADD_AD_CONSTANT
5317
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005318 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005319#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005320 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5321 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005322#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005323#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005324 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5325 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005326#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005327 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005328 PY_SSL_VERSION_TLS);
5329 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5330 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005331 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5332 PY_SSL_VERSION_TLS_CLIENT);
5333 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5334 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005335 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5336 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005337#if HAVE_TLSv1_2
5338 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5339 PY_SSL_VERSION_TLS1_1);
5340 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5341 PY_SSL_VERSION_TLS1_2);
5342#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005343
Antoine Pitroub5218772010-05-21 09:56:06 +00005344 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005345 PyModule_AddIntConstant(m, "OP_ALL",
5346 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005347 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5348 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5349 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005350#if HAVE_TLSv1_2
5351 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5352 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5353#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005354 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5355 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005356 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005357 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005358#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005359 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005360#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005361#ifdef SSL_OP_NO_COMPRESSION
5362 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5363 SSL_OP_NO_COMPRESSION);
5364#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005365
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005366#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005367 r = Py_True;
5368#else
5369 r = Py_False;
5370#endif
5371 Py_INCREF(r);
5372 PyModule_AddObject(m, "HAS_SNI", r);
5373
Antoine Pitroud6494802011-07-21 01:11:30 +02005374 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005375 Py_INCREF(r);
5376 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5377
Antoine Pitrou501da612011-12-21 09:27:41 +01005378#ifdef OPENSSL_NO_ECDH
5379 r = Py_False;
5380#else
5381 r = Py_True;
5382#endif
5383 Py_INCREF(r);
5384 PyModule_AddObject(m, "HAS_ECDH", r);
5385
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005386#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005387 r = Py_True;
5388#else
5389 r = Py_False;
5390#endif
5391 Py_INCREF(r);
5392 PyModule_AddObject(m, "HAS_NPN", r);
5393
Benjamin Petersoncca27322015-01-23 16:35:37 -05005394#ifdef HAVE_ALPN
5395 r = Py_True;
5396#else
5397 r = Py_False;
5398#endif
5399 Py_INCREF(r);
5400 PyModule_AddObject(m, "HAS_ALPN", r);
5401
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005402 /* Mappings for error codes */
5403 err_codes_to_names = PyDict_New();
5404 err_names_to_codes = PyDict_New();
5405 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5406 return NULL;
5407 errcode = error_codes;
5408 while (errcode->mnemonic != NULL) {
5409 PyObject *mnemo, *key;
5410 mnemo = PyUnicode_FromString(errcode->mnemonic);
5411 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5412 if (mnemo == NULL || key == NULL)
5413 return NULL;
5414 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5415 return NULL;
5416 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5417 return NULL;
5418 Py_DECREF(key);
5419 Py_DECREF(mnemo);
5420 errcode++;
5421 }
5422 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5423 return NULL;
5424 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5425 return NULL;
5426
5427 lib_codes_to_names = PyDict_New();
5428 if (lib_codes_to_names == NULL)
5429 return NULL;
5430 libcode = library_codes;
5431 while (libcode->library != NULL) {
5432 PyObject *mnemo, *key;
5433 key = PyLong_FromLong(libcode->code);
5434 mnemo = PyUnicode_FromString(libcode->library);
5435 if (key == NULL || mnemo == NULL)
5436 return NULL;
5437 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5438 return NULL;
5439 Py_DECREF(key);
5440 Py_DECREF(mnemo);
5441 libcode++;
5442 }
5443 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5444 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005445
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005446 /* OpenSSL version */
5447 /* SSLeay() gives us the version of the library linked against,
5448 which could be different from the headers version.
5449 */
5450 libver = SSLeay();
5451 r = PyLong_FromUnsignedLong(libver);
5452 if (r == NULL)
5453 return NULL;
5454 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5455 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005456 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005457 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5458 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5459 return NULL;
5460 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5461 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5462 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005463
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005464 libver = OPENSSL_VERSION_NUMBER;
5465 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5466 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5467 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5468 return NULL;
5469
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005470 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005471}