blob: 5ea354a60aacb5fe3db133cb4ed76da2151ed154 [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) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002639 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002640 return NULL;
2641 }
2642
2643 assert(type != NULL && type->tp_alloc != NULL);
2644 self = (PySSLContext *) type->tp_alloc(type, 0);
2645 if (self == NULL) {
2646 SSL_CTX_free(ctx);
2647 return NULL;
2648 }
2649 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002650#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002651 self->npn_protocols = NULL;
2652#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002653#ifdef HAVE_ALPN
2654 self->alpn_protocols = NULL;
2655#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002656#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002657 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002658#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002659 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002660 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2661 self->check_hostname = 1;
2662 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2663 Py_DECREF(self);
2664 return NULL;
2665 }
2666 } else {
2667 self->check_hostname = 0;
2668 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2669 Py_DECREF(self);
2670 return NULL;
2671 }
2672 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002673 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002674 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2675 if (proto_version != PY_SSL_VERSION_SSL2)
2676 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002677 if (proto_version != PY_SSL_VERSION_SSL3)
2678 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002679 /* Minimal security flags for server and client side context.
2680 * Client sockets ignore server-side parameters. */
2681#ifdef SSL_OP_NO_COMPRESSION
2682 options |= SSL_OP_NO_COMPRESSION;
2683#endif
2684#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2685 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2686#endif
2687#ifdef SSL_OP_SINGLE_DH_USE
2688 options |= SSL_OP_SINGLE_DH_USE;
2689#endif
2690#ifdef SSL_OP_SINGLE_ECDH_USE
2691 options |= SSL_OP_SINGLE_ECDH_USE;
2692#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002693 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002694
Christian Heimes358cfd42016-09-10 22:43:48 +02002695 /* A bare minimum cipher list without completly broken cipher suites.
2696 * It's far from perfect but gives users a better head start. */
2697 if (proto_version != PY_SSL_VERSION_SSL2) {
2698 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2699 } else {
2700 /* SSLv2 needs MD5 */
2701 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2702 }
2703 if (result == 0) {
2704 Py_DECREF(self);
2705 ERR_clear_error();
2706 PyErr_SetString(PySSLErrorObject,
2707 "No cipher can be selected.");
2708 return NULL;
2709 }
2710
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002711#if defined(SSL_MODE_RELEASE_BUFFERS)
2712 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2713 usage for no cost at all. However, don't do this for OpenSSL versions
2714 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2715 2014-0198. I can't find exactly which beta fixed this CVE, so be
2716 conservative and assume it wasn't fixed until release. We do this check
2717 at runtime to avoid problems from the dynamic linker.
2718 See #25672 for more on this. */
2719 libver = SSLeay();
2720 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2721 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2722 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2723 }
2724#endif
2725
2726
Donald Stufft8ae264c2017-03-02 11:45:29 -05002727#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002728 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2729 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002730 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2731 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002732#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002733 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2734#else
2735 {
2736 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2737 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2738 EC_KEY_free(key);
2739 }
2740#endif
2741#endif
2742
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002743#define SID_CTX "Python"
2744 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2745 sizeof(SID_CTX));
2746#undef SID_CTX
2747
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002748#ifdef X509_V_FLAG_TRUSTED_FIRST
2749 {
2750 /* Improve trust chain building when cross-signed intermediate
2751 certificates are present. See https://bugs.python.org/issue23476. */
2752 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2753 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2754 }
2755#endif
2756
Antoine Pitrou152efa22010-05-16 18:19:27 +00002757 return (PyObject *)self;
2758}
2759
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002760static int
2761context_traverse(PySSLContext *self, visitproc visit, void *arg)
2762{
2763#ifndef OPENSSL_NO_TLSEXT
2764 Py_VISIT(self->set_hostname);
2765#endif
2766 return 0;
2767}
2768
2769static int
2770context_clear(PySSLContext *self)
2771{
2772#ifndef OPENSSL_NO_TLSEXT
2773 Py_CLEAR(self->set_hostname);
2774#endif
2775 return 0;
2776}
2777
Antoine Pitrou152efa22010-05-16 18:19:27 +00002778static void
2779context_dealloc(PySSLContext *self)
2780{
INADA Naokia6296d32017-08-24 14:55:17 +09002781 /* bpo-31095: UnTrack is needed before calling any callbacks */
2782 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002783 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002784 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002785#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002786 PyMem_FREE(self->npn_protocols);
2787#endif
2788#ifdef HAVE_ALPN
2789 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002790#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002791 Py_TYPE(self)->tp_free(self);
2792}
2793
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002794/*[clinic input]
2795_ssl._SSLContext.set_ciphers
2796 cipherlist: str
2797 /
2798[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002799
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002800static PyObject *
2801_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2802/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2803{
2804 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002805 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002806 /* Clearing the error queue is necessary on some OpenSSL versions,
2807 otherwise the error will be reported again when another SSL call
2808 is done. */
2809 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002810 PyErr_SetString(PySSLErrorObject,
2811 "No cipher can be selected.");
2812 return NULL;
2813 }
2814 Py_RETURN_NONE;
2815}
2816
Christian Heimes25bfcd52016-09-06 00:04:45 +02002817#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2818/*[clinic input]
2819_ssl._SSLContext.get_ciphers
2820[clinic start generated code]*/
2821
2822static PyObject *
2823_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2824/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2825{
2826 SSL *ssl = NULL;
2827 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002828 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002829 int i=0;
2830 PyObject *result = NULL, *dct;
2831
2832 ssl = SSL_new(self->ctx);
2833 if (ssl == NULL) {
2834 _setSSLError(NULL, 0, __FILE__, __LINE__);
2835 goto exit;
2836 }
2837 sk = SSL_get_ciphers(ssl);
2838
2839 result = PyList_New(sk_SSL_CIPHER_num(sk));
2840 if (result == NULL) {
2841 goto exit;
2842 }
2843
2844 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2845 cipher = sk_SSL_CIPHER_value(sk, i);
2846 dct = cipher_to_dict(cipher);
2847 if (dct == NULL) {
2848 Py_CLEAR(result);
2849 goto exit;
2850 }
2851 PyList_SET_ITEM(result, i, dct);
2852 }
2853
2854 exit:
2855 if (ssl != NULL)
2856 SSL_free(ssl);
2857 return result;
2858
2859}
2860#endif
2861
2862
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002863#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002864static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002865do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2866 const unsigned char *server_protocols, unsigned int server_protocols_len,
2867 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002868{
Benjamin Peterson88615022015-01-23 17:30:26 -05002869 int ret;
2870 if (client_protocols == NULL) {
2871 client_protocols = (unsigned char *)"";
2872 client_protocols_len = 0;
2873 }
2874 if (server_protocols == NULL) {
2875 server_protocols = (unsigned char *)"";
2876 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002877 }
2878
Benjamin Peterson88615022015-01-23 17:30:26 -05002879 ret = SSL_select_next_proto(out, outlen,
2880 server_protocols, server_protocols_len,
2881 client_protocols, client_protocols_len);
2882 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2883 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002884
2885 return SSL_TLSEXT_ERR_OK;
2886}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002887#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002888
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002889#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002890/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2891static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002892_advertiseNPN_cb(SSL *s,
2893 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002894 void *args)
2895{
2896 PySSLContext *ssl_ctx = (PySSLContext *) args;
2897
2898 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002899 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002900 *len = 0;
2901 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05002902 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002903 *len = ssl_ctx->npn_protocols_len;
2904 }
2905
2906 return SSL_TLSEXT_ERR_OK;
2907}
2908/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
2909static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002910_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002911 unsigned char **out, unsigned char *outlen,
2912 const unsigned char *server, unsigned int server_len,
2913 void *args)
2914{
Benjamin Petersoncca27322015-01-23 16:35:37 -05002915 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002916 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05002917 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002918}
2919#endif
2920
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002921/*[clinic input]
2922_ssl._SSLContext._set_npn_protocols
2923 protos: Py_buffer
2924 /
2925[clinic start generated code]*/
2926
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002927static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002928_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
2929 Py_buffer *protos)
2930/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002931{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002932#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002933 PyMem_Free(self->npn_protocols);
2934 self->npn_protocols = PyMem_Malloc(protos->len);
2935 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002936 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002937 memcpy(self->npn_protocols, protos->buf, protos->len);
2938 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002939
2940 /* set both server and client callbacks, because the context can
2941 * be used to create both types of sockets */
2942 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
2943 _advertiseNPN_cb,
2944 self);
2945 SSL_CTX_set_next_proto_select_cb(self->ctx,
2946 _selectNPN_cb,
2947 self);
2948
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002949 Py_RETURN_NONE;
2950#else
2951 PyErr_SetString(PyExc_NotImplementedError,
2952 "The NPN extension requires OpenSSL 1.0.1 or later.");
2953 return NULL;
2954#endif
2955}
2956
Benjamin Petersoncca27322015-01-23 16:35:37 -05002957#ifdef HAVE_ALPN
2958static int
2959_selectALPN_cb(SSL *s,
2960 const unsigned char **out, unsigned char *outlen,
2961 const unsigned char *client_protocols, unsigned int client_protocols_len,
2962 void *args)
2963{
2964 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05002965 return do_protocol_selection(1, (unsigned char **)out, outlen,
2966 ctx->alpn_protocols, ctx->alpn_protocols_len,
2967 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002968}
2969#endif
2970
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002971/*[clinic input]
2972_ssl._SSLContext._set_alpn_protocols
2973 protos: Py_buffer
2974 /
2975[clinic start generated code]*/
2976
Benjamin Petersoncca27322015-01-23 16:35:37 -05002977static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002978_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
2979 Py_buffer *protos)
2980/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05002981{
2982#ifdef HAVE_ALPN
Segev Finer5cff6372017-07-27 01:19:17 +03002983 if (protos->len > UINT_MAX) {
2984 PyErr_Format(PyExc_OverflowError,
2985 "protocols longer than %d bytes", UINT_MAX);
2986 return NULL;
2987 }
2988
Benjamin Petersoncca27322015-01-23 16:35:37 -05002989 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002990 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05002991 if (!self->alpn_protocols)
2992 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002993 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03002994 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002995
2996 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
2997 return PyErr_NoMemory();
2998 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
2999
Benjamin Petersoncca27322015-01-23 16:35:37 -05003000 Py_RETURN_NONE;
3001#else
3002 PyErr_SetString(PyExc_NotImplementedError,
3003 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3004 return NULL;
3005#endif
3006}
3007
Antoine Pitrou152efa22010-05-16 18:19:27 +00003008static PyObject *
3009get_verify_mode(PySSLContext *self, void *c)
3010{
3011 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3012 case SSL_VERIFY_NONE:
3013 return PyLong_FromLong(PY_SSL_CERT_NONE);
3014 case SSL_VERIFY_PEER:
3015 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3016 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3017 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3018 }
3019 PyErr_SetString(PySSLErrorObject,
3020 "invalid return value from SSL_CTX_get_verify_mode");
3021 return NULL;
3022}
3023
3024static int
3025set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3026{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003027 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003028 if (!PyArg_Parse(arg, "i", &n))
3029 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003030 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003031 PyErr_SetString(PyExc_ValueError,
3032 "Cannot set verify_mode to CERT_NONE when "
3033 "check_hostname is enabled.");
3034 return -1;
3035 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003036 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003037}
3038
3039static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003040get_verify_flags(PySSLContext *self, void *c)
3041{
3042 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003043 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003044 unsigned long flags;
3045
3046 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003047 param = X509_STORE_get0_param(store);
3048 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003049 return PyLong_FromUnsignedLong(flags);
3050}
3051
3052static int
3053set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3054{
3055 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003056 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003057 unsigned long new_flags, flags, set, clear;
3058
3059 if (!PyArg_Parse(arg, "k", &new_flags))
3060 return -1;
3061 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003062 param = X509_STORE_get0_param(store);
3063 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003064 clear = flags & ~new_flags;
3065 set = ~flags & new_flags;
3066 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003067 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003068 _setSSLError(NULL, 0, __FILE__, __LINE__);
3069 return -1;
3070 }
3071 }
3072 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003073 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003074 _setSSLError(NULL, 0, __FILE__, __LINE__);
3075 return -1;
3076 }
3077 }
3078 return 0;
3079}
3080
3081static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003082get_options(PySSLContext *self, void *c)
3083{
3084 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3085}
3086
3087static int
3088set_options(PySSLContext *self, PyObject *arg, void *c)
3089{
3090 long new_opts, opts, set, clear;
3091 if (!PyArg_Parse(arg, "l", &new_opts))
3092 return -1;
3093 opts = SSL_CTX_get_options(self->ctx);
3094 clear = opts & ~new_opts;
3095 set = ~opts & new_opts;
3096 if (clear) {
3097#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3098 SSL_CTX_clear_options(self->ctx, clear);
3099#else
3100 PyErr_SetString(PyExc_ValueError,
3101 "can't clear options before OpenSSL 0.9.8m");
3102 return -1;
3103#endif
3104 }
3105 if (set)
3106 SSL_CTX_set_options(self->ctx, set);
3107 return 0;
3108}
3109
Christian Heimes1aa9a752013-12-02 02:41:19 +01003110static PyObject *
3111get_check_hostname(PySSLContext *self, void *c)
3112{
3113 return PyBool_FromLong(self->check_hostname);
3114}
3115
3116static int
3117set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3118{
3119 int check_hostname;
3120 if (!PyArg_Parse(arg, "p", &check_hostname))
3121 return -1;
3122 if (check_hostname &&
3123 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
3124 PyErr_SetString(PyExc_ValueError,
3125 "check_hostname needs a SSL context with either "
3126 "CERT_OPTIONAL or CERT_REQUIRED");
3127 return -1;
3128 }
3129 self->check_hostname = check_hostname;
3130 return 0;
3131}
3132
3133
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003134typedef struct {
3135 PyThreadState *thread_state;
3136 PyObject *callable;
3137 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003138 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003139 int error;
3140} _PySSLPasswordInfo;
3141
3142static int
3143_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3144 const char *bad_type_error)
3145{
3146 /* Set the password and size fields of a _PySSLPasswordInfo struct
3147 from a unicode, bytes, or byte array object.
3148 The password field will be dynamically allocated and must be freed
3149 by the caller */
3150 PyObject *password_bytes = NULL;
3151 const char *data = NULL;
3152 Py_ssize_t size;
3153
3154 if (PyUnicode_Check(password)) {
3155 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3156 if (!password_bytes) {
3157 goto error;
3158 }
3159 data = PyBytes_AS_STRING(password_bytes);
3160 size = PyBytes_GET_SIZE(password_bytes);
3161 } else if (PyBytes_Check(password)) {
3162 data = PyBytes_AS_STRING(password);
3163 size = PyBytes_GET_SIZE(password);
3164 } else if (PyByteArray_Check(password)) {
3165 data = PyByteArray_AS_STRING(password);
3166 size = PyByteArray_GET_SIZE(password);
3167 } else {
3168 PyErr_SetString(PyExc_TypeError, bad_type_error);
3169 goto error;
3170 }
3171
Victor Stinner9ee02032013-06-23 15:08:23 +02003172 if (size > (Py_ssize_t)INT_MAX) {
3173 PyErr_Format(PyExc_ValueError,
3174 "password cannot be longer than %d bytes", INT_MAX);
3175 goto error;
3176 }
3177
Victor Stinner11ebff22013-07-07 17:07:52 +02003178 PyMem_Free(pw_info->password);
3179 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003180 if (!pw_info->password) {
3181 PyErr_SetString(PyExc_MemoryError,
3182 "unable to allocate password buffer");
3183 goto error;
3184 }
3185 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003186 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003187
3188 Py_XDECREF(password_bytes);
3189 return 1;
3190
3191error:
3192 Py_XDECREF(password_bytes);
3193 return 0;
3194}
3195
3196static int
3197_password_callback(char *buf, int size, int rwflag, void *userdata)
3198{
3199 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3200 PyObject *fn_ret = NULL;
3201
3202 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3203
3204 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003205 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003206 if (!fn_ret) {
3207 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3208 core python API, so we could use it to add a frame here */
3209 goto error;
3210 }
3211
3212 if (!_pwinfo_set(pw_info, fn_ret,
3213 "password callback must return a string")) {
3214 goto error;
3215 }
3216 Py_CLEAR(fn_ret);
3217 }
3218
3219 if (pw_info->size > size) {
3220 PyErr_Format(PyExc_ValueError,
3221 "password cannot be longer than %d bytes", size);
3222 goto error;
3223 }
3224
3225 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3226 memcpy(buf, pw_info->password, pw_info->size);
3227 return pw_info->size;
3228
3229error:
3230 Py_XDECREF(fn_ret);
3231 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3232 pw_info->error = 1;
3233 return -1;
3234}
3235
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003236/*[clinic input]
3237_ssl._SSLContext.load_cert_chain
3238 certfile: object
3239 keyfile: object = NULL
3240 password: object = NULL
3241
3242[clinic start generated code]*/
3243
Antoine Pitroub5218772010-05-21 09:56:06 +00003244static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003245_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3246 PyObject *keyfile, PyObject *password)
3247/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003248{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003249 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003250 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3251 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003252 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003253 int r;
3254
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003255 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003256 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003257 if (keyfile == Py_None)
3258 keyfile = NULL;
3259 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3260 PyErr_SetString(PyExc_TypeError,
3261 "certfile should be a valid filesystem path");
3262 return NULL;
3263 }
3264 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3265 PyErr_SetString(PyExc_TypeError,
3266 "keyfile should be a valid filesystem path");
3267 goto error;
3268 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003269 if (password && password != Py_None) {
3270 if (PyCallable_Check(password)) {
3271 pw_info.callable = password;
3272 } else if (!_pwinfo_set(&pw_info, password,
3273 "password should be a string or callable")) {
3274 goto error;
3275 }
3276 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3277 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3278 }
3279 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003280 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3281 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003282 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003283 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003284 if (pw_info.error) {
3285 ERR_clear_error();
3286 /* the password callback has already set the error information */
3287 }
3288 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003289 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003290 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003291 }
3292 else {
3293 _setSSLError(NULL, 0, __FILE__, __LINE__);
3294 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003295 goto error;
3296 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003297 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003298 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003299 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3300 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003301 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3302 Py_CLEAR(keyfile_bytes);
3303 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003304 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003305 if (pw_info.error) {
3306 ERR_clear_error();
3307 /* the password callback has already set the error information */
3308 }
3309 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003310 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003311 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003312 }
3313 else {
3314 _setSSLError(NULL, 0, __FILE__, __LINE__);
3315 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003316 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003317 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003318 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003319 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003320 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003321 if (r != 1) {
3322 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003323 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003324 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003325 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3326 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003327 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003328 Py_RETURN_NONE;
3329
3330error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003331 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3332 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003333 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003334 Py_XDECREF(keyfile_bytes);
3335 Py_XDECREF(certfile_bytes);
3336 return NULL;
3337}
3338
Christian Heimesefff7062013-11-21 03:35:02 +01003339/* internal helper function, returns -1 on error
3340 */
3341static int
3342_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3343 int filetype)
3344{
3345 BIO *biobuf = NULL;
3346 X509_STORE *store;
3347 int retval = 0, err, loaded = 0;
3348
3349 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3350
3351 if (len <= 0) {
3352 PyErr_SetString(PyExc_ValueError,
3353 "Empty certificate data");
3354 return -1;
3355 } else if (len > INT_MAX) {
3356 PyErr_SetString(PyExc_OverflowError,
3357 "Certificate data is too long.");
3358 return -1;
3359 }
3360
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003361 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003362 if (biobuf == NULL) {
3363 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3364 return -1;
3365 }
3366
3367 store = SSL_CTX_get_cert_store(self->ctx);
3368 assert(store != NULL);
3369
3370 while (1) {
3371 X509 *cert = NULL;
3372 int r;
3373
3374 if (filetype == SSL_FILETYPE_ASN1) {
3375 cert = d2i_X509_bio(biobuf, NULL);
3376 } else {
3377 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003378 SSL_CTX_get_default_passwd_cb(self->ctx),
3379 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3380 );
Christian Heimesefff7062013-11-21 03:35:02 +01003381 }
3382 if (cert == NULL) {
3383 break;
3384 }
3385 r = X509_STORE_add_cert(store, cert);
3386 X509_free(cert);
3387 if (!r) {
3388 err = ERR_peek_last_error();
3389 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3390 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3391 /* cert already in hash table, not an error */
3392 ERR_clear_error();
3393 } else {
3394 break;
3395 }
3396 }
3397 loaded++;
3398 }
3399
3400 err = ERR_peek_last_error();
3401 if ((filetype == SSL_FILETYPE_ASN1) &&
3402 (loaded > 0) &&
3403 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3404 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3405 /* EOF ASN1 file, not an error */
3406 ERR_clear_error();
3407 retval = 0;
3408 } else if ((filetype == SSL_FILETYPE_PEM) &&
3409 (loaded > 0) &&
3410 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3411 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3412 /* EOF PEM file, not an error */
3413 ERR_clear_error();
3414 retval = 0;
3415 } else {
3416 _setSSLError(NULL, 0, __FILE__, __LINE__);
3417 retval = -1;
3418 }
3419
3420 BIO_free(biobuf);
3421 return retval;
3422}
3423
3424
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003425/*[clinic input]
3426_ssl._SSLContext.load_verify_locations
3427 cafile: object = NULL
3428 capath: object = NULL
3429 cadata: object = NULL
3430
3431[clinic start generated code]*/
3432
Antoine Pitrou152efa22010-05-16 18:19:27 +00003433static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003434_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3435 PyObject *cafile,
3436 PyObject *capath,
3437 PyObject *cadata)
3438/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003439{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003440 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3441 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003442 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003443
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003444 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003445 if (cafile == Py_None)
3446 cafile = NULL;
3447 if (capath == Py_None)
3448 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003449 if (cadata == Py_None)
3450 cadata = NULL;
3451
3452 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003453 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003454 "cafile, capath and cadata cannot be all omitted");
3455 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003456 }
3457 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3458 PyErr_SetString(PyExc_TypeError,
3459 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003460 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003461 }
3462 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003463 PyErr_SetString(PyExc_TypeError,
3464 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003465 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003466 }
Christian Heimesefff7062013-11-21 03:35:02 +01003467
3468 /* validata cadata type and load cadata */
3469 if (cadata) {
3470 Py_buffer buf;
3471 PyObject *cadata_ascii = NULL;
3472
3473 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3474 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3475 PyBuffer_Release(&buf);
3476 PyErr_SetString(PyExc_TypeError,
3477 "cadata should be a contiguous buffer with "
3478 "a single dimension");
3479 goto error;
3480 }
3481 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3482 PyBuffer_Release(&buf);
3483 if (r == -1) {
3484 goto error;
3485 }
3486 } else {
3487 PyErr_Clear();
3488 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3489 if (cadata_ascii == NULL) {
3490 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003491 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003492 "bytes-like object");
3493 goto error;
3494 }
3495 r = _add_ca_certs(self,
3496 PyBytes_AS_STRING(cadata_ascii),
3497 PyBytes_GET_SIZE(cadata_ascii),
3498 SSL_FILETYPE_PEM);
3499 Py_DECREF(cadata_ascii);
3500 if (r == -1) {
3501 goto error;
3502 }
3503 }
3504 }
3505
3506 /* load cafile or capath */
3507 if (cafile || capath) {
3508 if (cafile)
3509 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3510 if (capath)
3511 capath_buf = PyBytes_AS_STRING(capath_bytes);
3512 PySSL_BEGIN_ALLOW_THREADS
3513 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3514 PySSL_END_ALLOW_THREADS
3515 if (r != 1) {
3516 ok = 0;
3517 if (errno != 0) {
3518 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003519 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003520 }
3521 else {
3522 _setSSLError(NULL, 0, __FILE__, __LINE__);
3523 }
3524 goto error;
3525 }
3526 }
3527 goto end;
3528
3529 error:
3530 ok = 0;
3531 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003532 Py_XDECREF(cafile_bytes);
3533 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003534 if (ok) {
3535 Py_RETURN_NONE;
3536 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003537 return NULL;
3538 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003539}
3540
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003541/*[clinic input]
3542_ssl._SSLContext.load_dh_params
3543 path as filepath: object
3544 /
3545
3546[clinic start generated code]*/
3547
Antoine Pitrou152efa22010-05-16 18:19:27 +00003548static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003549_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3550/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003551{
3552 FILE *f;
3553 DH *dh;
3554
Victor Stinnerdaf45552013-08-28 00:53:59 +02003555 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003556 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003557 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003558
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003559 errno = 0;
3560 PySSL_BEGIN_ALLOW_THREADS
3561 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003562 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003563 PySSL_END_ALLOW_THREADS
3564 if (dh == NULL) {
3565 if (errno != 0) {
3566 ERR_clear_error();
3567 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3568 }
3569 else {
3570 _setSSLError(NULL, 0, __FILE__, __LINE__);
3571 }
3572 return NULL;
3573 }
3574 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3575 _setSSLError(NULL, 0, __FILE__, __LINE__);
3576 DH_free(dh);
3577 Py_RETURN_NONE;
3578}
3579
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003580/*[clinic input]
3581_ssl._SSLContext._wrap_socket
3582 sock: object(subclass_of="PySocketModule.Sock_Type")
3583 server_side: int
3584 server_hostname as hostname_obj: object = None
3585
3586[clinic start generated code]*/
3587
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003588static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003589_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3590 int server_side, PyObject *hostname_obj)
3591/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003592{
Antoine Pitroud5323212010-10-22 18:19:07 +00003593 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003594 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003595
Antoine Pitroud5323212010-10-22 18:19:07 +00003596 /* server_hostname is either None (or absent), or to be encoded
3597 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003598 if (hostname_obj != Py_None) {
3599 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003600 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003601 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003602
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003603 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3604 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003605 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003606 if (hostname != NULL)
3607 PyMem_Free(hostname);
3608 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003609}
3610
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003611/*[clinic input]
3612_ssl._SSLContext._wrap_bio
3613 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3614 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3615 server_side: int
3616 server_hostname as hostname_obj: object = None
3617
3618[clinic start generated code]*/
3619
Antoine Pitroub0182c82010-10-12 20:09:02 +00003620static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003621_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3622 PySSLMemoryBIO *outgoing, int server_side,
3623 PyObject *hostname_obj)
3624/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003625{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003626 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003627 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003628
3629 /* server_hostname is either None (or absent), or to be encoded
3630 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003631 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003632 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3633 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003634 }
3635
3636 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3637 incoming, outgoing);
3638
3639 PyMem_Free(hostname);
3640 return res;
3641}
3642
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003643/*[clinic input]
3644_ssl._SSLContext.session_stats
3645[clinic start generated code]*/
3646
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003647static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003648_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3649/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003650{
3651 int r;
3652 PyObject *value, *stats = PyDict_New();
3653 if (!stats)
3654 return NULL;
3655
3656#define ADD_STATS(SSL_NAME, KEY_NAME) \
3657 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3658 if (value == NULL) \
3659 goto error; \
3660 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3661 Py_DECREF(value); \
3662 if (r < 0) \
3663 goto error;
3664
3665 ADD_STATS(number, "number");
3666 ADD_STATS(connect, "connect");
3667 ADD_STATS(connect_good, "connect_good");
3668 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3669 ADD_STATS(accept, "accept");
3670 ADD_STATS(accept_good, "accept_good");
3671 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3672 ADD_STATS(accept, "accept");
3673 ADD_STATS(hits, "hits");
3674 ADD_STATS(misses, "misses");
3675 ADD_STATS(timeouts, "timeouts");
3676 ADD_STATS(cache_full, "cache_full");
3677
3678#undef ADD_STATS
3679
3680 return stats;
3681
3682error:
3683 Py_DECREF(stats);
3684 return NULL;
3685}
3686
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003687/*[clinic input]
3688_ssl._SSLContext.set_default_verify_paths
3689[clinic start generated code]*/
3690
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003691static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003692_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3693/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003694{
3695 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3696 _setSSLError(NULL, 0, __FILE__, __LINE__);
3697 return NULL;
3698 }
3699 Py_RETURN_NONE;
3700}
3701
Antoine Pitrou501da612011-12-21 09:27:41 +01003702#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003703/*[clinic input]
3704_ssl._SSLContext.set_ecdh_curve
3705 name: object
3706 /
3707
3708[clinic start generated code]*/
3709
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003710static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003711_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3712/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003713{
3714 PyObject *name_bytes;
3715 int nid;
3716 EC_KEY *key;
3717
3718 if (!PyUnicode_FSConverter(name, &name_bytes))
3719 return NULL;
3720 assert(PyBytes_Check(name_bytes));
3721 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3722 Py_DECREF(name_bytes);
3723 if (nid == 0) {
3724 PyErr_Format(PyExc_ValueError,
3725 "unknown elliptic curve name %R", name);
3726 return NULL;
3727 }
3728 key = EC_KEY_new_by_curve_name(nid);
3729 if (key == NULL) {
3730 _setSSLError(NULL, 0, __FILE__, __LINE__);
3731 return NULL;
3732 }
3733 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3734 EC_KEY_free(key);
3735 Py_RETURN_NONE;
3736}
Antoine Pitrou501da612011-12-21 09:27:41 +01003737#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003738
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003739#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003740static int
3741_servername_callback(SSL *s, int *al, void *args)
3742{
3743 int ret;
3744 PySSLContext *ssl_ctx = (PySSLContext *) args;
3745 PySSLSocket *ssl;
3746 PyObject *servername_o;
3747 PyObject *servername_idna;
3748 PyObject *result;
3749 /* The high-level ssl.SSLSocket object */
3750 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003751 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003752 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003753
3754 if (ssl_ctx->set_hostname == NULL) {
3755 /* remove race condition in this the call back while if removing the
3756 * callback is in progress */
3757 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003758 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003759 }
3760
3761 ssl = SSL_get_app_data(s);
3762 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003763
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003764 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003765 * SSL connection and that has a .context attribute that can be changed to
3766 * identify the requested hostname. Since the official API is the Python
3767 * level API we want to pass the callback a Python level object rather than
3768 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3769 * SSLObject) that will be passed. Otherwise if there's a socket then that
3770 * will be passed. If both do not exist only then the C-level object is
3771 * passed. */
3772 if (ssl->owner)
3773 ssl_socket = PyWeakref_GetObject(ssl->owner);
3774 else if (ssl->Socket)
3775 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3776 else
3777 ssl_socket = (PyObject *) ssl;
3778
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003779 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003780 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003781 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003782
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003783 if (servername == NULL) {
3784 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3785 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003786 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003787 else {
3788 servername_o = PyBytes_FromString(servername);
3789 if (servername_o == NULL) {
3790 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3791 goto error;
3792 }
3793 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3794 if (servername_idna == NULL) {
3795 PyErr_WriteUnraisable(servername_o);
3796 Py_DECREF(servername_o);
3797 goto error;
3798 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003799 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003800 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3801 servername_idna, ssl_ctx, NULL);
3802 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003803 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003804 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003805
3806 if (result == NULL) {
3807 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3808 *al = SSL_AD_HANDSHAKE_FAILURE;
3809 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3810 }
3811 else {
3812 if (result != Py_None) {
3813 *al = (int) PyLong_AsLong(result);
3814 if (PyErr_Occurred()) {
3815 PyErr_WriteUnraisable(result);
3816 *al = SSL_AD_INTERNAL_ERROR;
3817 }
3818 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3819 }
3820 else {
3821 ret = SSL_TLSEXT_ERR_OK;
3822 }
3823 Py_DECREF(result);
3824 }
3825
3826 PyGILState_Release(gstate);
3827 return ret;
3828
3829error:
3830 Py_DECREF(ssl_socket);
3831 *al = SSL_AD_INTERNAL_ERROR;
3832 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3833 PyGILState_Release(gstate);
3834 return ret;
3835}
Antoine Pitroua5963382013-03-30 16:39:00 +01003836#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003837
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003838/*[clinic input]
3839_ssl._SSLContext.set_servername_callback
3840 method as cb: object
3841 /
3842
3843Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3844
3845If the argument is None then the callback is disabled. The method is called
3846with the SSLSocket, the server name as a string, and the SSLContext object.
3847See RFC 6066 for details of the SNI extension.
3848[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003849
3850static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003851_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3852/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003853{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003854#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003855 Py_CLEAR(self->set_hostname);
3856 if (cb == Py_None) {
3857 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3858 }
3859 else {
3860 if (!PyCallable_Check(cb)) {
3861 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3862 PyErr_SetString(PyExc_TypeError,
3863 "not a callable object");
3864 return NULL;
3865 }
3866 Py_INCREF(cb);
3867 self->set_hostname = cb;
3868 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3869 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3870 }
3871 Py_RETURN_NONE;
3872#else
3873 PyErr_SetString(PyExc_NotImplementedError,
3874 "The TLS extension servername callback, "
3875 "SSL_CTX_set_tlsext_servername_callback, "
3876 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003877 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003878#endif
3879}
3880
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003881/*[clinic input]
3882_ssl._SSLContext.cert_store_stats
3883
3884Returns quantities of loaded X.509 certificates.
3885
3886X.509 certificates with a CA extension and certificate revocation lists
3887inside the context's cert store.
3888
3889NOTE: Certificates in a capath directory aren't loaded unless they have
3890been used at least once.
3891[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003892
3893static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003894_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
3895/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003896{
3897 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003898 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003899 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02003900 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003901
3902 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003903 objs = X509_STORE_get0_objects(store);
3904 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
3905 obj = sk_X509_OBJECT_value(objs, i);
3906 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003907 case X509_LU_X509:
3908 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02003909 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003910 ca++;
3911 }
3912 break;
3913 case X509_LU_CRL:
3914 crl++;
3915 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003916 default:
3917 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
3918 * As far as I can tell they are internal states and never
3919 * stored in a cert store */
3920 break;
3921 }
3922 }
3923 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
3924 "x509_ca", ca);
3925}
3926
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003927/*[clinic input]
3928_ssl._SSLContext.get_ca_certs
3929 binary_form: bool = False
3930
3931Returns a list of dicts with information of loaded CA certs.
3932
3933If the optional argument is True, returns a DER-encoded copy of the CA
3934certificate.
3935
3936NOTE: Certificates in a capath directory aren't loaded unless they have
3937been used at least once.
3938[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003939
3940static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003941_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
3942/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003943{
3944 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003945 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003946 PyObject *ci = NULL, *rlist = NULL;
3947 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02003948
3949 if ((rlist = PyList_New(0)) == NULL) {
3950 return NULL;
3951 }
3952
3953 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003954 objs = X509_STORE_get0_objects(store);
3955 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003956 X509_OBJECT *obj;
3957 X509 *cert;
3958
Christian Heimes598894f2016-09-05 23:19:05 +02003959 obj = sk_X509_OBJECT_value(objs, i);
3960 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003961 /* not a x509 cert */
3962 continue;
3963 }
3964 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02003965 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02003966 if (!X509_check_ca(cert)) {
3967 continue;
3968 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003969 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02003970 ci = _certificate_to_der(cert);
3971 } else {
3972 ci = _decode_certificate(cert);
3973 }
3974 if (ci == NULL) {
3975 goto error;
3976 }
3977 if (PyList_Append(rlist, ci) == -1) {
3978 goto error;
3979 }
3980 Py_CLEAR(ci);
3981 }
3982 return rlist;
3983
3984 error:
3985 Py_XDECREF(ci);
3986 Py_XDECREF(rlist);
3987 return NULL;
3988}
3989
3990
Antoine Pitrou152efa22010-05-16 18:19:27 +00003991static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003992 {"check_hostname", (getter) get_check_hostname,
3993 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00003994 {"options", (getter) get_options,
3995 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01003996 {"verify_flags", (getter) get_verify_flags,
3997 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00003998 {"verify_mode", (getter) get_verify_mode,
3999 (setter) set_verify_mode, NULL},
4000 {NULL}, /* sentinel */
4001};
4002
4003static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004004 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4005 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4006 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4007 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4008 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4009 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4010 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4011 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4012 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4013 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4014 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4015 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4016 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4017 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004018 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004019 {NULL, NULL} /* sentinel */
4020};
4021
4022static PyTypeObject PySSLContext_Type = {
4023 PyVarObject_HEAD_INIT(NULL, 0)
4024 "_ssl._SSLContext", /*tp_name*/
4025 sizeof(PySSLContext), /*tp_basicsize*/
4026 0, /*tp_itemsize*/
4027 (destructor)context_dealloc, /*tp_dealloc*/
4028 0, /*tp_print*/
4029 0, /*tp_getattr*/
4030 0, /*tp_setattr*/
4031 0, /*tp_reserved*/
4032 0, /*tp_repr*/
4033 0, /*tp_as_number*/
4034 0, /*tp_as_sequence*/
4035 0, /*tp_as_mapping*/
4036 0, /*tp_hash*/
4037 0, /*tp_call*/
4038 0, /*tp_str*/
4039 0, /*tp_getattro*/
4040 0, /*tp_setattro*/
4041 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004042 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004043 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004044 (traverseproc) context_traverse, /*tp_traverse*/
4045 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004046 0, /*tp_richcompare*/
4047 0, /*tp_weaklistoffset*/
4048 0, /*tp_iter*/
4049 0, /*tp_iternext*/
4050 context_methods, /*tp_methods*/
4051 0, /*tp_members*/
4052 context_getsetlist, /*tp_getset*/
4053 0, /*tp_base*/
4054 0, /*tp_dict*/
4055 0, /*tp_descr_get*/
4056 0, /*tp_descr_set*/
4057 0, /*tp_dictoffset*/
4058 0, /*tp_init*/
4059 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004060 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004061};
4062
4063
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004064/*
4065 * MemoryBIO objects
4066 */
4067
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004068/*[clinic input]
4069@classmethod
4070_ssl.MemoryBIO.__new__
4071
4072[clinic start generated code]*/
4073
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004074static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004075_ssl_MemoryBIO_impl(PyTypeObject *type)
4076/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004077{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004078 BIO *bio;
4079 PySSLMemoryBIO *self;
4080
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004081 bio = BIO_new(BIO_s_mem());
4082 if (bio == NULL) {
4083 PyErr_SetString(PySSLErrorObject,
4084 "failed to allocate BIO");
4085 return NULL;
4086 }
4087 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4088 * just that no data is currently available. The SSL routines should retry
4089 * the read, which we can achieve by calling BIO_set_retry_read(). */
4090 BIO_set_retry_read(bio);
4091 BIO_set_mem_eof_return(bio, -1);
4092
4093 assert(type != NULL && type->tp_alloc != NULL);
4094 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4095 if (self == NULL) {
4096 BIO_free(bio);
4097 return NULL;
4098 }
4099 self->bio = bio;
4100 self->eof_written = 0;
4101
4102 return (PyObject *) self;
4103}
4104
4105static void
4106memory_bio_dealloc(PySSLMemoryBIO *self)
4107{
4108 BIO_free(self->bio);
4109 Py_TYPE(self)->tp_free(self);
4110}
4111
4112static PyObject *
4113memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4114{
Segev Finer5cff6372017-07-27 01:19:17 +03004115 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004116}
4117
4118PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4119"The number of bytes pending in the memory BIO.");
4120
4121static PyObject *
4122memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4123{
4124 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4125 && self->eof_written);
4126}
4127
4128PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4129"Whether the memory BIO is at EOF.");
4130
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004131/*[clinic input]
4132_ssl.MemoryBIO.read
4133 size as len: int = -1
4134 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004135
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004136Read up to size bytes from the memory BIO.
4137
4138If size is not specified, read the entire buffer.
4139If the return value is an empty bytes instance, this means either
4140EOF or that no data is available. Use the "eof" property to
4141distinguish between the two.
4142[clinic start generated code]*/
4143
4144static PyObject *
4145_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4146/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4147{
4148 int avail, nbytes;
4149 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004150
Segev Finer5cff6372017-07-27 01:19:17 +03004151 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004152 if ((len < 0) || (len > avail))
4153 len = avail;
4154
4155 result = PyBytes_FromStringAndSize(NULL, len);
4156 if ((result == NULL) || (len == 0))
4157 return result;
4158
4159 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4160 /* There should never be any short reads but check anyway. */
4161 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4162 Py_DECREF(result);
4163 return NULL;
4164 }
4165
4166 return result;
4167}
4168
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004169/*[clinic input]
4170_ssl.MemoryBIO.write
4171 b: Py_buffer
4172 /
4173
4174Writes the bytes b into the memory BIO.
4175
4176Returns the number of bytes written.
4177[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004178
4179static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004180_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4181/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004182{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183 int nbytes;
4184
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004185 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004186 PyErr_Format(PyExc_OverflowError,
4187 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004188 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004189 }
4190
4191 if (self->eof_written) {
4192 PyErr_SetString(PySSLErrorObject,
4193 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004194 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004195 }
4196
Segev Finer5cff6372017-07-27 01:19:17 +03004197 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004198 if (nbytes < 0) {
4199 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004200 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004201 }
4202
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004203 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004204}
4205
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004206/*[clinic input]
4207_ssl.MemoryBIO.write_eof
4208
4209Write an EOF marker to the memory BIO.
4210
4211When all data has been read, the "eof" property will be True.
4212[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004213
4214static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004215_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4216/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004217{
4218 self->eof_written = 1;
4219 /* After an EOF is written, a zero return from read() should be a real EOF
4220 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4221 BIO_clear_retry_flags(self->bio);
4222 BIO_set_mem_eof_return(self->bio, 0);
4223
4224 Py_RETURN_NONE;
4225}
4226
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004227static PyGetSetDef memory_bio_getsetlist[] = {
4228 {"pending", (getter) memory_bio_get_pending, NULL,
4229 PySSL_memory_bio_pending_doc},
4230 {"eof", (getter) memory_bio_get_eof, NULL,
4231 PySSL_memory_bio_eof_doc},
4232 {NULL}, /* sentinel */
4233};
4234
4235static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004236 _SSL_MEMORYBIO_READ_METHODDEF
4237 _SSL_MEMORYBIO_WRITE_METHODDEF
4238 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004239 {NULL, NULL} /* sentinel */
4240};
4241
4242static PyTypeObject PySSLMemoryBIO_Type = {
4243 PyVarObject_HEAD_INIT(NULL, 0)
4244 "_ssl.MemoryBIO", /*tp_name*/
4245 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4246 0, /*tp_itemsize*/
4247 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4248 0, /*tp_print*/
4249 0, /*tp_getattr*/
4250 0, /*tp_setattr*/
4251 0, /*tp_reserved*/
4252 0, /*tp_repr*/
4253 0, /*tp_as_number*/
4254 0, /*tp_as_sequence*/
4255 0, /*tp_as_mapping*/
4256 0, /*tp_hash*/
4257 0, /*tp_call*/
4258 0, /*tp_str*/
4259 0, /*tp_getattro*/
4260 0, /*tp_setattro*/
4261 0, /*tp_as_buffer*/
4262 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4263 0, /*tp_doc*/
4264 0, /*tp_traverse*/
4265 0, /*tp_clear*/
4266 0, /*tp_richcompare*/
4267 0, /*tp_weaklistoffset*/
4268 0, /*tp_iter*/
4269 0, /*tp_iternext*/
4270 memory_bio_methods, /*tp_methods*/
4271 0, /*tp_members*/
4272 memory_bio_getsetlist, /*tp_getset*/
4273 0, /*tp_base*/
4274 0, /*tp_dict*/
4275 0, /*tp_descr_get*/
4276 0, /*tp_descr_set*/
4277 0, /*tp_dictoffset*/
4278 0, /*tp_init*/
4279 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004280 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004281};
4282
Antoine Pitrou152efa22010-05-16 18:19:27 +00004283
Christian Heimes99a65702016-09-10 23:44:53 +02004284/*
4285 * SSL Session object
4286 */
4287
4288static void
4289PySSLSession_dealloc(PySSLSession *self)
4290{
INADA Naokia6296d32017-08-24 14:55:17 +09004291 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004292 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004293 Py_XDECREF(self->ctx);
4294 if (self->session != NULL) {
4295 SSL_SESSION_free(self->session);
4296 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004297 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004298}
4299
4300static PyObject *
4301PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4302{
4303 int result;
4304
4305 if (left == NULL || right == NULL) {
4306 PyErr_BadInternalCall();
4307 return NULL;
4308 }
4309
4310 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4311 Py_RETURN_NOTIMPLEMENTED;
4312 }
4313
4314 if (left == right) {
4315 result = 0;
4316 } else {
4317 const unsigned char *left_id, *right_id;
4318 unsigned int left_len, right_len;
4319 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4320 &left_len);
4321 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4322 &right_len);
4323 if (left_len == right_len) {
4324 result = memcmp(left_id, right_id, left_len);
4325 } else {
4326 result = 1;
4327 }
4328 }
4329
4330 switch (op) {
4331 case Py_EQ:
4332 if (result == 0) {
4333 Py_RETURN_TRUE;
4334 } else {
4335 Py_RETURN_FALSE;
4336 }
4337 break;
4338 case Py_NE:
4339 if (result != 0) {
4340 Py_RETURN_TRUE;
4341 } else {
4342 Py_RETURN_FALSE;
4343 }
4344 break;
4345 case Py_LT:
4346 case Py_LE:
4347 case Py_GT:
4348 case Py_GE:
4349 Py_RETURN_NOTIMPLEMENTED;
4350 break;
4351 default:
4352 PyErr_BadArgument();
4353 return NULL;
4354 }
4355}
4356
4357static int
4358PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4359{
4360 Py_VISIT(self->ctx);
4361 return 0;
4362}
4363
4364static int
4365PySSLSession_clear(PySSLSession *self)
4366{
4367 Py_CLEAR(self->ctx);
4368 return 0;
4369}
4370
4371
4372static PyObject *
4373PySSLSession_get_time(PySSLSession *self, void *closure) {
4374 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4375}
4376
4377PyDoc_STRVAR(PySSLSession_get_time_doc,
4378"Session creation time (seconds since epoch).");
4379
4380
4381static PyObject *
4382PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4383 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4384}
4385
4386PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4387"Session timeout (delta in seconds).");
4388
4389
4390static PyObject *
4391PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4392 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4393 return PyLong_FromUnsignedLong(hint);
4394}
4395
4396PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4397"Ticket life time hint.");
4398
4399
4400static PyObject *
4401PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4402 const unsigned char *id;
4403 unsigned int len;
4404 id = SSL_SESSION_get_id(self->session, &len);
4405 return PyBytes_FromStringAndSize((const char *)id, len);
4406}
4407
4408PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4409"Session id");
4410
4411
4412static PyObject *
4413PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4414 if (SSL_SESSION_has_ticket(self->session)) {
4415 Py_RETURN_TRUE;
4416 } else {
4417 Py_RETURN_FALSE;
4418 }
4419}
4420
4421PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4422"Does the session contain a ticket?");
4423
4424
4425static PyGetSetDef PySSLSession_getsetlist[] = {
4426 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4427 PySSLSession_get_has_ticket_doc},
4428 {"id", (getter) PySSLSession_get_session_id, NULL,
4429 PySSLSession_get_session_id_doc},
4430 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4431 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4432 {"time", (getter) PySSLSession_get_time, NULL,
4433 PySSLSession_get_time_doc},
4434 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4435 PySSLSession_get_timeout_doc},
4436 {NULL}, /* sentinel */
4437};
4438
4439static PyTypeObject PySSLSession_Type = {
4440 PyVarObject_HEAD_INIT(NULL, 0)
4441 "_ssl.Session", /*tp_name*/
4442 sizeof(PySSLSession), /*tp_basicsize*/
4443 0, /*tp_itemsize*/
4444 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4445 0, /*tp_print*/
4446 0, /*tp_getattr*/
4447 0, /*tp_setattr*/
4448 0, /*tp_reserved*/
4449 0, /*tp_repr*/
4450 0, /*tp_as_number*/
4451 0, /*tp_as_sequence*/
4452 0, /*tp_as_mapping*/
4453 0, /*tp_hash*/
4454 0, /*tp_call*/
4455 0, /*tp_str*/
4456 0, /*tp_getattro*/
4457 0, /*tp_setattro*/
4458 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004459 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004460 0, /*tp_doc*/
4461 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4462 (inquiry)PySSLSession_clear, /*tp_clear*/
4463 PySSLSession_richcompare, /*tp_richcompare*/
4464 0, /*tp_weaklistoffset*/
4465 0, /*tp_iter*/
4466 0, /*tp_iternext*/
4467 0, /*tp_methods*/
4468 0, /*tp_members*/
4469 PySSLSession_getsetlist, /*tp_getset*/
4470};
4471
4472
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004473/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004474/*[clinic input]
4475_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004476 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004477 entropy: double
4478 /
4479
4480Mix string into the OpenSSL PRNG state.
4481
4482entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304483string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004484[clinic start generated code]*/
4485
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004486static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004487_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004488/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004489{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004490 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004491 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004492
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004493 buf = (const char *)view->buf;
4494 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004495 do {
4496 written = Py_MIN(len, INT_MAX);
4497 RAND_add(buf, (int)written, entropy);
4498 buf += written;
4499 len -= written;
4500 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004501 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004502}
4503
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004504static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004505PySSL_RAND(int len, int pseudo)
4506{
4507 int ok;
4508 PyObject *bytes;
4509 unsigned long err;
4510 const char *errstr;
4511 PyObject *v;
4512
Victor Stinner1e81a392013-12-19 16:47:04 +01004513 if (len < 0) {
4514 PyErr_SetString(PyExc_ValueError, "num must be positive");
4515 return NULL;
4516 }
4517
Victor Stinner99c8b162011-05-24 12:05:19 +02004518 bytes = PyBytes_FromStringAndSize(NULL, len);
4519 if (bytes == NULL)
4520 return NULL;
4521 if (pseudo) {
4522 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4523 if (ok == 0 || ok == 1)
4524 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4525 }
4526 else {
4527 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4528 if (ok == 1)
4529 return bytes;
4530 }
4531 Py_DECREF(bytes);
4532
4533 err = ERR_get_error();
4534 errstr = ERR_reason_error_string(err);
4535 v = Py_BuildValue("(ks)", err, errstr);
4536 if (v != NULL) {
4537 PyErr_SetObject(PySSLErrorObject, v);
4538 Py_DECREF(v);
4539 }
4540 return NULL;
4541}
4542
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004543/*[clinic input]
4544_ssl.RAND_bytes
4545 n: int
4546 /
4547
4548Generate n cryptographically strong pseudo-random bytes.
4549[clinic start generated code]*/
4550
Victor Stinner99c8b162011-05-24 12:05:19 +02004551static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004552_ssl_RAND_bytes_impl(PyObject *module, int n)
4553/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004554{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004555 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004556}
4557
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004558/*[clinic input]
4559_ssl.RAND_pseudo_bytes
4560 n: int
4561 /
4562
4563Generate n pseudo-random bytes.
4564
4565Return a pair (bytes, is_cryptographic). is_cryptographic is True
4566if the bytes generated are cryptographically strong.
4567[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004568
4569static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004570_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4571/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004572{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004573 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004574}
4575
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004576/*[clinic input]
4577_ssl.RAND_status
4578
4579Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4580
4581It is necessary to seed the PRNG with RAND_add() on some platforms before
4582using the ssl() function.
4583[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004584
4585static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004586_ssl_RAND_status_impl(PyObject *module)
4587/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004588{
Christian Heimes217cfd12007-12-02 14:31:20 +00004589 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004590}
4591
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004592#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004593/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004594/*[clinic input]
4595_ssl.RAND_egd
4596 path: object(converter="PyUnicode_FSConverter")
4597 /
4598
4599Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4600
4601Returns number of bytes read. Raises SSLError if connection to EGD
4602fails or if it does not provide enough data to seed PRNG.
4603[clinic start generated code]*/
4604
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004605static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004606_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4607/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004608{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004609 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004610 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004611 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004612 PyErr_SetString(PySSLErrorObject,
4613 "EGD connection failed or EGD did not return "
4614 "enough data to seed the PRNG");
4615 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004616 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004617 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004618}
Christian Heimesa5d07652016-09-24 10:48:05 +02004619/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004620#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004621
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004622
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004623
4624/*[clinic input]
4625_ssl.get_default_verify_paths
4626
4627Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4628
4629The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4630[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004631
4632static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004633_ssl_get_default_verify_paths_impl(PyObject *module)
4634/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004635{
4636 PyObject *ofile_env = NULL;
4637 PyObject *ofile = NULL;
4638 PyObject *odir_env = NULL;
4639 PyObject *odir = NULL;
4640
Benjamin Petersond113c962015-07-18 10:59:13 -07004641#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004642 const char *tmp = (info); \
4643 target = NULL; \
4644 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4645 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4646 target = PyBytes_FromString(tmp); } \
4647 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004648 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004649
Benjamin Petersond113c962015-07-18 10:59:13 -07004650 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4651 CONVERT(X509_get_default_cert_file(), ofile);
4652 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4653 CONVERT(X509_get_default_cert_dir(), odir);
4654#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004655
Christian Heimes200bb1b2013-06-14 15:14:29 +02004656 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004657
4658 error:
4659 Py_XDECREF(ofile_env);
4660 Py_XDECREF(ofile);
4661 Py_XDECREF(odir_env);
4662 Py_XDECREF(odir);
4663 return NULL;
4664}
4665
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004666static PyObject*
4667asn1obj2py(ASN1_OBJECT *obj)
4668{
4669 int nid;
4670 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004671
4672 nid = OBJ_obj2nid(obj);
4673 if (nid == NID_undef) {
4674 PyErr_Format(PyExc_ValueError, "Unknown object");
4675 return NULL;
4676 }
4677 sn = OBJ_nid2sn(nid);
4678 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004679 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004680}
4681
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004682/*[clinic input]
4683_ssl.txt2obj
4684 txt: str
4685 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004686
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004687Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4688
4689By default objects are looked up by OID. With name=True short and
4690long name are also matched.
4691[clinic start generated code]*/
4692
4693static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004694_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4695/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004696{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004697 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004698 ASN1_OBJECT *obj;
4699
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004700 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4701 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004702 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004703 return NULL;
4704 }
4705 result = asn1obj2py(obj);
4706 ASN1_OBJECT_free(obj);
4707 return result;
4708}
4709
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004710/*[clinic input]
4711_ssl.nid2obj
4712 nid: int
4713 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004714
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004715Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4716[clinic start generated code]*/
4717
4718static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004719_ssl_nid2obj_impl(PyObject *module, int nid)
4720/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004721{
4722 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004723 ASN1_OBJECT *obj;
4724
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004725 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004726 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004727 return NULL;
4728 }
4729 obj = OBJ_nid2obj(nid);
4730 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004731 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004732 return NULL;
4733 }
4734 result = asn1obj2py(obj);
4735 ASN1_OBJECT_free(obj);
4736 return result;
4737}
4738
Christian Heimes46bebee2013-06-09 19:03:31 +02004739#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004740
4741static PyObject*
4742certEncodingType(DWORD encodingType)
4743{
4744 static PyObject *x509_asn = NULL;
4745 static PyObject *pkcs_7_asn = NULL;
4746
4747 if (x509_asn == NULL) {
4748 x509_asn = PyUnicode_InternFromString("x509_asn");
4749 if (x509_asn == NULL)
4750 return NULL;
4751 }
4752 if (pkcs_7_asn == NULL) {
4753 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4754 if (pkcs_7_asn == NULL)
4755 return NULL;
4756 }
4757 switch(encodingType) {
4758 case X509_ASN_ENCODING:
4759 Py_INCREF(x509_asn);
4760 return x509_asn;
4761 case PKCS_7_ASN_ENCODING:
4762 Py_INCREF(pkcs_7_asn);
4763 return pkcs_7_asn;
4764 default:
4765 return PyLong_FromLong(encodingType);
4766 }
4767}
4768
4769static PyObject*
4770parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4771{
4772 CERT_ENHKEY_USAGE *usage;
4773 DWORD size, error, i;
4774 PyObject *retval;
4775
4776 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4777 error = GetLastError();
4778 if (error == CRYPT_E_NOT_FOUND) {
4779 Py_RETURN_TRUE;
4780 }
4781 return PyErr_SetFromWindowsErr(error);
4782 }
4783
4784 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4785 if (usage == NULL) {
4786 return PyErr_NoMemory();
4787 }
4788
4789 /* Now get the actual enhanced usage property */
4790 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4791 PyMem_Free(usage);
4792 error = GetLastError();
4793 if (error == CRYPT_E_NOT_FOUND) {
4794 Py_RETURN_TRUE;
4795 }
4796 return PyErr_SetFromWindowsErr(error);
4797 }
4798 retval = PySet_New(NULL);
4799 if (retval == NULL) {
4800 goto error;
4801 }
4802 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4803 if (usage->rgpszUsageIdentifier[i]) {
4804 PyObject *oid;
4805 int err;
4806 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4807 if (oid == NULL) {
4808 Py_CLEAR(retval);
4809 goto error;
4810 }
4811 err = PySet_Add(retval, oid);
4812 Py_DECREF(oid);
4813 if (err == -1) {
4814 Py_CLEAR(retval);
4815 goto error;
4816 }
4817 }
4818 }
4819 error:
4820 PyMem_Free(usage);
4821 return retval;
4822}
4823
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004824/*[clinic input]
4825_ssl.enum_certificates
4826 store_name: str
4827
4828Retrieve certificates from Windows' cert store.
4829
4830store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4831more cert storages, too. The function returns a list of (bytes,
4832encoding_type, trust) tuples. The encoding_type flag can be interpreted
4833with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4834a set of OIDs or the boolean True.
4835[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004836
Christian Heimes46bebee2013-06-09 19:03:31 +02004837static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004838_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4839/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004840{
Christian Heimes46bebee2013-06-09 19:03:31 +02004841 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004842 PCCERT_CONTEXT pCertCtx = NULL;
4843 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004844 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004845
Christian Heimes44109d72013-11-22 01:51:30 +01004846 result = PyList_New(0);
4847 if (result == NULL) {
4848 return NULL;
4849 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004850 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4851 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4852 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004853 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004854 Py_DECREF(result);
4855 return PyErr_SetFromWindowsErr(GetLastError());
4856 }
4857
Christian Heimes44109d72013-11-22 01:51:30 +01004858 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4859 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4860 pCertCtx->cbCertEncoded);
4861 if (!cert) {
4862 Py_CLEAR(result);
4863 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004864 }
Christian Heimes44109d72013-11-22 01:51:30 +01004865 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4866 Py_CLEAR(result);
4867 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004868 }
Christian Heimes44109d72013-11-22 01:51:30 +01004869 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4870 if (keyusage == Py_True) {
4871 Py_DECREF(keyusage);
4872 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004873 }
Christian Heimes44109d72013-11-22 01:51:30 +01004874 if (keyusage == NULL) {
4875 Py_CLEAR(result);
4876 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004877 }
Christian Heimes44109d72013-11-22 01:51:30 +01004878 if ((tup = PyTuple_New(3)) == NULL) {
4879 Py_CLEAR(result);
4880 break;
4881 }
4882 PyTuple_SET_ITEM(tup, 0, cert);
4883 cert = NULL;
4884 PyTuple_SET_ITEM(tup, 1, enc);
4885 enc = NULL;
4886 PyTuple_SET_ITEM(tup, 2, keyusage);
4887 keyusage = NULL;
4888 if (PyList_Append(result, tup) < 0) {
4889 Py_CLEAR(result);
4890 break;
4891 }
4892 Py_CLEAR(tup);
4893 }
4894 if (pCertCtx) {
4895 /* loop ended with an error, need to clean up context manually */
4896 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02004897 }
4898
4899 /* In error cases cert, enc and tup may not be NULL */
4900 Py_XDECREF(cert);
4901 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01004902 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02004903 Py_XDECREF(tup);
4904
4905 if (!CertCloseStore(hStore, 0)) {
4906 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01004907 Py_XDECREF(result);
4908 return PyErr_SetFromWindowsErr(GetLastError());
4909 }
4910 return result;
4911}
4912
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004913/*[clinic input]
4914_ssl.enum_crls
4915 store_name: str
4916
4917Retrieve CRLs from Windows' cert store.
4918
4919store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4920more cert storages, too. The function returns a list of (bytes,
4921encoding_type) tuples. The encoding_type flag can be interpreted with
4922X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
4923[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004924
4925static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004926_ssl_enum_crls_impl(PyObject *module, const char *store_name)
4927/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01004928{
Christian Heimes44109d72013-11-22 01:51:30 +01004929 HCERTSTORE hStore = NULL;
4930 PCCRL_CONTEXT pCrlCtx = NULL;
4931 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
4932 PyObject *result = NULL;
4933
Christian Heimes44109d72013-11-22 01:51:30 +01004934 result = PyList_New(0);
4935 if (result == NULL) {
4936 return NULL;
4937 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004938 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4939 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4940 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004941 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004942 Py_DECREF(result);
4943 return PyErr_SetFromWindowsErr(GetLastError());
4944 }
Christian Heimes44109d72013-11-22 01:51:30 +01004945
4946 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
4947 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
4948 pCrlCtx->cbCrlEncoded);
4949 if (!crl) {
4950 Py_CLEAR(result);
4951 break;
4952 }
4953 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
4954 Py_CLEAR(result);
4955 break;
4956 }
4957 if ((tup = PyTuple_New(2)) == NULL) {
4958 Py_CLEAR(result);
4959 break;
4960 }
4961 PyTuple_SET_ITEM(tup, 0, crl);
4962 crl = NULL;
4963 PyTuple_SET_ITEM(tup, 1, enc);
4964 enc = NULL;
4965
4966 if (PyList_Append(result, tup) < 0) {
4967 Py_CLEAR(result);
4968 break;
4969 }
4970 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02004971 }
Christian Heimes44109d72013-11-22 01:51:30 +01004972 if (pCrlCtx) {
4973 /* loop ended with an error, need to clean up context manually */
4974 CertFreeCRLContext(pCrlCtx);
4975 }
4976
4977 /* In error cases cert, enc and tup may not be NULL */
4978 Py_XDECREF(crl);
4979 Py_XDECREF(enc);
4980 Py_XDECREF(tup);
4981
4982 if (!CertCloseStore(hStore, 0)) {
4983 /* This error case might shadow another exception.*/
4984 Py_XDECREF(result);
4985 return PyErr_SetFromWindowsErr(GetLastError());
4986 }
4987 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02004988}
Christian Heimes44109d72013-11-22 01:51:30 +01004989
4990#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00004991
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004992/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004993static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004994 _SSL__TEST_DECODE_CERT_METHODDEF
4995 _SSL_RAND_ADD_METHODDEF
4996 _SSL_RAND_BYTES_METHODDEF
4997 _SSL_RAND_PSEUDO_BYTES_METHODDEF
4998 _SSL_RAND_EGD_METHODDEF
4999 _SSL_RAND_STATUS_METHODDEF
5000 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5001 _SSL_ENUM_CERTIFICATES_METHODDEF
5002 _SSL_ENUM_CRLS_METHODDEF
5003 _SSL_TXT2OBJ_METHODDEF
5004 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005005 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005006};
5007
5008
Christian Heimes598894f2016-09-05 23:19:05 +02005009#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005010
5011/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005012 * of the Python C thread library
5013 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5014 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005015
5016static PyThread_type_lock *_ssl_locks = NULL;
5017
Christian Heimes4d98ca92013-08-19 17:36:29 +02005018#if OPENSSL_VERSION_NUMBER >= 0x10000000
5019/* use new CRYPTO_THREADID API. */
5020static void
5021_ssl_threadid_callback(CRYPTO_THREADID *id)
5022{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005023 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005024}
5025#else
5026/* deprecated CRYPTO_set_id_callback() API. */
5027static unsigned long
5028_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005029 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005030}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005031#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005032
Bill Janssen6e027db2007-11-15 22:23:56 +00005033static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005034 (int mode, int n, const char *file, int line) {
5035 /* this function is needed to perform locking on shared data
5036 structures. (Note that OpenSSL uses a number of global data
5037 structures that will be implicitly shared whenever multiple
5038 threads use OpenSSL.) Multi-threaded applications will
5039 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005040
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005041 locking_function() must be able to handle up to
5042 CRYPTO_num_locks() different mutex locks. It sets the n-th
5043 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005044
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005045 file and line are the file number of the function setting the
5046 lock. They can be useful for debugging.
5047 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005048
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005049 if ((_ssl_locks == NULL) ||
5050 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5051 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005052
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005053 if (mode & CRYPTO_LOCK) {
5054 PyThread_acquire_lock(_ssl_locks[n], 1);
5055 } else {
5056 PyThread_release_lock(_ssl_locks[n]);
5057 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005058}
5059
5060static int _setup_ssl_threads(void) {
5061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005062 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005063
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005064 if (_ssl_locks == NULL) {
5065 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005066 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5067 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005068 if (_ssl_locks == NULL) {
5069 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005070 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005071 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005072 for (i = 0; i < _ssl_locks_count; i++) {
5073 _ssl_locks[i] = PyThread_allocate_lock();
5074 if (_ssl_locks[i] == NULL) {
5075 unsigned int j;
5076 for (j = 0; j < i; j++) {
5077 PyThread_free_lock(_ssl_locks[j]);
5078 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005079 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005080 return 0;
5081 }
5082 }
5083 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005084#if OPENSSL_VERSION_NUMBER >= 0x10000000
5085 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5086#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005087 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005088#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005089 }
5090 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005091}
5092
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005093#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005094
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005095PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005096"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005097for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005098
Martin v. Löwis1a214512008-06-11 05:26:20 +00005099
5100static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005101 PyModuleDef_HEAD_INIT,
5102 "_ssl",
5103 module_doc,
5104 -1,
5105 PySSL_methods,
5106 NULL,
5107 NULL,
5108 NULL,
5109 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005110};
5111
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005112
5113static void
5114parse_openssl_version(unsigned long libver,
5115 unsigned int *major, unsigned int *minor,
5116 unsigned int *fix, unsigned int *patch,
5117 unsigned int *status)
5118{
5119 *status = libver & 0xF;
5120 libver >>= 4;
5121 *patch = libver & 0xFF;
5122 libver >>= 8;
5123 *fix = libver & 0xFF;
5124 libver >>= 8;
5125 *minor = libver & 0xFF;
5126 libver >>= 8;
5127 *major = libver & 0xFF;
5128}
5129
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005130PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005131PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005132{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005133 PyObject *m, *d, *r;
5134 unsigned long libver;
5135 unsigned int major, minor, fix, patch, status;
5136 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005137 struct py_ssl_error_code *errcode;
5138 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005139
Antoine Pitrou152efa22010-05-16 18:19:27 +00005140 if (PyType_Ready(&PySSLContext_Type) < 0)
5141 return NULL;
5142 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005143 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005144 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5145 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005146 if (PyType_Ready(&PySSLSession_Type) < 0)
5147 return NULL;
5148
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005149
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005150 m = PyModule_Create(&_sslmodule);
5151 if (m == NULL)
5152 return NULL;
5153 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005155 /* Load _socket module and its C API */
5156 socket_api = PySocketModule_ImportModuleAndAPI();
5157 if (!socket_api)
5158 return NULL;
5159 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005160
Christian Heimesc941e622017-09-05 15:47:11 +02005161#ifndef OPENSSL_VERSION_1_1
5162 /* Load all algorithms and initialize cpuid */
5163 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005164 /* Init OpenSSL */
5165 SSL_load_error_strings();
5166 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005167#endif
5168
Christian Heimes598894f2016-09-05 23:19:05 +02005169#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005170 /* note that this will start threading if not already started */
5171 if (!_setup_ssl_threads()) {
5172 return NULL;
5173 }
Christian Heimes598894f2016-09-05 23:19:05 +02005174#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5175 /* OpenSSL 1.1.0 builtin thread support is enabled */
5176 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005177#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005178
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005179 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005180 sslerror_type_slots[0].pfunc = PyExc_OSError;
5181 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005182 if (PySSLErrorObject == NULL)
5183 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005184
Antoine Pitrou41032a62011-10-27 23:56:55 +02005185 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5186 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5187 PySSLErrorObject, NULL);
5188 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5189 "ssl.SSLWantReadError", SSLWantReadError_doc,
5190 PySSLErrorObject, NULL);
5191 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5192 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5193 PySSLErrorObject, NULL);
5194 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5195 "ssl.SSLSyscallError", SSLSyscallError_doc,
5196 PySSLErrorObject, NULL);
5197 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5198 "ssl.SSLEOFError", SSLEOFError_doc,
5199 PySSLErrorObject, NULL);
5200 if (PySSLZeroReturnErrorObject == NULL
5201 || PySSLWantReadErrorObject == NULL
5202 || PySSLWantWriteErrorObject == NULL
5203 || PySSLSyscallErrorObject == NULL
5204 || PySSLEOFErrorObject == NULL)
5205 return NULL;
5206 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
5207 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5208 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5209 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5210 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5211 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005212 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005213 if (PyDict_SetItemString(d, "_SSLContext",
5214 (PyObject *)&PySSLContext_Type) != 0)
5215 return NULL;
5216 if (PyDict_SetItemString(d, "_SSLSocket",
5217 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005218 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005219 if (PyDict_SetItemString(d, "MemoryBIO",
5220 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5221 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005222 if (PyDict_SetItemString(d, "SSLSession",
5223 (PyObject *)&PySSLSession_Type) != 0)
5224 return NULL;
5225
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005226 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5227 PY_SSL_ERROR_ZERO_RETURN);
5228 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5229 PY_SSL_ERROR_WANT_READ);
5230 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5231 PY_SSL_ERROR_WANT_WRITE);
5232 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5233 PY_SSL_ERROR_WANT_X509_LOOKUP);
5234 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5235 PY_SSL_ERROR_SYSCALL);
5236 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5237 PY_SSL_ERROR_SSL);
5238 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5239 PY_SSL_ERROR_WANT_CONNECT);
5240 /* non ssl.h errorcodes */
5241 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5242 PY_SSL_ERROR_EOF);
5243 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5244 PY_SSL_ERROR_INVALID_ERROR_CODE);
5245 /* cert requirements */
5246 PyModule_AddIntConstant(m, "CERT_NONE",
5247 PY_SSL_CERT_NONE);
5248 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5249 PY_SSL_CERT_OPTIONAL);
5250 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5251 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005252 /* CRL verification for verification_flags */
5253 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5254 0);
5255 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5256 X509_V_FLAG_CRL_CHECK);
5257 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5258 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5259 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5260 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005261#ifdef X509_V_FLAG_TRUSTED_FIRST
5262 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5263 X509_V_FLAG_TRUSTED_FIRST);
5264#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005265
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005266 /* Alert Descriptions from ssl.h */
5267 /* note RESERVED constants no longer intended for use have been removed */
5268 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5269
5270#define ADD_AD_CONSTANT(s) \
5271 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5272 SSL_AD_##s)
5273
5274 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5275 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5276 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5277 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5278 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5279 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5280 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5281 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5282 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5283 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5284 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5285 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5286 ADD_AD_CONSTANT(UNKNOWN_CA);
5287 ADD_AD_CONSTANT(ACCESS_DENIED);
5288 ADD_AD_CONSTANT(DECODE_ERROR);
5289 ADD_AD_CONSTANT(DECRYPT_ERROR);
5290 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5291 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5292 ADD_AD_CONSTANT(INTERNAL_ERROR);
5293 ADD_AD_CONSTANT(USER_CANCELLED);
5294 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005295 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005296#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5297 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5298#endif
5299#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5300 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5301#endif
5302#ifdef SSL_AD_UNRECOGNIZED_NAME
5303 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5304#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005305#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5306 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5307#endif
5308#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5309 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5310#endif
5311#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5312 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5313#endif
5314
5315#undef ADD_AD_CONSTANT
5316
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005317 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005318#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005319 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5320 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005321#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005322#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005323 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5324 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005325#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005326 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005327 PY_SSL_VERSION_TLS);
5328 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5329 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005330 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5331 PY_SSL_VERSION_TLS_CLIENT);
5332 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5333 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005334 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5335 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005336#if HAVE_TLSv1_2
5337 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5338 PY_SSL_VERSION_TLS1_1);
5339 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5340 PY_SSL_VERSION_TLS1_2);
5341#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005342
Antoine Pitroub5218772010-05-21 09:56:06 +00005343 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005344 PyModule_AddIntConstant(m, "OP_ALL",
5345 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005346 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5347 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5348 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005349#if HAVE_TLSv1_2
5350 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5351 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5352#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005353 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5354 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005355 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005356 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005357#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005358 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005359#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005360#ifdef SSL_OP_NO_COMPRESSION
5361 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5362 SSL_OP_NO_COMPRESSION);
5363#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005364
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005365#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005366 r = Py_True;
5367#else
5368 r = Py_False;
5369#endif
5370 Py_INCREF(r);
5371 PyModule_AddObject(m, "HAS_SNI", r);
5372
Antoine Pitroud6494802011-07-21 01:11:30 +02005373 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005374 Py_INCREF(r);
5375 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5376
Antoine Pitrou501da612011-12-21 09:27:41 +01005377#ifdef OPENSSL_NO_ECDH
5378 r = Py_False;
5379#else
5380 r = Py_True;
5381#endif
5382 Py_INCREF(r);
5383 PyModule_AddObject(m, "HAS_ECDH", r);
5384
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005385#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005386 r = Py_True;
5387#else
5388 r = Py_False;
5389#endif
5390 Py_INCREF(r);
5391 PyModule_AddObject(m, "HAS_NPN", r);
5392
Benjamin Petersoncca27322015-01-23 16:35:37 -05005393#ifdef HAVE_ALPN
5394 r = Py_True;
5395#else
5396 r = Py_False;
5397#endif
5398 Py_INCREF(r);
5399 PyModule_AddObject(m, "HAS_ALPN", r);
5400
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005401 /* Mappings for error codes */
5402 err_codes_to_names = PyDict_New();
5403 err_names_to_codes = PyDict_New();
5404 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5405 return NULL;
5406 errcode = error_codes;
5407 while (errcode->mnemonic != NULL) {
5408 PyObject *mnemo, *key;
5409 mnemo = PyUnicode_FromString(errcode->mnemonic);
5410 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5411 if (mnemo == NULL || key == NULL)
5412 return NULL;
5413 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5414 return NULL;
5415 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5416 return NULL;
5417 Py_DECREF(key);
5418 Py_DECREF(mnemo);
5419 errcode++;
5420 }
5421 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5422 return NULL;
5423 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5424 return NULL;
5425
5426 lib_codes_to_names = PyDict_New();
5427 if (lib_codes_to_names == NULL)
5428 return NULL;
5429 libcode = library_codes;
5430 while (libcode->library != NULL) {
5431 PyObject *mnemo, *key;
5432 key = PyLong_FromLong(libcode->code);
5433 mnemo = PyUnicode_FromString(libcode->library);
5434 if (key == NULL || mnemo == NULL)
5435 return NULL;
5436 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5437 return NULL;
5438 Py_DECREF(key);
5439 Py_DECREF(mnemo);
5440 libcode++;
5441 }
5442 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5443 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005445 /* OpenSSL version */
5446 /* SSLeay() gives us the version of the library linked against,
5447 which could be different from the headers version.
5448 */
5449 libver = SSLeay();
5450 r = PyLong_FromUnsignedLong(libver);
5451 if (r == NULL)
5452 return NULL;
5453 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5454 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005455 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005456 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5457 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5458 return NULL;
5459 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5460 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5461 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005462
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005463 libver = OPENSSL_VERSION_NUMBER;
5464 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5465 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5466 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5467 return NULL;
5468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005469 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005470}