blob: c5eec7eded6292bd7ccfd2de3f5c0213926df21b [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
Christian Heimesff5be6e2018-01-20 13:19:21 +010067/* Set HAVE_X509_VERIFY_PARAM_SET1_HOST for non-autoconf builds */
68#ifndef HAVE_X509_VERIFY_PARAM_SET1_HOST
69# if !defined(LIBRESSL_VERSION_NUMBER) && OPENSSL_VERSION_NUMBER > 0x1000200fL
70# define HAVE_X509_VERIFY_PARAM_SET1_HOST
71# endif
72#endif
73
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010074/* SSL error object */
75static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070076static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010077static PyObject *PySSLZeroReturnErrorObject;
78static PyObject *PySSLWantReadErrorObject;
79static PyObject *PySSLWantWriteErrorObject;
80static PyObject *PySSLSyscallErrorObject;
81static PyObject *PySSLEOFErrorObject;
82
83/* Error mappings */
84static PyObject *err_codes_to_names;
85static PyObject *err_names_to_codes;
86static PyObject *lib_codes_to_names;
87
88struct py_ssl_error_code {
89 const char *mnemonic;
90 int library, reason;
91};
92struct py_ssl_library_code {
93 const char *library;
94 int code;
95};
96
Steve Dower68d663c2017-07-17 11:15:48 +020097#if defined(MS_WINDOWS) && defined(Py_DEBUG)
98/* Debug builds on Windows rely on getting errno directly from OpenSSL.
99 * However, because it uses a different CRT, we need to transfer the
100 * value of errno from OpenSSL into our debug CRT.
101 *
102 * Don't be fooled - this is horribly ugly code. The only reasonable
103 * alternative is to do both debug and release builds of OpenSSL, which
104 * requires much uglier code to transform their automatically generated
105 * makefile. This is the lesser of all the evils.
106 */
107
108static void _PySSLFixErrno(void) {
109 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
110 if (!ucrtbase) {
111 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
112 * have a catastrophic failure, but this function is not the
113 * place to raise it. */
114 return;
115 }
116
117 typedef int *(__stdcall *errno_func)(void);
118 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
119 if (ssl_errno) {
120 errno = *ssl_errno();
121 *ssl_errno() = 0;
122 } else {
123 errno = ENOTRECOVERABLE;
124 }
125}
126
127#undef _PySSL_FIX_ERRNO
128#define _PySSL_FIX_ERRNO _PySSLFixErrno()
129#endif
130
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100131/* Include generated data (error codes) */
132#include "_ssl_data.h"
133
Christian Heimes598894f2016-09-05 23:19:05 +0200134#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
135# define OPENSSL_VERSION_1_1 1
136#endif
137
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100138/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
139 http://www.openssl.org/news/changelog.html
140 */
141#if OPENSSL_VERSION_NUMBER >= 0x10001000L
142# define HAVE_TLSv1_2 1
143#else
144# define HAVE_TLSv1_2 0
145#endif
146
Christian Heimes470fba12013-11-28 15:12:15 +0100147/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100148 * This includes the SSL_set_SSL_CTX() function.
149 */
150#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
151# define HAVE_SNI 1
152#else
153# define HAVE_SNI 0
154#endif
155
Benjamin Petersond3308222015-09-27 00:09:02 -0700156#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500157# define HAVE_ALPN
158#endif
159
Victor Stinner524714e2016-07-22 17:43:59 +0200160#ifndef INVALID_SOCKET /* MS defines this */
161#define INVALID_SOCKET (-1)
162#endif
163
Christian Heimes598894f2016-09-05 23:19:05 +0200164#ifdef OPENSSL_VERSION_1_1
165/* OpenSSL 1.1.0+ */
166#ifndef OPENSSL_NO_SSL2
167#define OPENSSL_NO_SSL2
168#endif
169#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200170#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200171
172#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200173#define TLS_client_method SSLv23_client_method
174#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200175
176static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
177{
178 return ne->set;
179}
180
181#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200182/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200183static int COMP_get_type(const COMP_METHOD *meth)
184{
185 return meth->type;
186}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200187/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200188#endif
189
190static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
191{
192 return ctx->default_passwd_callback;
193}
194
195static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
196{
197 return ctx->default_passwd_callback_userdata;
198}
199
200static int X509_OBJECT_get_type(X509_OBJECT *x)
201{
202 return x->type;
203}
204
205static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
206{
207 return x->data.x509;
208}
209
210static int BIO_up_ref(BIO *b)
211{
212 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
213 return 1;
214}
215
216static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
217 return store->objs;
218}
219
220static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
221{
222 return store->param;
223}
Christian Heimes99a65702016-09-10 23:44:53 +0200224
225static int
226SSL_SESSION_has_ticket(const SSL_SESSION *s)
227{
228 return (s->tlsext_ticklen > 0) ? 1 : 0;
229}
230
231static unsigned long
232SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
233{
234 return s->tlsext_tick_lifetime_hint;
235}
236
Christian Heimes598894f2016-09-05 23:19:05 +0200237#endif /* OpenSSL < 1.1.0 or LibreSSL */
238
239
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000240enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000241 /* these mirror ssl.h */
242 PY_SSL_ERROR_NONE,
243 PY_SSL_ERROR_SSL,
244 PY_SSL_ERROR_WANT_READ,
245 PY_SSL_ERROR_WANT_WRITE,
246 PY_SSL_ERROR_WANT_X509_LOOKUP,
247 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
248 PY_SSL_ERROR_ZERO_RETURN,
249 PY_SSL_ERROR_WANT_CONNECT,
250 /* start of non ssl.h errorcodes */
251 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
252 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
253 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000254};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000255
Thomas Woutersed03b412007-08-28 21:37:11 +0000256enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000257 PY_SSL_CLIENT,
258 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000259};
260
261enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000262 PY_SSL_CERT_NONE,
263 PY_SSL_CERT_OPTIONAL,
264 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000265};
266
267enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000268 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200269 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200270 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100271#if HAVE_TLSv1_2
272 PY_SSL_VERSION_TLS1,
273 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200274 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100275#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200276 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000277#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200278 PY_SSL_VERSION_TLS_CLIENT=0x10,
279 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100280};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200281
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000282/* serves as a flag to see whether we've initialized the SSL thread support. */
283/* 0 means no, greater than 0 means yes */
284
285static unsigned int _ssl_locks_count = 0;
286
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000287/* SSL socket object */
288
289#define X509_NAME_MAXLEN 256
290
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000291/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
292 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
293 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
294#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000295# define HAVE_SSL_CTX_CLEAR_OPTIONS
296#else
297# undef HAVE_SSL_CTX_CLEAR_OPTIONS
298#endif
299
Antoine Pitroud6494802011-07-21 01:11:30 +0200300/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
301 * older SSL, but let's be safe */
302#define PySSL_CB_MAXLEN 128
303
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100304
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000305typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000306 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000307 SSL_CTX *ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +0200308#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500309 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100310 int npn_protocols_len;
311#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500312#ifdef HAVE_ALPN
313 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300314 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500315#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100316#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200317 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100318#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100319 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000320} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000321
Antoine Pitrou152efa22010-05-16 18:19:27 +0000322typedef struct {
323 PyObject_HEAD
324 PyObject *Socket; /* weakref to socket on which we're layered */
325 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100326 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200327 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200328 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200329 PyObject *owner; /* Python level "owner" passed to servername callback */
330 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700331 int ssl_errno; /* last seen error from SSL */
332 int c_errno; /* last seen error from libc */
333#ifdef MS_WINDOWS
334 int ws_errno; /* last seen error from winsock */
335#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000336} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000337
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200338typedef struct {
339 PyObject_HEAD
340 BIO *bio;
341 int eof_written;
342} PySSLMemoryBIO;
343
Christian Heimes99a65702016-09-10 23:44:53 +0200344typedef struct {
345 PyObject_HEAD
346 SSL_SESSION *session;
347 PySSLContext *ctx;
348} PySSLSession;
349
Antoine Pitrou152efa22010-05-16 18:19:27 +0000350static PyTypeObject PySSLContext_Type;
351static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200352static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200353static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000354
Steve Dowere6eb48c2017-09-08 15:16:15 -0700355#ifdef MS_WINDOWS
356#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
357 (sock)->ws_errno = WSAGetLastError(); \
358 _PySSL_FIX_ERRNO; \
359 (sock)->c_errno = errno; \
360 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
361 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
362#else
363#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
364 (sock)->c_errno = errno; \
365 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
366 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
367#endif
368#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
369
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300370/*[clinic input]
371module _ssl
372class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
373class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
374class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200375class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300376[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200377/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300378
379#include "clinic/_ssl.c.h"
380
Victor Stinner14690702015-04-06 22:46:13 +0200381static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000382
Christian Heimes99a65702016-09-10 23:44:53 +0200383
Antoine Pitrou152efa22010-05-16 18:19:27 +0000384#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
385#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200386#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200387#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000388
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000389typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000390 SOCKET_IS_NONBLOCKING,
391 SOCKET_IS_BLOCKING,
392 SOCKET_HAS_TIMED_OUT,
393 SOCKET_HAS_BEEN_CLOSED,
394 SOCKET_TOO_LARGE_FOR_SELECT,
395 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000396} timeout_state;
397
Thomas Woutersed03b412007-08-28 21:37:11 +0000398/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000399#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200400#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000401
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200402/* Get the socket from a PySSLSocket, if it has one */
403#define GET_SOCKET(obj) ((obj)->Socket ? \
404 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200405
Victor Stinner14690702015-04-06 22:46:13 +0200406/* If sock is NULL, use a timeout of 0 second */
407#define GET_SOCKET_TIMEOUT(sock) \
408 ((sock != NULL) ? (sock)->sock_timeout : 0)
409
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200410/*
411 * SSL errors.
412 */
413
414PyDoc_STRVAR(SSLError_doc,
415"An error occurred in the SSL implementation.");
416
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700417PyDoc_STRVAR(SSLCertVerificationError_doc,
418"A certificate could not be verified.");
419
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200420PyDoc_STRVAR(SSLZeroReturnError_doc,
421"SSL/TLS session closed cleanly.");
422
423PyDoc_STRVAR(SSLWantReadError_doc,
424"Non-blocking SSL socket needs to read more data\n"
425"before the requested operation can be completed.");
426
427PyDoc_STRVAR(SSLWantWriteError_doc,
428"Non-blocking SSL socket needs to write more data\n"
429"before the requested operation can be completed.");
430
431PyDoc_STRVAR(SSLSyscallError_doc,
432"System error when attempting SSL operation.");
433
434PyDoc_STRVAR(SSLEOFError_doc,
435"SSL/TLS connection terminated abruptly.");
436
437static PyObject *
438SSLError_str(PyOSErrorObject *self)
439{
440 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
441 Py_INCREF(self->strerror);
442 return self->strerror;
443 }
444 else
445 return PyObject_Str(self->args);
446}
447
448static PyType_Slot sslerror_type_slots[] = {
449 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
450 {Py_tp_doc, SSLError_doc},
451 {Py_tp_str, SSLError_str},
452 {0, 0},
453};
454
455static PyType_Spec sslerror_type_spec = {
456 "ssl.SSLError",
457 sizeof(PyOSErrorObject),
458 0,
459 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
460 sslerror_type_slots
461};
462
463static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700464fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
465 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200466{
467 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700468 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200469 PyObject *init_value, *msg, *key;
470 _Py_IDENTIFIER(reason);
471 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700472 _Py_IDENTIFIER(verify_message);
473 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200474
475 if (errcode != 0) {
476 int lib, reason;
477
478 lib = ERR_GET_LIB(errcode);
479 reason = ERR_GET_REASON(errcode);
480 key = Py_BuildValue("ii", lib, reason);
481 if (key == NULL)
482 goto fail;
483 reason_obj = PyDict_GetItem(err_codes_to_names, key);
484 Py_DECREF(key);
485 if (reason_obj == NULL) {
486 /* XXX if reason < 100, it might reflect a library number (!!) */
487 PyErr_Clear();
488 }
489 key = PyLong_FromLong(lib);
490 if (key == NULL)
491 goto fail;
492 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
493 Py_DECREF(key);
494 if (lib_obj == NULL) {
495 PyErr_Clear();
496 }
497 if (errstr == NULL)
498 errstr = ERR_reason_error_string(errcode);
499 }
500 if (errstr == NULL)
501 errstr = "unknown error";
502
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700503 /* verify code for cert validation error */
504 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
505 const char *verify_str = NULL;
506 long verify_code;
507
508 verify_code = SSL_get_verify_result(sslsock->ssl);
509 verify_code_obj = PyLong_FromLong(verify_code);
510 if (verify_code_obj == NULL) {
511 goto fail;
512 }
513
514 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700515#ifdef X509_V_ERR_HOSTNAME_MISMATCH
516 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700517 case X509_V_ERR_HOSTNAME_MISMATCH:
518 verify_obj = PyUnicode_FromFormat(
519 "Hostname mismatch, certificate is not valid for '%S'.",
520 sslsock->server_hostname
521 );
522 break;
Christian Heimes09153602017-09-08 14:47:58 -0700523#endif
524#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700525 case X509_V_ERR_IP_ADDRESS_MISMATCH:
526 verify_obj = PyUnicode_FromFormat(
527 "IP address mismatch, certificate is not valid for '%S'.",
528 sslsock->server_hostname
529 );
530 break;
Christian Heimes09153602017-09-08 14:47:58 -0700531#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700532 default:
533 verify_str = X509_verify_cert_error_string(verify_code);
534 if (verify_str != NULL) {
535 verify_obj = PyUnicode_FromString(verify_str);
536 } else {
537 verify_obj = Py_None;
538 Py_INCREF(verify_obj);
539 }
540 break;
541 }
542 if (verify_obj == NULL) {
543 goto fail;
544 }
545 }
546
547 if (verify_obj && reason_obj && lib_obj)
548 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
549 lib_obj, reason_obj, errstr, verify_obj,
550 lineno);
551 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200552 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
553 lib_obj, reason_obj, errstr, lineno);
554 else if (lib_obj)
555 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
556 lib_obj, errstr, lineno);
557 else
558 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200559 if (msg == NULL)
560 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100561
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200562 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100563 if (init_value == NULL)
564 goto fail;
565
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200566 err_value = PyObject_CallObject(type, init_value);
567 Py_DECREF(init_value);
568 if (err_value == NULL)
569 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100570
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200571 if (reason_obj == NULL)
572 reason_obj = Py_None;
573 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
574 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700575
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200576 if (lib_obj == NULL)
577 lib_obj = Py_None;
578 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
579 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700580
581 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
582 /* Only set verify code / message for SSLCertVerificationError */
583 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
584 verify_code_obj))
585 goto fail;
586 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
587 goto fail;
588 }
589
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200590 PyErr_SetObject(type, err_value);
591fail:
592 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700593 Py_XDECREF(verify_code_obj);
594 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200595}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000596
597static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700598PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000599{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200600 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200601 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000602 int err;
603 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200604 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000606 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200607 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000608
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700609 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700610 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000611
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000612 switch (err) {
613 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200614 errstr = "TLS/SSL connection has been closed (EOF)";
615 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000616 p = PY_SSL_ERROR_ZERO_RETURN;
617 break;
618 case SSL_ERROR_WANT_READ:
619 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200620 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000621 p = PY_SSL_ERROR_WANT_READ;
622 break;
623 case SSL_ERROR_WANT_WRITE:
624 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200625 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000626 errstr = "The operation did not complete (write)";
627 break;
628 case SSL_ERROR_WANT_X509_LOOKUP:
629 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000630 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 break;
632 case SSL_ERROR_WANT_CONNECT:
633 p = PY_SSL_ERROR_WANT_CONNECT;
634 errstr = "The operation did not complete (connect)";
635 break;
636 case SSL_ERROR_SYSCALL:
637 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000638 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700639 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000640 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000641 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200642 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000643 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200644 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000645 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000646 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700647#ifdef MS_WINDOWS
648 if (sslsock->ws_errno)
649 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
650#endif
651 if (sslsock->c_errno) {
652 errno = sslsock->c_errno;
653 return PyErr_SetFromErrno(PyExc_OSError);
654 }
655 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200656 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000657 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200658 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000660 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200661 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000662 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000663 }
664 } else {
665 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000666 }
667 break;
668 }
669 case SSL_ERROR_SSL:
670 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000671 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700672 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200673 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000674 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700675 }
676 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
677 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
678 type = PySSLCertVerificationErrorObject;
679 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000680 break;
681 }
682 default:
683 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
684 errstr = "Invalid error code";
685 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000686 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700687 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000688 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000690}
691
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000692static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200693_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000694
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200695 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000696 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200697 else
698 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700699 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000700 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000701 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000702}
703
Antoine Pitrou152efa22010-05-16 18:19:27 +0000704static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100705newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000706 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200707 char *server_hostname,
708 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000709{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000710 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100711 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200712 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000713
Antoine Pitrou152efa22010-05-16 18:19:27 +0000714 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000715 if (self == NULL)
716 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000717
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000718 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000719 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100720 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700721 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200722 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200723 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700724 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200725 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700726 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
727 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200728 if (hostname == NULL) {
729 Py_DECREF(self);
730 return NULL;
731 }
732 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700733 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700734 self->ssl_errno = 0;
735 self->c_errno = 0;
736#ifdef MS_WINDOWS
737 self->ws_errno = 0;
738#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200739
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000740 /* Make sure the SSL error state is initialized */
741 (void) ERR_get_state();
742 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000743
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000744 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000745 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000746 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200747 SSL_set_app_data(self->ssl, self);
748 if (sock) {
749 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
750 } else {
751 /* BIOs are reference counted and SSL_set_bio borrows our reference.
752 * To prevent a double free in memory_bio_dealloc() we need to take an
753 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200754 BIO_up_ref(inbio->bio);
755 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200756 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
757 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200758 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000759#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200760 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000761#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200762 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000763
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100764#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000765 if (server_hostname != NULL)
766 SSL_set_tlsext_host_name(self->ssl, server_hostname);
767#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000768 /* If the socket is in non-blocking mode or timeout mode, set the BIO
769 * to non-blocking mode (blocking is the default)
770 */
Victor Stinnere2452312015-03-28 03:00:46 +0100771 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000772 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
773 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
774 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000775
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000776 PySSL_BEGIN_ALLOW_THREADS
777 if (socket_type == PY_SSL_CLIENT)
778 SSL_set_connect_state(self->ssl);
779 else
780 SSL_set_accept_state(self->ssl);
781 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000782
Antoine Pitroud6494802011-07-21 01:11:30 +0200783 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200784 if (sock != NULL) {
785 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
786 if (self->Socket == NULL) {
787 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200788 return NULL;
789 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100790 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000791 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000792}
793
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000794/* SSL object methods */
795
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300796/*[clinic input]
797_ssl._SSLSocket.do_handshake
798[clinic start generated code]*/
799
800static PyObject *
801_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
802/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000803{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000804 int ret;
805 int err;
806 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200807 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200808 _PyTime_t timeout, deadline = 0;
809 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000810
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200811 if (sock) {
812 if (((PyObject*)sock) == Py_None) {
813 _setSSLError("Underlying socket connection gone",
814 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
815 return NULL;
816 }
817 Py_INCREF(sock);
818
819 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100820 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200821 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
822 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000824
Victor Stinner14690702015-04-06 22:46:13 +0200825 timeout = GET_SOCKET_TIMEOUT(sock);
826 has_timeout = (timeout > 0);
827 if (has_timeout)
828 deadline = _PyTime_GetMonotonicClock() + timeout;
829
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000830 /* Actually negotiate SSL connection */
831 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000832 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000833 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000834 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700835 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000836 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700837 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200838
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000839 if (PyErr_CheckSignals())
840 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200841
Victor Stinner14690702015-04-06 22:46:13 +0200842 if (has_timeout)
843 timeout = deadline - _PyTime_GetMonotonicClock();
844
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000845 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200846 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000847 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200848 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000849 } else {
850 sockstate = SOCKET_OPERATION_OK;
851 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200852
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000853 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000854 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000855 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000856 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000857 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
858 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000859 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000860 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000861 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
862 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000863 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000864 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000865 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
866 break;
867 }
868 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200869 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000870 if (ret < 1)
871 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000872
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200873 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000874
875error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200876 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000877 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000878}
879
Thomas Woutersed03b412007-08-28 21:37:11 +0000880static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300881_asn1obj2py(const ASN1_OBJECT *name, int no_name)
882{
883 char buf[X509_NAME_MAXLEN];
884 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300886 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000887
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300888 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000889 if (buflen < 0) {
890 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300891 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000892 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300893 /* initial buffer is too small for oid + terminating null byte */
894 if (buflen > X509_NAME_MAXLEN - 1) {
895 /* make OBJ_obj2txt() calculate the required buflen */
896 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
897 /* allocate len + 1 for terminating NULL byte */
898 namebuf = PyMem_Malloc(buflen + 1);
899 if (namebuf == NULL) {
900 PyErr_NoMemory();
901 return NULL;
902 }
903 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
904 if (buflen < 0) {
905 _setSSLError(NULL, 0, __FILE__, __LINE__);
906 goto done;
907 }
908 }
909 if (!buflen && no_name) {
910 Py_INCREF(Py_None);
911 name_obj = Py_None;
912 }
913 else {
914 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
915 }
916
917 done:
918 if (buf != namebuf) {
919 PyMem_Free(namebuf);
920 }
921 return name_obj;
922}
923
924static PyObject *
925_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
926{
927 Py_ssize_t buflen;
928 unsigned char *valuebuf = NULL;
929 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000930
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
932 if (buflen < 0) {
933 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300934 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000935 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300936 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000938 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000939}
940
941static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000942_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000943{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000944 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
945 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
946 PyObject *rdnt;
947 PyObject *attr = NULL; /* tuple to hold an attribute */
948 int entry_count = X509_NAME_entry_count(xname);
949 X509_NAME_ENTRY *entry;
950 ASN1_OBJECT *name;
951 ASN1_STRING *value;
952 int index_counter;
953 int rdn_level = -1;
954 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000955
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000956 dn = PyList_New(0);
957 if (dn == NULL)
958 return NULL;
959 /* now create another tuple to hold the top-level RDN */
960 rdn = PyList_New(0);
961 if (rdn == NULL)
962 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000963
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000964 for (index_counter = 0;
965 index_counter < entry_count;
966 index_counter++)
967 {
968 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000969
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000970 /* check to see if we've gotten to a new RDN */
971 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200972 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000973 /* yes, new RDN */
974 /* add old RDN to DN */
975 rdnt = PyList_AsTuple(rdn);
976 Py_DECREF(rdn);
977 if (rdnt == NULL)
978 goto fail0;
979 retcode = PyList_Append(dn, rdnt);
980 Py_DECREF(rdnt);
981 if (retcode < 0)
982 goto fail0;
983 /* create new RDN */
984 rdn = PyList_New(0);
985 if (rdn == NULL)
986 goto fail0;
987 }
988 }
Christian Heimes598894f2016-09-05 23:19:05 +0200989 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000990
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000991 /* now add this attribute to the current RDN */
992 name = X509_NAME_ENTRY_get_object(entry);
993 value = X509_NAME_ENTRY_get_data(entry);
994 attr = _create_tuple_for_attribute(name, value);
995 /*
996 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
997 entry->set,
998 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
999 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
1000 */
1001 if (attr == NULL)
1002 goto fail1;
1003 retcode = PyList_Append(rdn, attr);
1004 Py_DECREF(attr);
1005 if (retcode < 0)
1006 goto fail1;
1007 }
1008 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001009 if (rdn != NULL) {
1010 if (PyList_GET_SIZE(rdn) > 0) {
1011 rdnt = PyList_AsTuple(rdn);
1012 Py_DECREF(rdn);
1013 if (rdnt == NULL)
1014 goto fail0;
1015 retcode = PyList_Append(dn, rdnt);
1016 Py_DECREF(rdnt);
1017 if (retcode < 0)
1018 goto fail0;
1019 }
1020 else {
1021 Py_DECREF(rdn);
1022 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001023 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001024
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001025 /* convert list to tuple */
1026 rdnt = PyList_AsTuple(dn);
1027 Py_DECREF(dn);
1028 if (rdnt == NULL)
1029 return NULL;
1030 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001031
1032 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001033 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001034
1035 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 Py_XDECREF(dn);
1037 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001038}
1039
1040static PyObject *
1041_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001042
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 /* this code follows the procedure outlined in
1044 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1045 function to extract the STACK_OF(GENERAL_NAME),
1046 then iterates through the stack to add the
1047 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001048
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001049 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001050 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001051 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 GENERAL_NAMES *names = NULL;
1053 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001054 BIO *biobuf = NULL;
1055 char buf[2048];
1056 char *vptr;
1057 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001058
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001059 if (certificate == NULL)
1060 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001061
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001062 /* get a memory buffer */
1063 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001064
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001065 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1066 certificate, NID_subject_alt_name, NULL, NULL);
1067 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 if (peer_alt_names == Py_None) {
1069 peer_alt_names = PyList_New(0);
1070 if (peer_alt_names == NULL)
1071 goto fail;
1072 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001073
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001074 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001075 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001076 int gntype;
1077 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001080 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001081 switch (gntype) {
1082 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001083 /* we special-case DirName as a tuple of
1084 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001085
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001086 t = PyTuple_New(2);
1087 if (t == NULL) {
1088 goto fail;
1089 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 v = PyUnicode_FromString("DirName");
1092 if (v == NULL) {
1093 Py_DECREF(t);
1094 goto fail;
1095 }
1096 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001098 v = _create_tuple_for_X509_NAME (name->d.dirn);
1099 if (v == NULL) {
1100 Py_DECREF(t);
1101 goto fail;
1102 }
1103 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001104 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001105
Christian Heimes824f7f32013-08-17 00:54:47 +02001106 case GEN_EMAIL:
1107 case GEN_DNS:
1108 case GEN_URI:
1109 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1110 correctly, CVE-2013-4238 */
1111 t = PyTuple_New(2);
1112 if (t == NULL)
1113 goto fail;
1114 switch (gntype) {
1115 case GEN_EMAIL:
1116 v = PyUnicode_FromString("email");
1117 as = name->d.rfc822Name;
1118 break;
1119 case GEN_DNS:
1120 v = PyUnicode_FromString("DNS");
1121 as = name->d.dNSName;
1122 break;
1123 case GEN_URI:
1124 v = PyUnicode_FromString("URI");
1125 as = name->d.uniformResourceIdentifier;
1126 break;
1127 }
1128 if (v == NULL) {
1129 Py_DECREF(t);
1130 goto fail;
1131 }
1132 PyTuple_SET_ITEM(t, 0, v);
1133 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1134 ASN1_STRING_length(as));
1135 if (v == NULL) {
1136 Py_DECREF(t);
1137 goto fail;
1138 }
1139 PyTuple_SET_ITEM(t, 1, v);
1140 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001141
Christian Heimes1c03abd2016-09-06 23:25:35 +02001142 case GEN_RID:
1143 t = PyTuple_New(2);
1144 if (t == NULL)
1145 goto fail;
1146
1147 v = PyUnicode_FromString("Registered ID");
1148 if (v == NULL) {
1149 Py_DECREF(t);
1150 goto fail;
1151 }
1152 PyTuple_SET_ITEM(t, 0, v);
1153
1154 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1155 if (len < 0) {
1156 Py_DECREF(t);
1157 _setSSLError(NULL, 0, __FILE__, __LINE__);
1158 goto fail;
1159 } else if (len >= (int)sizeof(buf)) {
1160 v = PyUnicode_FromString("<INVALID>");
1161 } else {
1162 v = PyUnicode_FromStringAndSize(buf, len);
1163 }
1164 if (v == NULL) {
1165 Py_DECREF(t);
1166 goto fail;
1167 }
1168 PyTuple_SET_ITEM(t, 1, v);
1169 break;
1170
Christian Heimes824f7f32013-08-17 00:54:47 +02001171 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001172 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001173 switch (gntype) {
1174 /* check for new general name type */
1175 case GEN_OTHERNAME:
1176 case GEN_X400:
1177 case GEN_EDIPARTY:
1178 case GEN_IPADD:
1179 case GEN_RID:
1180 break;
1181 default:
1182 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1183 "Unknown general name type %d",
1184 gntype) == -1) {
1185 goto fail;
1186 }
1187 break;
1188 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001189 (void) BIO_reset(biobuf);
1190 GENERAL_NAME_print(biobuf, name);
1191 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1192 if (len < 0) {
1193 _setSSLError(NULL, 0, __FILE__, __LINE__);
1194 goto fail;
1195 }
1196 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001197 if (vptr == NULL) {
1198 PyErr_Format(PyExc_ValueError,
1199 "Invalid value %.200s",
1200 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001201 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001202 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001203 t = PyTuple_New(2);
1204 if (t == NULL)
1205 goto fail;
1206 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1207 if (v == NULL) {
1208 Py_DECREF(t);
1209 goto fail;
1210 }
1211 PyTuple_SET_ITEM(t, 0, v);
1212 v = PyUnicode_FromStringAndSize((vptr + 1),
1213 (len - (vptr - buf + 1)));
1214 if (v == NULL) {
1215 Py_DECREF(t);
1216 goto fail;
1217 }
1218 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001219 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001220 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001221
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001222 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001223
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 if (PyList_Append(peer_alt_names, t) < 0) {
1225 Py_DECREF(t);
1226 goto fail;
1227 }
1228 Py_DECREF(t);
1229 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001230 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001231 }
1232 BIO_free(biobuf);
1233 if (peer_alt_names != Py_None) {
1234 v = PyList_AsTuple(peer_alt_names);
1235 Py_DECREF(peer_alt_names);
1236 return v;
1237 } else {
1238 return peer_alt_names;
1239 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001240
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001241
1242 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 if (biobuf != NULL)
1244 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001245
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001246 if (peer_alt_names != Py_None) {
1247 Py_XDECREF(peer_alt_names);
1248 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001250 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001251}
1252
1253static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001254_get_aia_uri(X509 *certificate, int nid) {
1255 PyObject *lst = NULL, *ostr = NULL;
1256 int i, result;
1257 AUTHORITY_INFO_ACCESS *info;
1258
1259 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001260 if (info == NULL)
1261 return Py_None;
1262 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1263 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001264 return Py_None;
1265 }
1266
1267 if ((lst = PyList_New(0)) == NULL) {
1268 goto fail;
1269 }
1270
1271 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1272 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1273 ASN1_IA5STRING *uri;
1274
1275 if ((OBJ_obj2nid(ad->method) != nid) ||
1276 (ad->location->type != GEN_URI)) {
1277 continue;
1278 }
1279 uri = ad->location->d.uniformResourceIdentifier;
1280 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1281 uri->length);
1282 if (ostr == NULL) {
1283 goto fail;
1284 }
1285 result = PyList_Append(lst, ostr);
1286 Py_DECREF(ostr);
1287 if (result < 0) {
1288 goto fail;
1289 }
1290 }
1291 AUTHORITY_INFO_ACCESS_free(info);
1292
1293 /* convert to tuple or None */
1294 if (PyList_Size(lst) == 0) {
1295 Py_DECREF(lst);
1296 return Py_None;
1297 } else {
1298 PyObject *tup;
1299 tup = PyList_AsTuple(lst);
1300 Py_DECREF(lst);
1301 return tup;
1302 }
1303
1304 fail:
1305 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001306 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001307 return NULL;
1308}
1309
1310static PyObject *
1311_get_crl_dp(X509 *certificate) {
1312 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001313 int i, j;
1314 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001315
Christian Heimes598894f2016-09-05 23:19:05 +02001316 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001317
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001318 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001319 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001320
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001321 lst = PyList_New(0);
1322 if (lst == NULL)
1323 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001324
1325 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1326 DIST_POINT *dp;
1327 STACK_OF(GENERAL_NAME) *gns;
1328
1329 dp = sk_DIST_POINT_value(dps, i);
1330 gns = dp->distpoint->name.fullname;
1331
1332 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1333 GENERAL_NAME *gn;
1334 ASN1_IA5STRING *uri;
1335 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001336 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001337
1338 gn = sk_GENERAL_NAME_value(gns, j);
1339 if (gn->type != GEN_URI) {
1340 continue;
1341 }
1342 uri = gn->d.uniformResourceIdentifier;
1343 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1344 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001345 if (ouri == NULL)
1346 goto done;
1347
1348 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001349 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001350 if (err < 0)
1351 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001352 }
1353 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001354
1355 /* Convert to tuple. */
1356 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1357
1358 done:
1359 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001360 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001361 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001362}
1363
1364static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001365_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001366
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001367 PyObject *retval = NULL;
1368 BIO *biobuf = NULL;
1369 PyObject *peer;
1370 PyObject *peer_alt_names = NULL;
1371 PyObject *issuer;
1372 PyObject *version;
1373 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001374 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001375 ASN1_INTEGER *serialNumber;
1376 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001377 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 ASN1_TIME *notBefore, *notAfter;
1379 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001380
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001381 retval = PyDict_New();
1382 if (retval == NULL)
1383 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001384
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001385 peer = _create_tuple_for_X509_NAME(
1386 X509_get_subject_name(certificate));
1387 if (peer == NULL)
1388 goto fail0;
1389 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1390 Py_DECREF(peer);
1391 goto fail0;
1392 }
1393 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001394
Antoine Pitroufb046912010-11-09 20:21:19 +00001395 issuer = _create_tuple_for_X509_NAME(
1396 X509_get_issuer_name(certificate));
1397 if (issuer == NULL)
1398 goto fail0;
1399 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001400 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001401 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001402 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001403 Py_DECREF(issuer);
1404
1405 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001406 if (version == NULL)
1407 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001408 if (PyDict_SetItemString(retval, "version", version) < 0) {
1409 Py_DECREF(version);
1410 goto fail0;
1411 }
1412 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001413
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001414 /* get a memory buffer */
1415 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001416
Antoine Pitroufb046912010-11-09 20:21:19 +00001417 (void) BIO_reset(biobuf);
1418 serialNumber = X509_get_serialNumber(certificate);
1419 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1420 i2a_ASN1_INTEGER(biobuf, serialNumber);
1421 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1422 if (len < 0) {
1423 _setSSLError(NULL, 0, __FILE__, __LINE__);
1424 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001425 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001426 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1427 if (sn_obj == NULL)
1428 goto fail1;
1429 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1430 Py_DECREF(sn_obj);
1431 goto fail1;
1432 }
1433 Py_DECREF(sn_obj);
1434
1435 (void) BIO_reset(biobuf);
1436 notBefore = X509_get_notBefore(certificate);
1437 ASN1_TIME_print(biobuf, notBefore);
1438 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1439 if (len < 0) {
1440 _setSSLError(NULL, 0, __FILE__, __LINE__);
1441 goto fail1;
1442 }
1443 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1444 if (pnotBefore == NULL)
1445 goto fail1;
1446 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1447 Py_DECREF(pnotBefore);
1448 goto fail1;
1449 }
1450 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001451
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001452 (void) BIO_reset(biobuf);
1453 notAfter = X509_get_notAfter(certificate);
1454 ASN1_TIME_print(biobuf, notAfter);
1455 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1456 if (len < 0) {
1457 _setSSLError(NULL, 0, __FILE__, __LINE__);
1458 goto fail1;
1459 }
1460 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1461 if (pnotAfter == NULL)
1462 goto fail1;
1463 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1464 Py_DECREF(pnotAfter);
1465 goto fail1;
1466 }
1467 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001468
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001469 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001470
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001471 peer_alt_names = _get_peer_alt_names(certificate);
1472 if (peer_alt_names == NULL)
1473 goto fail1;
1474 else if (peer_alt_names != Py_None) {
1475 if (PyDict_SetItemString(retval, "subjectAltName",
1476 peer_alt_names) < 0) {
1477 Py_DECREF(peer_alt_names);
1478 goto fail1;
1479 }
1480 Py_DECREF(peer_alt_names);
1481 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001482
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001483 /* Authority Information Access: OCSP URIs */
1484 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1485 if (obj == NULL) {
1486 goto fail1;
1487 } else if (obj != Py_None) {
1488 result = PyDict_SetItemString(retval, "OCSP", obj);
1489 Py_DECREF(obj);
1490 if (result < 0) {
1491 goto fail1;
1492 }
1493 }
1494
1495 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1496 if (obj == NULL) {
1497 goto fail1;
1498 } else if (obj != Py_None) {
1499 result = PyDict_SetItemString(retval, "caIssuers", obj);
1500 Py_DECREF(obj);
1501 if (result < 0) {
1502 goto fail1;
1503 }
1504 }
1505
1506 /* CDP (CRL distribution points) */
1507 obj = _get_crl_dp(certificate);
1508 if (obj == NULL) {
1509 goto fail1;
1510 } else if (obj != Py_None) {
1511 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1512 Py_DECREF(obj);
1513 if (result < 0) {
1514 goto fail1;
1515 }
1516 }
1517
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 BIO_free(biobuf);
1519 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001520
1521 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001522 if (biobuf != NULL)
1523 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001524 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001525 Py_XDECREF(retval);
1526 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001527}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001528
Christian Heimes9a5395a2013-06-17 15:44:12 +02001529static PyObject *
1530_certificate_to_der(X509 *certificate)
1531{
1532 unsigned char *bytes_buf = NULL;
1533 int len;
1534 PyObject *retval;
1535
1536 bytes_buf = NULL;
1537 len = i2d_X509(certificate, &bytes_buf);
1538 if (len < 0) {
1539 _setSSLError(NULL, 0, __FILE__, __LINE__);
1540 return NULL;
1541 }
1542 /* this is actually an immutable bytes sequence */
1543 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1544 OPENSSL_free(bytes_buf);
1545 return retval;
1546}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001547
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001548/*[clinic input]
1549_ssl._test_decode_cert
1550 path: object(converter="PyUnicode_FSConverter")
1551 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001552
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001553[clinic start generated code]*/
1554
1555static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001556_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1557/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001558{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001559 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001560 X509 *x=NULL;
1561 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001562
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1564 PyErr_SetString(PySSLErrorObject,
1565 "Can't malloc memory to read file");
1566 goto fail0;
1567 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001568
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001569 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001570 PyErr_SetString(PySSLErrorObject,
1571 "Can't open file");
1572 goto fail0;
1573 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001575 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1576 if (x == NULL) {
1577 PyErr_SetString(PySSLErrorObject,
1578 "Error decoding PEM-encoded file");
1579 goto fail0;
1580 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001581
Antoine Pitroufb046912010-11-09 20:21:19 +00001582 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001583 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001584
1585 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001586 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001587 if (cert != NULL) BIO_free(cert);
1588 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001589}
1590
1591
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001592/*[clinic input]
1593_ssl._SSLSocket.peer_certificate
1594 der as binary_mode: bool = False
1595 /
1596
1597Returns the certificate for the peer.
1598
1599If no certificate was provided, returns None. If a certificate was
1600provided, but not validated, returns an empty dictionary. Otherwise
1601returns a dict containing information about the peer certificate.
1602
1603If the optional argument is True, returns a DER-encoded copy of the
1604peer certificate, or None if no certificate was provided. This will
1605return the certificate even if it wasn't validated.
1606[clinic start generated code]*/
1607
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001609_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1610/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001611{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001612 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001613 X509 *peer_cert;
1614 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001615
Christian Heimes66dc33b2017-05-23 16:02:02 -07001616 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001617 PyErr_SetString(PyExc_ValueError,
1618 "handshake not done yet");
1619 return NULL;
1620 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001621 peer_cert = SSL_get_peer_certificate(self->ssl);
1622 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001624
Antoine Pitrou721738f2012-08-15 23:20:39 +02001625 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001626 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001627 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001628 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001629 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001630 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001631 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001632 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001633 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001634 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001635 X509_free(peer_cert);
1636 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001637}
1638
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001639static PyObject *
1640cipher_to_tuple(const SSL_CIPHER *cipher)
1641{
1642 const char *cipher_name, *cipher_protocol;
1643 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001644 if (retval == NULL)
1645 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001646
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001647 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001649 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001650 PyTuple_SET_ITEM(retval, 0, Py_None);
1651 } else {
1652 v = PyUnicode_FromString(cipher_name);
1653 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001654 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001655 PyTuple_SET_ITEM(retval, 0, v);
1656 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001657
1658 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001660 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001661 PyTuple_SET_ITEM(retval, 1, Py_None);
1662 } else {
1663 v = PyUnicode_FromString(cipher_protocol);
1664 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001665 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001666 PyTuple_SET_ITEM(retval, 1, v);
1667 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001668
1669 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001671 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001672 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001673
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001674 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001675
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001676 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001677 Py_DECREF(retval);
1678 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001679}
1680
Christian Heimes25bfcd52016-09-06 00:04:45 +02001681#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1682static PyObject *
1683cipher_to_dict(const SSL_CIPHER *cipher)
1684{
1685 const char *cipher_name, *cipher_protocol;
1686
1687 unsigned long cipher_id;
1688 int alg_bits, strength_bits, len;
1689 char buf[512] = {0};
1690#if OPENSSL_VERSION_1_1
1691 int aead, nid;
1692 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1693#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001694
1695 /* can be NULL */
1696 cipher_name = SSL_CIPHER_get_name(cipher);
1697 cipher_protocol = SSL_CIPHER_get_version(cipher);
1698 cipher_id = SSL_CIPHER_get_id(cipher);
1699 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001700 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1701 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001702 if (len > 1 && buf[len-1] == '\n')
1703 buf[len-1] = '\0';
1704 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1705
1706#if OPENSSL_VERSION_1_1
1707 aead = SSL_CIPHER_is_aead(cipher);
1708 nid = SSL_CIPHER_get_cipher_nid(cipher);
1709 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1710 nid = SSL_CIPHER_get_digest_nid(cipher);
1711 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1712 nid = SSL_CIPHER_get_kx_nid(cipher);
1713 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1714 nid = SSL_CIPHER_get_auth_nid(cipher);
1715 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1716#endif
1717
Victor Stinner410b9882016-09-12 12:00:23 +02001718 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001719 "{sksssssssisi"
1720#if OPENSSL_VERSION_1_1
1721 "sOssssssss"
1722#endif
1723 "}",
1724 "id", cipher_id,
1725 "name", cipher_name,
1726 "protocol", cipher_protocol,
1727 "description", buf,
1728 "strength_bits", strength_bits,
1729 "alg_bits", alg_bits
1730#if OPENSSL_VERSION_1_1
1731 ,"aead", aead ? Py_True : Py_False,
1732 "symmetric", skcipher,
1733 "digest", digest,
1734 "kea", kx,
1735 "auth", auth
1736#endif
1737 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001738}
1739#endif
1740
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001741/*[clinic input]
1742_ssl._SSLSocket.shared_ciphers
1743[clinic start generated code]*/
1744
1745static PyObject *
1746_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1747/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001748{
1749 STACK_OF(SSL_CIPHER) *ciphers;
1750 int i;
1751 PyObject *res;
1752
Christian Heimes598894f2016-09-05 23:19:05 +02001753 ciphers = SSL_get_ciphers(self->ssl);
1754 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001755 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001756 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1757 if (!res)
1758 return NULL;
1759 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1760 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1761 if (!tup) {
1762 Py_DECREF(res);
1763 return NULL;
1764 }
1765 PyList_SET_ITEM(res, i, tup);
1766 }
1767 return res;
1768}
1769
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001770/*[clinic input]
1771_ssl._SSLSocket.cipher
1772[clinic start generated code]*/
1773
1774static PyObject *
1775_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1776/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001777{
1778 const SSL_CIPHER *current;
1779
1780 if (self->ssl == NULL)
1781 Py_RETURN_NONE;
1782 current = SSL_get_current_cipher(self->ssl);
1783 if (current == NULL)
1784 Py_RETURN_NONE;
1785 return cipher_to_tuple(current);
1786}
1787
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001788/*[clinic input]
1789_ssl._SSLSocket.version
1790[clinic start generated code]*/
1791
1792static PyObject *
1793_ssl__SSLSocket_version_impl(PySSLSocket *self)
1794/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001795{
1796 const char *version;
1797
1798 if (self->ssl == NULL)
1799 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001800 if (!SSL_is_init_finished(self->ssl)) {
1801 /* handshake not finished */
1802 Py_RETURN_NONE;
1803 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001804 version = SSL_get_version(self->ssl);
1805 if (!strcmp(version, "unknown"))
1806 Py_RETURN_NONE;
1807 return PyUnicode_FromString(version);
1808}
1809
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001810#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001811/*[clinic input]
1812_ssl._SSLSocket.selected_npn_protocol
1813[clinic start generated code]*/
1814
1815static PyObject *
1816_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1817/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1818{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001819 const unsigned char *out;
1820 unsigned int outlen;
1821
Victor Stinner4569cd52013-06-23 14:58:43 +02001822 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001823 &out, &outlen);
1824
1825 if (out == NULL)
1826 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001827 return PyUnicode_FromStringAndSize((char *)out, outlen);
1828}
1829#endif
1830
1831#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001832/*[clinic input]
1833_ssl._SSLSocket.selected_alpn_protocol
1834[clinic start generated code]*/
1835
1836static PyObject *
1837_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1838/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1839{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001840 const unsigned char *out;
1841 unsigned int outlen;
1842
1843 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1844
1845 if (out == NULL)
1846 Py_RETURN_NONE;
1847 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001848}
1849#endif
1850
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001851/*[clinic input]
1852_ssl._SSLSocket.compression
1853[clinic start generated code]*/
1854
1855static PyObject *
1856_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1857/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1858{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001859#ifdef OPENSSL_NO_COMP
1860 Py_RETURN_NONE;
1861#else
1862 const COMP_METHOD *comp_method;
1863 const char *short_name;
1864
1865 if (self->ssl == NULL)
1866 Py_RETURN_NONE;
1867 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001868 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001869 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001870 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001871 if (short_name == NULL)
1872 Py_RETURN_NONE;
1873 return PyUnicode_DecodeFSDefault(short_name);
1874#endif
1875}
1876
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001877static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1878 Py_INCREF(self->ctx);
1879 return self->ctx;
1880}
1881
1882static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1883 void *closure) {
1884
1885 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001886#if !HAVE_SNI
1887 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1888 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001889 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001890#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001891 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001892 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001893 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001894#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001895 } else {
1896 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1897 return -1;
1898 }
1899
1900 return 0;
1901}
1902
1903PyDoc_STRVAR(PySSL_set_context_doc,
1904"_setter_context(ctx)\n\
1905\
1906This changes the context associated with the SSLSocket. This is typically\n\
1907used from within a callback function set by the set_servername_callback\n\
1908on the SSLContext to change the certificate information associated with the\n\
1909SSLSocket before the cryptographic exchange handshake messages\n");
1910
1911
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001912static PyObject *
1913PySSL_get_server_side(PySSLSocket *self, void *c)
1914{
1915 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1916}
1917
1918PyDoc_STRVAR(PySSL_get_server_side_doc,
1919"Whether this is a server-side socket.");
1920
1921static PyObject *
1922PySSL_get_server_hostname(PySSLSocket *self, void *c)
1923{
1924 if (self->server_hostname == NULL)
1925 Py_RETURN_NONE;
1926 Py_INCREF(self->server_hostname);
1927 return self->server_hostname;
1928}
1929
1930PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1931"The currently set server hostname (for SNI).");
1932
1933static PyObject *
1934PySSL_get_owner(PySSLSocket *self, void *c)
1935{
1936 PyObject *owner;
1937
1938 if (self->owner == NULL)
1939 Py_RETURN_NONE;
1940
1941 owner = PyWeakref_GetObject(self->owner);
1942 Py_INCREF(owner);
1943 return owner;
1944}
1945
1946static int
1947PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1948{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001949 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001950 if (self->owner == NULL)
1951 return -1;
1952 return 0;
1953}
1954
1955PyDoc_STRVAR(PySSL_get_owner_doc,
1956"The Python-level owner of this object.\
1957Passed as \"self\" in servername callback.");
1958
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001959
Antoine Pitrou152efa22010-05-16 18:19:27 +00001960static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001961{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001962 if (self->ssl)
1963 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001964 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001965 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001966 Py_XDECREF(self->server_hostname);
1967 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001968 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001969}
1970
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001971/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001972 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001973 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001974 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001975
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001976static int
Victor Stinner14690702015-04-06 22:46:13 +02001977PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001978{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001979 int rc;
1980#ifdef HAVE_POLL
1981 struct pollfd pollfd;
1982 _PyTime_t ms;
1983#else
1984 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001985 fd_set fds;
1986 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001987#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001988
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001989 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001990 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001991 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001992 else if (timeout < 0) {
1993 if (s->sock_timeout > 0)
1994 return SOCKET_HAS_TIMED_OUT;
1995 else
1996 return SOCKET_IS_BLOCKING;
1997 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001998
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001999 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002000 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002001 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002002
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002003 /* Prefer poll, if available, since you can poll() any fd
2004 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002005#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002006 pollfd.fd = s->sock_fd;
2007 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002008
Victor Stinner14690702015-04-06 22:46:13 +02002009 /* timeout is in seconds, poll() uses milliseconds */
2010 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002011 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002012
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002013 PySSL_BEGIN_ALLOW_THREADS
2014 rc = poll(&pollfd, 1, (int)ms);
2015 PySSL_END_ALLOW_THREADS
2016#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002017 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002018 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002019 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002020
Victor Stinner14690702015-04-06 22:46:13 +02002021 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002022
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002023 FD_ZERO(&fds);
2024 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002025
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002026 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002027 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002028 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002030 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002031 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002032 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002033 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002034#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002036 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2037 (when we are able to write or when there's something to read) */
2038 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002039}
2040
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002041/*[clinic input]
2042_ssl._SSLSocket.write
2043 b: Py_buffer
2044 /
2045
2046Writes the bytes-like object b into the SSL object.
2047
2048Returns the number of bytes written.
2049[clinic start generated code]*/
2050
2051static PyObject *
2052_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2053/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002054{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002055 int len;
2056 int sockstate;
2057 int err;
2058 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002059 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002060 _PyTime_t timeout, deadline = 0;
2061 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002062
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002063 if (sock != NULL) {
2064 if (((PyObject*)sock) == Py_None) {
2065 _setSSLError("Underlying socket connection gone",
2066 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2067 return NULL;
2068 }
2069 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002070 }
2071
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002072 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002073 PyErr_Format(PyExc_OverflowError,
2074 "string longer than %d bytes", INT_MAX);
2075 goto error;
2076 }
2077
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002078 if (sock != NULL) {
2079 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002080 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002081 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2082 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2083 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084
Victor Stinner14690702015-04-06 22:46:13 +02002085 timeout = GET_SOCKET_TIMEOUT(sock);
2086 has_timeout = (timeout > 0);
2087 if (has_timeout)
2088 deadline = _PyTime_GetMonotonicClock() + timeout;
2089
2090 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002091 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002092 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002093 "The write operation timed out");
2094 goto error;
2095 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2096 PyErr_SetString(PySSLErrorObject,
2097 "Underlying socket has been closed.");
2098 goto error;
2099 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2100 PyErr_SetString(PySSLErrorObject,
2101 "Underlying socket too large for select().");
2102 goto error;
2103 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002104
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002105 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002107 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002108 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002109 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002110 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002111
2112 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002113 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002114
Victor Stinner14690702015-04-06 22:46:13 +02002115 if (has_timeout)
2116 timeout = deadline - _PyTime_GetMonotonicClock();
2117
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002118 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002119 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002120 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002121 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002122 } else {
2123 sockstate = SOCKET_OPERATION_OK;
2124 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002125
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002126 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002127 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002128 "The write operation timed out");
2129 goto error;
2130 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2131 PyErr_SetString(PySSLErrorObject,
2132 "Underlying socket has been closed.");
2133 goto error;
2134 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2135 break;
2136 }
2137 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002138
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002139 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 if (len > 0)
2141 return PyLong_FromLong(len);
2142 else
2143 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002144
2145error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002146 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002147 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002148}
2149
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002150/*[clinic input]
2151_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002152
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002153Returns the number of already decrypted bytes available for read, pending on the connection.
2154[clinic start generated code]*/
2155
2156static PyObject *
2157_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2158/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002159{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002160 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002162 PySSL_BEGIN_ALLOW_THREADS
2163 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002164 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002165 PySSL_END_ALLOW_THREADS
2166 if (count < 0)
2167 return PySSL_SetError(self, count, __FILE__, __LINE__);
2168 else
2169 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002170}
2171
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002172/*[clinic input]
2173_ssl._SSLSocket.read
2174 size as len: int
2175 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002176 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002177 ]
2178 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002179
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002180Read up to size bytes from the SSL socket.
2181[clinic start generated code]*/
2182
2183static PyObject *
2184_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2185 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002186/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002187{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002188 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002189 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002190 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002191 int sockstate;
2192 int err;
2193 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002194 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002195 _PyTime_t timeout, deadline = 0;
2196 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002197
Martin Panter5503d472016-03-27 05:35:19 +00002198 if (!group_right_1 && len < 0) {
2199 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2200 return NULL;
2201 }
2202
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002203 if (sock != NULL) {
2204 if (((PyObject*)sock) == Py_None) {
2205 _setSSLError("Underlying socket connection gone",
2206 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2207 return NULL;
2208 }
2209 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002210 }
2211
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002212 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002213 dest = PyBytes_FromStringAndSize(NULL, len);
2214 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002215 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002216 if (len == 0) {
2217 Py_XDECREF(sock);
2218 return dest;
2219 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002220 mem = PyBytes_AS_STRING(dest);
2221 }
2222 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002223 mem = buffer->buf;
2224 if (len <= 0 || len > buffer->len) {
2225 len = (int) buffer->len;
2226 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002227 PyErr_SetString(PyExc_OverflowError,
2228 "maximum length can't fit in a C 'int'");
2229 goto error;
2230 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002231 if (len == 0) {
2232 count = 0;
2233 goto done;
2234 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002235 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002236 }
2237
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002238 if (sock != NULL) {
2239 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002240 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002241 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2242 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2243 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244
Victor Stinner14690702015-04-06 22:46:13 +02002245 timeout = GET_SOCKET_TIMEOUT(sock);
2246 has_timeout = (timeout > 0);
2247 if (has_timeout)
2248 deadline = _PyTime_GetMonotonicClock() + timeout;
2249
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002250 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002251 PySSL_BEGIN_ALLOW_THREADS
2252 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002253 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002254 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002256 if (PyErr_CheckSignals())
2257 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002258
Victor Stinner14690702015-04-06 22:46:13 +02002259 if (has_timeout)
2260 timeout = deadline - _PyTime_GetMonotonicClock();
2261
Steve Dowere6eb48c2017-09-08 15:16:15 -07002262 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002263 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002264 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002266 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002267 } else if (err == SSL_ERROR_ZERO_RETURN &&
2268 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 {
2270 count = 0;
2271 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002272 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002273 else
2274 sockstate = SOCKET_OPERATION_OK;
2275
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002276 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002277 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 "The read operation timed out");
2279 goto error;
2280 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2281 break;
2282 }
2283 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002285 if (count <= 0) {
2286 PySSL_SetError(self, count, __FILE__, __LINE__);
2287 goto error;
2288 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002289
2290done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002291 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002292 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002293 _PyBytes_Resize(&dest, count);
2294 return dest;
2295 }
2296 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 return PyLong_FromLong(count);
2298 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002299
2300error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002301 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002302 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002303 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002304 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002305}
2306
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002307/*[clinic input]
2308_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002309
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002310Does the SSL shutdown handshake with the remote end.
2311
2312Returns the underlying socket object.
2313[clinic start generated code]*/
2314
2315static PyObject *
2316_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2317/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002318{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002319 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002320 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002321 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002322 _PyTime_t timeout, deadline = 0;
2323 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002324
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002325 if (sock != NULL) {
2326 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002327 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002328 _setSSLError("Underlying socket connection gone",
2329 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2330 return NULL;
2331 }
2332 Py_INCREF(sock);
2333
2334 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002335 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002336 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2337 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002339
Victor Stinner14690702015-04-06 22:46:13 +02002340 timeout = GET_SOCKET_TIMEOUT(sock);
2341 has_timeout = (timeout > 0);
2342 if (has_timeout)
2343 deadline = _PyTime_GetMonotonicClock() + timeout;
2344
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 while (1) {
2346 PySSL_BEGIN_ALLOW_THREADS
2347 /* Disable read-ahead so that unwrap can work correctly.
2348 * Otherwise OpenSSL might read in too much data,
2349 * eating clear text data that happens to be
2350 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002351 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 * function is used and the shutdown_seen_zero != 0
2353 * condition is met.
2354 */
2355 if (self->shutdown_seen_zero)
2356 SSL_set_read_ahead(self->ssl, 0);
2357 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002358 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002359 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002360
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002361 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2362 if (err > 0)
2363 break;
2364 if (err == 0) {
2365 /* Don't loop endlessly; instead preserve legacy
2366 behaviour of trying SSL_shutdown() only twice.
2367 This looks necessary for OpenSSL < 0.9.8m */
2368 if (++zeros > 1)
2369 break;
2370 /* Shutdown was sent, now try receiving */
2371 self->shutdown_seen_zero = 1;
2372 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002373 }
2374
Victor Stinner14690702015-04-06 22:46:13 +02002375 if (has_timeout)
2376 timeout = deadline - _PyTime_GetMonotonicClock();
2377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002378 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002379 _PySSL_UPDATE_ERRNO(self, err);
2380 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002381 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002382 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002383 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002384 else
2385 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002386
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002387 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002388 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002389 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002390 "The read operation timed out");
2391 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002392 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002393 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002394 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002395 }
2396 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2397 PyErr_SetString(PySSLErrorObject,
2398 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002399 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002400 }
2401 else if (sockstate != SOCKET_OPERATION_OK)
2402 /* Retain the SSL error code */
2403 break;
2404 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002405
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002406 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002407 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002408 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002409 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002410 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002411 /* It's already INCREF'ed */
2412 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002413 else
2414 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002415
2416error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002417 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002418 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002419}
2420
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002421/*[clinic input]
2422_ssl._SSLSocket.tls_unique_cb
2423
2424Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2425
2426If the TLS handshake is not yet complete, None is returned.
2427[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002428
Antoine Pitroud6494802011-07-21 01:11:30 +02002429static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002430_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2431/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002432{
2433 PyObject *retval = NULL;
2434 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002435 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002436
2437 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2438 /* if session is resumed XOR we are the client */
2439 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2440 }
2441 else {
2442 /* if a new session XOR we are the server */
2443 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2444 }
2445
2446 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002447 if (len == 0)
2448 Py_RETURN_NONE;
2449
2450 retval = PyBytes_FromStringAndSize(buf, len);
2451
2452 return retval;
2453}
2454
Christian Heimes99a65702016-09-10 23:44:53 +02002455#ifdef OPENSSL_VERSION_1_1
2456
2457static SSL_SESSION*
2458_ssl_session_dup(SSL_SESSION *session) {
2459 SSL_SESSION *newsession = NULL;
2460 int slen;
2461 unsigned char *senc = NULL, *p;
2462 const unsigned char *const_p;
2463
2464 if (session == NULL) {
2465 PyErr_SetString(PyExc_ValueError, "Invalid session");
2466 goto error;
2467 }
2468
2469 /* get length */
2470 slen = i2d_SSL_SESSION(session, NULL);
2471 if (slen == 0 || slen > 0xFF00) {
2472 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2473 goto error;
2474 }
2475 if ((senc = PyMem_Malloc(slen)) == NULL) {
2476 PyErr_NoMemory();
2477 goto error;
2478 }
2479 p = senc;
2480 if (!i2d_SSL_SESSION(session, &p)) {
2481 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2482 goto error;
2483 }
2484 const_p = senc;
2485 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2486 if (session == NULL) {
2487 goto error;
2488 }
2489 PyMem_Free(senc);
2490 return newsession;
2491 error:
2492 if (senc != NULL) {
2493 PyMem_Free(senc);
2494 }
2495 return NULL;
2496}
2497#endif
2498
2499static PyObject *
2500PySSL_get_session(PySSLSocket *self, void *closure) {
2501 /* get_session can return sessions from a server-side connection,
2502 * it does not check for handshake done or client socket. */
2503 PySSLSession *pysess;
2504 SSL_SESSION *session;
2505
2506#ifdef OPENSSL_VERSION_1_1
2507 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2508 * https://github.com/openssl/openssl/issues/1550 */
2509 session = SSL_get0_session(self->ssl); /* borrowed reference */
2510 if (session == NULL) {
2511 Py_RETURN_NONE;
2512 }
2513 if ((session = _ssl_session_dup(session)) == NULL) {
2514 return NULL;
2515 }
2516#else
2517 session = SSL_get1_session(self->ssl);
2518 if (session == NULL) {
2519 Py_RETURN_NONE;
2520 }
2521#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002522 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002523 if (pysess == NULL) {
2524 SSL_SESSION_free(session);
2525 return NULL;
2526 }
2527
2528 assert(self->ctx);
2529 pysess->ctx = self->ctx;
2530 Py_INCREF(pysess->ctx);
2531 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002532 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002533 return (PyObject *)pysess;
2534}
2535
2536static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2537 void *closure)
2538 {
2539 PySSLSession *pysess;
2540#ifdef OPENSSL_VERSION_1_1
2541 SSL_SESSION *session;
2542#endif
2543 int result;
2544
2545 if (!PySSLSession_Check(value)) {
2546 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2547 return -1;
2548 }
2549 pysess = (PySSLSession *)value;
2550
2551 if (self->ctx->ctx != pysess->ctx->ctx) {
2552 PyErr_SetString(PyExc_ValueError,
2553 "Session refers to a different SSLContext.");
2554 return -1;
2555 }
2556 if (self->socket_type != PY_SSL_CLIENT) {
2557 PyErr_SetString(PyExc_ValueError,
2558 "Cannot set session for server-side SSLSocket.");
2559 return -1;
2560 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002561 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002562 PyErr_SetString(PyExc_ValueError,
2563 "Cannot set session after handshake.");
2564 return -1;
2565 }
2566#ifdef OPENSSL_VERSION_1_1
2567 /* duplicate session */
2568 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2569 return -1;
2570 }
2571 result = SSL_set_session(self->ssl, session);
2572 /* free duplicate, SSL_set_session() bumps ref count */
2573 SSL_SESSION_free(session);
2574#else
2575 result = SSL_set_session(self->ssl, pysess->session);
2576#endif
2577 if (result == 0) {
2578 _setSSLError(NULL, 0, __FILE__, __LINE__);
2579 return -1;
2580 }
2581 return 0;
2582}
2583
2584PyDoc_STRVAR(PySSL_set_session_doc,
2585"_setter_session(session)\n\
2586\
2587Get / set SSLSession.");
2588
2589static PyObject *
2590PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2591 if (SSL_session_reused(self->ssl)) {
2592 Py_RETURN_TRUE;
2593 } else {
2594 Py_RETURN_FALSE;
2595 }
2596}
2597
2598PyDoc_STRVAR(PySSL_get_session_reused_doc,
2599"Was the client session reused during handshake?");
2600
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002601static PyGetSetDef ssl_getsetlist[] = {
2602 {"context", (getter) PySSL_get_context,
2603 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002604 {"server_side", (getter) PySSL_get_server_side, NULL,
2605 PySSL_get_server_side_doc},
2606 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2607 PySSL_get_server_hostname_doc},
2608 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2609 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002610 {"session", (getter) PySSL_get_session,
2611 (setter) PySSL_set_session, PySSL_set_session_doc},
2612 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2613 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002614 {NULL}, /* sentinel */
2615};
2616
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002617static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002618 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2619 _SSL__SSLSOCKET_WRITE_METHODDEF
2620 _SSL__SSLSOCKET_READ_METHODDEF
2621 _SSL__SSLSOCKET_PENDING_METHODDEF
2622 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2623 _SSL__SSLSOCKET_CIPHER_METHODDEF
2624 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2625 _SSL__SSLSOCKET_VERSION_METHODDEF
2626 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2627 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2628 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2629 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2630 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002631 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002632};
2633
Antoine Pitrou152efa22010-05-16 18:19:27 +00002634static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002635 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002636 "_ssl._SSLSocket", /*tp_name*/
2637 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002638 0, /*tp_itemsize*/
2639 /* methods */
2640 (destructor)PySSL_dealloc, /*tp_dealloc*/
2641 0, /*tp_print*/
2642 0, /*tp_getattr*/
2643 0, /*tp_setattr*/
2644 0, /*tp_reserved*/
2645 0, /*tp_repr*/
2646 0, /*tp_as_number*/
2647 0, /*tp_as_sequence*/
2648 0, /*tp_as_mapping*/
2649 0, /*tp_hash*/
2650 0, /*tp_call*/
2651 0, /*tp_str*/
2652 0, /*tp_getattro*/
2653 0, /*tp_setattro*/
2654 0, /*tp_as_buffer*/
2655 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2656 0, /*tp_doc*/
2657 0, /*tp_traverse*/
2658 0, /*tp_clear*/
2659 0, /*tp_richcompare*/
2660 0, /*tp_weaklistoffset*/
2661 0, /*tp_iter*/
2662 0, /*tp_iternext*/
2663 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002664 0, /*tp_members*/
2665 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002666};
2667
Antoine Pitrou152efa22010-05-16 18:19:27 +00002668
2669/*
2670 * _SSLContext objects
2671 */
2672
Christian Heimes5fe668c2016-09-12 00:01:11 +02002673static int
2674_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2675{
2676 int mode;
2677 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2678
2679 switch(n) {
2680 case PY_SSL_CERT_NONE:
2681 mode = SSL_VERIFY_NONE;
2682 break;
2683 case PY_SSL_CERT_OPTIONAL:
2684 mode = SSL_VERIFY_PEER;
2685 break;
2686 case PY_SSL_CERT_REQUIRED:
2687 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2688 break;
2689 default:
2690 PyErr_SetString(PyExc_ValueError,
2691 "invalid value for verify_mode");
2692 return -1;
2693 }
2694 /* keep current verify cb */
2695 verify_cb = SSL_CTX_get_verify_callback(ctx);
2696 SSL_CTX_set_verify(ctx, mode, verify_cb);
2697 return 0;
2698}
2699
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002700/*[clinic input]
2701@classmethod
2702_ssl._SSLContext.__new__
2703 protocol as proto_version: int
2704 /
2705[clinic start generated code]*/
2706
Antoine Pitrou152efa22010-05-16 18:19:27 +00002707static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002708_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2709/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002710{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002711 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002712 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002713 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002714 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002715#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002716 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002717#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002718
Antoine Pitrou152efa22010-05-16 18:19:27 +00002719 PySSL_BEGIN_ALLOW_THREADS
2720 if (proto_version == PY_SSL_VERSION_TLS1)
2721 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002722#if HAVE_TLSv1_2
2723 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2724 ctx = SSL_CTX_new(TLSv1_1_method());
2725 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2726 ctx = SSL_CTX_new(TLSv1_2_method());
2727#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002728#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002729 else if (proto_version == PY_SSL_VERSION_SSL3)
2730 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002731#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002732#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002733 else if (proto_version == PY_SSL_VERSION_SSL2)
2734 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002735#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002736 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002737 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002738 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2739 ctx = SSL_CTX_new(TLS_client_method());
2740 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2741 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002742 else
2743 proto_version = -1;
2744 PySSL_END_ALLOW_THREADS
2745
2746 if (proto_version == -1) {
2747 PyErr_SetString(PyExc_ValueError,
2748 "invalid protocol version");
2749 return NULL;
2750 }
2751 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002752 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002753 return NULL;
2754 }
2755
2756 assert(type != NULL && type->tp_alloc != NULL);
2757 self = (PySSLContext *) type->tp_alloc(type, 0);
2758 if (self == NULL) {
2759 SSL_CTX_free(ctx);
2760 return NULL;
2761 }
2762 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002763#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002764 self->npn_protocols = NULL;
2765#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002766#ifdef HAVE_ALPN
2767 self->alpn_protocols = NULL;
2768#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002769#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002770 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002771#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002772 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002773 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2774 self->check_hostname = 1;
2775 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2776 Py_DECREF(self);
2777 return NULL;
2778 }
2779 } else {
2780 self->check_hostname = 0;
2781 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2782 Py_DECREF(self);
2783 return NULL;
2784 }
2785 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002786 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002787 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2788 if (proto_version != PY_SSL_VERSION_SSL2)
2789 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002790 if (proto_version != PY_SSL_VERSION_SSL3)
2791 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002792 /* Minimal security flags for server and client side context.
2793 * Client sockets ignore server-side parameters. */
2794#ifdef SSL_OP_NO_COMPRESSION
2795 options |= SSL_OP_NO_COMPRESSION;
2796#endif
2797#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2798 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2799#endif
2800#ifdef SSL_OP_SINGLE_DH_USE
2801 options |= SSL_OP_SINGLE_DH_USE;
2802#endif
2803#ifdef SSL_OP_SINGLE_ECDH_USE
2804 options |= SSL_OP_SINGLE_ECDH_USE;
2805#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002806 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002807
Semen Zhydenko1295e112017-10-15 21:28:31 +02002808 /* A bare minimum cipher list without completely broken cipher suites.
Christian Heimes358cfd42016-09-10 22:43:48 +02002809 * It's far from perfect but gives users a better head start. */
2810 if (proto_version != PY_SSL_VERSION_SSL2) {
2811 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2812 } else {
2813 /* SSLv2 needs MD5 */
2814 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2815 }
2816 if (result == 0) {
2817 Py_DECREF(self);
2818 ERR_clear_error();
2819 PyErr_SetString(PySSLErrorObject,
2820 "No cipher can be selected.");
2821 return NULL;
2822 }
2823
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002824#if defined(SSL_MODE_RELEASE_BUFFERS)
2825 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2826 usage for no cost at all. However, don't do this for OpenSSL versions
2827 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2828 2014-0198. I can't find exactly which beta fixed this CVE, so be
2829 conservative and assume it wasn't fixed until release. We do this check
2830 at runtime to avoid problems from the dynamic linker.
2831 See #25672 for more on this. */
2832 libver = SSLeay();
2833 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2834 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2835 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2836 }
2837#endif
2838
2839
Donald Stufft8ae264c2017-03-02 11:45:29 -05002840#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002841 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2842 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002843 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2844 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002845#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002846 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2847#else
2848 {
2849 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2850 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2851 EC_KEY_free(key);
2852 }
2853#endif
2854#endif
2855
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002856#define SID_CTX "Python"
2857 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2858 sizeof(SID_CTX));
2859#undef SID_CTX
2860
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002861#ifdef X509_V_FLAG_TRUSTED_FIRST
2862 {
2863 /* Improve trust chain building when cross-signed intermediate
2864 certificates are present. See https://bugs.python.org/issue23476. */
2865 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2866 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2867 }
2868#endif
2869
Antoine Pitrou152efa22010-05-16 18:19:27 +00002870 return (PyObject *)self;
2871}
2872
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002873static int
2874context_traverse(PySSLContext *self, visitproc visit, void *arg)
2875{
2876#ifndef OPENSSL_NO_TLSEXT
2877 Py_VISIT(self->set_hostname);
2878#endif
2879 return 0;
2880}
2881
2882static int
2883context_clear(PySSLContext *self)
2884{
2885#ifndef OPENSSL_NO_TLSEXT
2886 Py_CLEAR(self->set_hostname);
2887#endif
2888 return 0;
2889}
2890
Antoine Pitrou152efa22010-05-16 18:19:27 +00002891static void
2892context_dealloc(PySSLContext *self)
2893{
INADA Naokia6296d32017-08-24 14:55:17 +09002894 /* bpo-31095: UnTrack is needed before calling any callbacks */
2895 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002896 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002898#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002899 PyMem_FREE(self->npn_protocols);
2900#endif
2901#ifdef HAVE_ALPN
2902 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002903#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002904 Py_TYPE(self)->tp_free(self);
2905}
2906
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002907/*[clinic input]
2908_ssl._SSLContext.set_ciphers
2909 cipherlist: str
2910 /
2911[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002912
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002913static PyObject *
2914_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2915/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2916{
2917 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002918 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002919 /* Clearing the error queue is necessary on some OpenSSL versions,
2920 otherwise the error will be reported again when another SSL call
2921 is done. */
2922 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002923 PyErr_SetString(PySSLErrorObject,
2924 "No cipher can be selected.");
2925 return NULL;
2926 }
2927 Py_RETURN_NONE;
2928}
2929
Christian Heimes25bfcd52016-09-06 00:04:45 +02002930#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2931/*[clinic input]
2932_ssl._SSLContext.get_ciphers
2933[clinic start generated code]*/
2934
2935static PyObject *
2936_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2937/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2938{
2939 SSL *ssl = NULL;
2940 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002941 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002942 int i=0;
2943 PyObject *result = NULL, *dct;
2944
2945 ssl = SSL_new(self->ctx);
2946 if (ssl == NULL) {
2947 _setSSLError(NULL, 0, __FILE__, __LINE__);
2948 goto exit;
2949 }
2950 sk = SSL_get_ciphers(ssl);
2951
2952 result = PyList_New(sk_SSL_CIPHER_num(sk));
2953 if (result == NULL) {
2954 goto exit;
2955 }
2956
2957 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2958 cipher = sk_SSL_CIPHER_value(sk, i);
2959 dct = cipher_to_dict(cipher);
2960 if (dct == NULL) {
2961 Py_CLEAR(result);
2962 goto exit;
2963 }
2964 PyList_SET_ITEM(result, i, dct);
2965 }
2966
2967 exit:
2968 if (ssl != NULL)
2969 SSL_free(ssl);
2970 return result;
2971
2972}
2973#endif
2974
2975
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002976#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002977static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002978do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2979 const unsigned char *server_protocols, unsigned int server_protocols_len,
2980 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002981{
Benjamin Peterson88615022015-01-23 17:30:26 -05002982 int ret;
2983 if (client_protocols == NULL) {
2984 client_protocols = (unsigned char *)"";
2985 client_protocols_len = 0;
2986 }
2987 if (server_protocols == NULL) {
2988 server_protocols = (unsigned char *)"";
2989 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002990 }
2991
Benjamin Peterson88615022015-01-23 17:30:26 -05002992 ret = SSL_select_next_proto(out, outlen,
2993 server_protocols, server_protocols_len,
2994 client_protocols, client_protocols_len);
2995 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2996 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002997
2998 return SSL_TLSEXT_ERR_OK;
2999}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003000#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05003001
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003002#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003003/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
3004static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003005_advertiseNPN_cb(SSL *s,
3006 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003007 void *args)
3008{
3009 PySSLContext *ssl_ctx = (PySSLContext *) args;
3010
3011 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003012 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003013 *len = 0;
3014 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003015 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003016 *len = ssl_ctx->npn_protocols_len;
3017 }
3018
3019 return SSL_TLSEXT_ERR_OK;
3020}
3021/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3022static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003023_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003024 unsigned char **out, unsigned char *outlen,
3025 const unsigned char *server, unsigned int server_len,
3026 void *args)
3027{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003028 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003029 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003030 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003031}
3032#endif
3033
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003034/*[clinic input]
3035_ssl._SSLContext._set_npn_protocols
3036 protos: Py_buffer
3037 /
3038[clinic start generated code]*/
3039
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003040static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003041_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3042 Py_buffer *protos)
3043/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003044{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003045#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003046 PyMem_Free(self->npn_protocols);
3047 self->npn_protocols = PyMem_Malloc(protos->len);
3048 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003049 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003050 memcpy(self->npn_protocols, protos->buf, protos->len);
3051 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003052
3053 /* set both server and client callbacks, because the context can
3054 * be used to create both types of sockets */
3055 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3056 _advertiseNPN_cb,
3057 self);
3058 SSL_CTX_set_next_proto_select_cb(self->ctx,
3059 _selectNPN_cb,
3060 self);
3061
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003062 Py_RETURN_NONE;
3063#else
3064 PyErr_SetString(PyExc_NotImplementedError,
3065 "The NPN extension requires OpenSSL 1.0.1 or later.");
3066 return NULL;
3067#endif
3068}
3069
Benjamin Petersoncca27322015-01-23 16:35:37 -05003070#ifdef HAVE_ALPN
3071static int
3072_selectALPN_cb(SSL *s,
3073 const unsigned char **out, unsigned char *outlen,
3074 const unsigned char *client_protocols, unsigned int client_protocols_len,
3075 void *args)
3076{
3077 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003078 return do_protocol_selection(1, (unsigned char **)out, outlen,
3079 ctx->alpn_protocols, ctx->alpn_protocols_len,
3080 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003081}
3082#endif
3083
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003084/*[clinic input]
3085_ssl._SSLContext._set_alpn_protocols
3086 protos: Py_buffer
3087 /
3088[clinic start generated code]*/
3089
Benjamin Petersoncca27322015-01-23 16:35:37 -05003090static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003091_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3092 Py_buffer *protos)
3093/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003094{
3095#ifdef HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003096 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003097 PyErr_Format(PyExc_OverflowError,
3098 "protocols longer than %d bytes", UINT_MAX);
3099 return NULL;
3100 }
3101
Benjamin Petersoncca27322015-01-23 16:35:37 -05003102 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003103 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003104 if (!self->alpn_protocols)
3105 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003106 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003107 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003108
3109 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3110 return PyErr_NoMemory();
3111 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3112
Benjamin Petersoncca27322015-01-23 16:35:37 -05003113 Py_RETURN_NONE;
3114#else
3115 PyErr_SetString(PyExc_NotImplementedError,
3116 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3117 return NULL;
3118#endif
3119}
3120
Antoine Pitrou152efa22010-05-16 18:19:27 +00003121static PyObject *
3122get_verify_mode(PySSLContext *self, void *c)
3123{
3124 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3125 case SSL_VERIFY_NONE:
3126 return PyLong_FromLong(PY_SSL_CERT_NONE);
3127 case SSL_VERIFY_PEER:
3128 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3129 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3130 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3131 }
3132 PyErr_SetString(PySSLErrorObject,
3133 "invalid return value from SSL_CTX_get_verify_mode");
3134 return NULL;
3135}
3136
3137static int
3138set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3139{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003140 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003141 if (!PyArg_Parse(arg, "i", &n))
3142 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003143 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003144 PyErr_SetString(PyExc_ValueError,
3145 "Cannot set verify_mode to CERT_NONE when "
3146 "check_hostname is enabled.");
3147 return -1;
3148 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003149 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003150}
3151
3152static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003153get_verify_flags(PySSLContext *self, void *c)
3154{
3155 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003156 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003157 unsigned long flags;
3158
3159 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003160 param = X509_STORE_get0_param(store);
3161 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003162 return PyLong_FromUnsignedLong(flags);
3163}
3164
3165static int
3166set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3167{
3168 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003169 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003170 unsigned long new_flags, flags, set, clear;
3171
3172 if (!PyArg_Parse(arg, "k", &new_flags))
3173 return -1;
3174 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003175 param = X509_STORE_get0_param(store);
3176 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003177 clear = flags & ~new_flags;
3178 set = ~flags & new_flags;
3179 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003180 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003181 _setSSLError(NULL, 0, __FILE__, __LINE__);
3182 return -1;
3183 }
3184 }
3185 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003186 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003187 _setSSLError(NULL, 0, __FILE__, __LINE__);
3188 return -1;
3189 }
3190 }
3191 return 0;
3192}
3193
3194static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003195get_options(PySSLContext *self, void *c)
3196{
3197 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3198}
3199
3200static int
3201set_options(PySSLContext *self, PyObject *arg, void *c)
3202{
3203 long new_opts, opts, set, clear;
3204 if (!PyArg_Parse(arg, "l", &new_opts))
3205 return -1;
3206 opts = SSL_CTX_get_options(self->ctx);
3207 clear = opts & ~new_opts;
3208 set = ~opts & new_opts;
3209 if (clear) {
3210#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3211 SSL_CTX_clear_options(self->ctx, clear);
3212#else
3213 PyErr_SetString(PyExc_ValueError,
3214 "can't clear options before OpenSSL 0.9.8m");
3215 return -1;
3216#endif
3217 }
3218 if (set)
3219 SSL_CTX_set_options(self->ctx, set);
3220 return 0;
3221}
3222
Christian Heimes1aa9a752013-12-02 02:41:19 +01003223static PyObject *
3224get_check_hostname(PySSLContext *self, void *c)
3225{
3226 return PyBool_FromLong(self->check_hostname);
3227}
3228
3229static int
3230set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3231{
3232 int check_hostname;
3233 if (!PyArg_Parse(arg, "p", &check_hostname))
3234 return -1;
3235 if (check_hostname &&
3236 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003237 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3238 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3239 return -1;
3240 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003241 }
3242 self->check_hostname = check_hostname;
3243 return 0;
3244}
3245
3246
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003247typedef struct {
3248 PyThreadState *thread_state;
3249 PyObject *callable;
3250 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003251 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003252 int error;
3253} _PySSLPasswordInfo;
3254
3255static int
3256_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3257 const char *bad_type_error)
3258{
3259 /* Set the password and size fields of a _PySSLPasswordInfo struct
3260 from a unicode, bytes, or byte array object.
3261 The password field will be dynamically allocated and must be freed
3262 by the caller */
3263 PyObject *password_bytes = NULL;
3264 const char *data = NULL;
3265 Py_ssize_t size;
3266
3267 if (PyUnicode_Check(password)) {
3268 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3269 if (!password_bytes) {
3270 goto error;
3271 }
3272 data = PyBytes_AS_STRING(password_bytes);
3273 size = PyBytes_GET_SIZE(password_bytes);
3274 } else if (PyBytes_Check(password)) {
3275 data = PyBytes_AS_STRING(password);
3276 size = PyBytes_GET_SIZE(password);
3277 } else if (PyByteArray_Check(password)) {
3278 data = PyByteArray_AS_STRING(password);
3279 size = PyByteArray_GET_SIZE(password);
3280 } else {
3281 PyErr_SetString(PyExc_TypeError, bad_type_error);
3282 goto error;
3283 }
3284
Victor Stinner9ee02032013-06-23 15:08:23 +02003285 if (size > (Py_ssize_t)INT_MAX) {
3286 PyErr_Format(PyExc_ValueError,
3287 "password cannot be longer than %d bytes", INT_MAX);
3288 goto error;
3289 }
3290
Victor Stinner11ebff22013-07-07 17:07:52 +02003291 PyMem_Free(pw_info->password);
3292 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003293 if (!pw_info->password) {
3294 PyErr_SetString(PyExc_MemoryError,
3295 "unable to allocate password buffer");
3296 goto error;
3297 }
3298 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003299 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003300
3301 Py_XDECREF(password_bytes);
3302 return 1;
3303
3304error:
3305 Py_XDECREF(password_bytes);
3306 return 0;
3307}
3308
3309static int
3310_password_callback(char *buf, int size, int rwflag, void *userdata)
3311{
3312 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3313 PyObject *fn_ret = NULL;
3314
3315 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3316
3317 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003318 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003319 if (!fn_ret) {
3320 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3321 core python API, so we could use it to add a frame here */
3322 goto error;
3323 }
3324
3325 if (!_pwinfo_set(pw_info, fn_ret,
3326 "password callback must return a string")) {
3327 goto error;
3328 }
3329 Py_CLEAR(fn_ret);
3330 }
3331
3332 if (pw_info->size > size) {
3333 PyErr_Format(PyExc_ValueError,
3334 "password cannot be longer than %d bytes", size);
3335 goto error;
3336 }
3337
3338 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3339 memcpy(buf, pw_info->password, pw_info->size);
3340 return pw_info->size;
3341
3342error:
3343 Py_XDECREF(fn_ret);
3344 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3345 pw_info->error = 1;
3346 return -1;
3347}
3348
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003349/*[clinic input]
3350_ssl._SSLContext.load_cert_chain
3351 certfile: object
3352 keyfile: object = NULL
3353 password: object = NULL
3354
3355[clinic start generated code]*/
3356
Antoine Pitroub5218772010-05-21 09:56:06 +00003357static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003358_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3359 PyObject *keyfile, PyObject *password)
3360/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003361{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003362 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003363 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3364 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003365 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003366 int r;
3367
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003368 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003369 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003370 if (keyfile == Py_None)
3371 keyfile = NULL;
3372 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3373 PyErr_SetString(PyExc_TypeError,
3374 "certfile should be a valid filesystem path");
3375 return NULL;
3376 }
3377 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3378 PyErr_SetString(PyExc_TypeError,
3379 "keyfile should be a valid filesystem path");
3380 goto error;
3381 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003382 if (password && password != Py_None) {
3383 if (PyCallable_Check(password)) {
3384 pw_info.callable = password;
3385 } else if (!_pwinfo_set(&pw_info, password,
3386 "password should be a string or callable")) {
3387 goto error;
3388 }
3389 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3390 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3391 }
3392 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003393 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3394 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003395 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003396 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003397 if (pw_info.error) {
3398 ERR_clear_error();
3399 /* the password callback has already set the error information */
3400 }
3401 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003402 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003403 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003404 }
3405 else {
3406 _setSSLError(NULL, 0, __FILE__, __LINE__);
3407 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003408 goto error;
3409 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003410 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003411 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003412 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3413 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003414 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3415 Py_CLEAR(keyfile_bytes);
3416 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003417 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003418 if (pw_info.error) {
3419 ERR_clear_error();
3420 /* the password callback has already set the error information */
3421 }
3422 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003423 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003424 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003425 }
3426 else {
3427 _setSSLError(NULL, 0, __FILE__, __LINE__);
3428 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003429 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003430 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003431 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003432 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003433 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434 if (r != 1) {
3435 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003436 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003437 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003438 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3439 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003440 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003441 Py_RETURN_NONE;
3442
3443error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003444 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3445 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003446 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003447 Py_XDECREF(keyfile_bytes);
3448 Py_XDECREF(certfile_bytes);
3449 return NULL;
3450}
3451
Christian Heimesefff7062013-11-21 03:35:02 +01003452/* internal helper function, returns -1 on error
3453 */
3454static int
3455_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3456 int filetype)
3457{
3458 BIO *biobuf = NULL;
3459 X509_STORE *store;
3460 int retval = 0, err, loaded = 0;
3461
3462 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3463
3464 if (len <= 0) {
3465 PyErr_SetString(PyExc_ValueError,
3466 "Empty certificate data");
3467 return -1;
3468 } else if (len > INT_MAX) {
3469 PyErr_SetString(PyExc_OverflowError,
3470 "Certificate data is too long.");
3471 return -1;
3472 }
3473
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003474 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003475 if (biobuf == NULL) {
3476 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3477 return -1;
3478 }
3479
3480 store = SSL_CTX_get_cert_store(self->ctx);
3481 assert(store != NULL);
3482
3483 while (1) {
3484 X509 *cert = NULL;
3485 int r;
3486
3487 if (filetype == SSL_FILETYPE_ASN1) {
3488 cert = d2i_X509_bio(biobuf, NULL);
3489 } else {
3490 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003491 SSL_CTX_get_default_passwd_cb(self->ctx),
3492 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3493 );
Christian Heimesefff7062013-11-21 03:35:02 +01003494 }
3495 if (cert == NULL) {
3496 break;
3497 }
3498 r = X509_STORE_add_cert(store, cert);
3499 X509_free(cert);
3500 if (!r) {
3501 err = ERR_peek_last_error();
3502 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3503 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3504 /* cert already in hash table, not an error */
3505 ERR_clear_error();
3506 } else {
3507 break;
3508 }
3509 }
3510 loaded++;
3511 }
3512
3513 err = ERR_peek_last_error();
3514 if ((filetype == SSL_FILETYPE_ASN1) &&
3515 (loaded > 0) &&
3516 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3517 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3518 /* EOF ASN1 file, not an error */
3519 ERR_clear_error();
3520 retval = 0;
3521 } else if ((filetype == SSL_FILETYPE_PEM) &&
3522 (loaded > 0) &&
3523 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3524 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3525 /* EOF PEM file, not an error */
3526 ERR_clear_error();
3527 retval = 0;
3528 } else {
3529 _setSSLError(NULL, 0, __FILE__, __LINE__);
3530 retval = -1;
3531 }
3532
3533 BIO_free(biobuf);
3534 return retval;
3535}
3536
3537
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003538/*[clinic input]
3539_ssl._SSLContext.load_verify_locations
3540 cafile: object = NULL
3541 capath: object = NULL
3542 cadata: object = NULL
3543
3544[clinic start generated code]*/
3545
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003547_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3548 PyObject *cafile,
3549 PyObject *capath,
3550 PyObject *cadata)
3551/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003552{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003553 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3554 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003555 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003556
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003557 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003558 if (cafile == Py_None)
3559 cafile = NULL;
3560 if (capath == Py_None)
3561 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003562 if (cadata == Py_None)
3563 cadata = NULL;
3564
3565 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003566 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003567 "cafile, capath and cadata cannot be all omitted");
3568 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003569 }
3570 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3571 PyErr_SetString(PyExc_TypeError,
3572 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003573 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003574 }
3575 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003576 PyErr_SetString(PyExc_TypeError,
3577 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003578 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003579 }
Christian Heimesefff7062013-11-21 03:35:02 +01003580
3581 /* validata cadata type and load cadata */
3582 if (cadata) {
3583 Py_buffer buf;
3584 PyObject *cadata_ascii = NULL;
3585
3586 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3587 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3588 PyBuffer_Release(&buf);
3589 PyErr_SetString(PyExc_TypeError,
3590 "cadata should be a contiguous buffer with "
3591 "a single dimension");
3592 goto error;
3593 }
3594 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3595 PyBuffer_Release(&buf);
3596 if (r == -1) {
3597 goto error;
3598 }
3599 } else {
3600 PyErr_Clear();
3601 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3602 if (cadata_ascii == NULL) {
3603 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003604 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003605 "bytes-like object");
3606 goto error;
3607 }
3608 r = _add_ca_certs(self,
3609 PyBytes_AS_STRING(cadata_ascii),
3610 PyBytes_GET_SIZE(cadata_ascii),
3611 SSL_FILETYPE_PEM);
3612 Py_DECREF(cadata_ascii);
3613 if (r == -1) {
3614 goto error;
3615 }
3616 }
3617 }
3618
3619 /* load cafile or capath */
3620 if (cafile || capath) {
3621 if (cafile)
3622 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3623 if (capath)
3624 capath_buf = PyBytes_AS_STRING(capath_bytes);
3625 PySSL_BEGIN_ALLOW_THREADS
3626 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3627 PySSL_END_ALLOW_THREADS
3628 if (r != 1) {
3629 ok = 0;
3630 if (errno != 0) {
3631 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003632 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003633 }
3634 else {
3635 _setSSLError(NULL, 0, __FILE__, __LINE__);
3636 }
3637 goto error;
3638 }
3639 }
3640 goto end;
3641
3642 error:
3643 ok = 0;
3644 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003645 Py_XDECREF(cafile_bytes);
3646 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003647 if (ok) {
3648 Py_RETURN_NONE;
3649 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003650 return NULL;
3651 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003652}
3653
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003654/*[clinic input]
3655_ssl._SSLContext.load_dh_params
3656 path as filepath: object
3657 /
3658
3659[clinic start generated code]*/
3660
Antoine Pitrou152efa22010-05-16 18:19:27 +00003661static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003662_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3663/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003664{
3665 FILE *f;
3666 DH *dh;
3667
Victor Stinnerdaf45552013-08-28 00:53:59 +02003668 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003669 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003670 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003671
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003672 errno = 0;
3673 PySSL_BEGIN_ALLOW_THREADS
3674 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003675 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003676 PySSL_END_ALLOW_THREADS
3677 if (dh == NULL) {
3678 if (errno != 0) {
3679 ERR_clear_error();
3680 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3681 }
3682 else {
3683 _setSSLError(NULL, 0, __FILE__, __LINE__);
3684 }
3685 return NULL;
3686 }
3687 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3688 _setSSLError(NULL, 0, __FILE__, __LINE__);
3689 DH_free(dh);
3690 Py_RETURN_NONE;
3691}
3692
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003693/*[clinic input]
3694_ssl._SSLContext._wrap_socket
3695 sock: object(subclass_of="PySocketModule.Sock_Type")
3696 server_side: int
3697 server_hostname as hostname_obj: object = None
3698
3699[clinic start generated code]*/
3700
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003701static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003702_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3703 int server_side, PyObject *hostname_obj)
3704/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003705{
Antoine Pitroud5323212010-10-22 18:19:07 +00003706 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003707 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708
Antoine Pitroud5323212010-10-22 18:19:07 +00003709 /* server_hostname is either None (or absent), or to be encoded
3710 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003711 if (hostname_obj != Py_None) {
3712 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003713 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003714 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003715
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003716 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3717 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003718 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003719 if (hostname != NULL)
3720 PyMem_Free(hostname);
3721 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003722}
3723
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003724/*[clinic input]
3725_ssl._SSLContext._wrap_bio
3726 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3727 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3728 server_side: int
3729 server_hostname as hostname_obj: object = None
3730
3731[clinic start generated code]*/
3732
Antoine Pitroub0182c82010-10-12 20:09:02 +00003733static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003734_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3735 PySSLMemoryBIO *outgoing, int server_side,
3736 PyObject *hostname_obj)
3737/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003738{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003739 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003740 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003741
3742 /* server_hostname is either None (or absent), or to be encoded
3743 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003744 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003745 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3746 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003747 }
3748
3749 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3750 incoming, outgoing);
3751
3752 PyMem_Free(hostname);
3753 return res;
3754}
3755
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003756/*[clinic input]
3757_ssl._SSLContext.session_stats
3758[clinic start generated code]*/
3759
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003760static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003761_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3762/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003763{
3764 int r;
3765 PyObject *value, *stats = PyDict_New();
3766 if (!stats)
3767 return NULL;
3768
3769#define ADD_STATS(SSL_NAME, KEY_NAME) \
3770 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3771 if (value == NULL) \
3772 goto error; \
3773 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3774 Py_DECREF(value); \
3775 if (r < 0) \
3776 goto error;
3777
3778 ADD_STATS(number, "number");
3779 ADD_STATS(connect, "connect");
3780 ADD_STATS(connect_good, "connect_good");
3781 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3782 ADD_STATS(accept, "accept");
3783 ADD_STATS(accept_good, "accept_good");
3784 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3785 ADD_STATS(accept, "accept");
3786 ADD_STATS(hits, "hits");
3787 ADD_STATS(misses, "misses");
3788 ADD_STATS(timeouts, "timeouts");
3789 ADD_STATS(cache_full, "cache_full");
3790
3791#undef ADD_STATS
3792
3793 return stats;
3794
3795error:
3796 Py_DECREF(stats);
3797 return NULL;
3798}
3799
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003800/*[clinic input]
3801_ssl._SSLContext.set_default_verify_paths
3802[clinic start generated code]*/
3803
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003804static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003805_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3806/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003807{
3808 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3809 _setSSLError(NULL, 0, __FILE__, __LINE__);
3810 return NULL;
3811 }
3812 Py_RETURN_NONE;
3813}
3814
Antoine Pitrou501da612011-12-21 09:27:41 +01003815#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003816/*[clinic input]
3817_ssl._SSLContext.set_ecdh_curve
3818 name: object
3819 /
3820
3821[clinic start generated code]*/
3822
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003823static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003824_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3825/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003826{
3827 PyObject *name_bytes;
3828 int nid;
3829 EC_KEY *key;
3830
3831 if (!PyUnicode_FSConverter(name, &name_bytes))
3832 return NULL;
3833 assert(PyBytes_Check(name_bytes));
3834 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3835 Py_DECREF(name_bytes);
3836 if (nid == 0) {
3837 PyErr_Format(PyExc_ValueError,
3838 "unknown elliptic curve name %R", name);
3839 return NULL;
3840 }
3841 key = EC_KEY_new_by_curve_name(nid);
3842 if (key == NULL) {
3843 _setSSLError(NULL, 0, __FILE__, __LINE__);
3844 return NULL;
3845 }
3846 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3847 EC_KEY_free(key);
3848 Py_RETURN_NONE;
3849}
Antoine Pitrou501da612011-12-21 09:27:41 +01003850#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003851
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003852#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003853static int
3854_servername_callback(SSL *s, int *al, void *args)
3855{
3856 int ret;
3857 PySSLContext *ssl_ctx = (PySSLContext *) args;
3858 PySSLSocket *ssl;
3859 PyObject *servername_o;
3860 PyObject *servername_idna;
3861 PyObject *result;
3862 /* The high-level ssl.SSLSocket object */
3863 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003864 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003865 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003866
3867 if (ssl_ctx->set_hostname == NULL) {
3868 /* remove race condition in this the call back while if removing the
3869 * callback is in progress */
3870 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003871 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003872 }
3873
3874 ssl = SSL_get_app_data(s);
3875 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003876
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003877 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003878 * SSL connection and that has a .context attribute that can be changed to
3879 * identify the requested hostname. Since the official API is the Python
3880 * level API we want to pass the callback a Python level object rather than
3881 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3882 * SSLObject) that will be passed. Otherwise if there's a socket then that
3883 * will be passed. If both do not exist only then the C-level object is
3884 * passed. */
3885 if (ssl->owner)
3886 ssl_socket = PyWeakref_GetObject(ssl->owner);
3887 else if (ssl->Socket)
3888 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3889 else
3890 ssl_socket = (PyObject *) ssl;
3891
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003892 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003893 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003894 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003895
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003896 if (servername == NULL) {
3897 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3898 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003899 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003900 else {
3901 servername_o = PyBytes_FromString(servername);
3902 if (servername_o == NULL) {
3903 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3904 goto error;
3905 }
3906 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3907 if (servername_idna == NULL) {
3908 PyErr_WriteUnraisable(servername_o);
3909 Py_DECREF(servername_o);
3910 goto error;
3911 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003912 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003913 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3914 servername_idna, ssl_ctx, NULL);
3915 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003916 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003917 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003918
3919 if (result == NULL) {
3920 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3921 *al = SSL_AD_HANDSHAKE_FAILURE;
3922 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3923 }
3924 else {
3925 if (result != Py_None) {
3926 *al = (int) PyLong_AsLong(result);
3927 if (PyErr_Occurred()) {
3928 PyErr_WriteUnraisable(result);
3929 *al = SSL_AD_INTERNAL_ERROR;
3930 }
3931 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3932 }
3933 else {
3934 ret = SSL_TLSEXT_ERR_OK;
3935 }
3936 Py_DECREF(result);
3937 }
3938
3939 PyGILState_Release(gstate);
3940 return ret;
3941
3942error:
3943 Py_DECREF(ssl_socket);
3944 *al = SSL_AD_INTERNAL_ERROR;
3945 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3946 PyGILState_Release(gstate);
3947 return ret;
3948}
Antoine Pitroua5963382013-03-30 16:39:00 +01003949#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003950
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003951/*[clinic input]
3952_ssl._SSLContext.set_servername_callback
3953 method as cb: object
3954 /
3955
3956Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3957
3958If the argument is None then the callback is disabled. The method is called
3959with the SSLSocket, the server name as a string, and the SSLContext object.
3960See RFC 6066 for details of the SNI extension.
3961[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003962
3963static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003964_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3965/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003966{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003967#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003968 Py_CLEAR(self->set_hostname);
3969 if (cb == Py_None) {
3970 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3971 }
3972 else {
3973 if (!PyCallable_Check(cb)) {
3974 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3975 PyErr_SetString(PyExc_TypeError,
3976 "not a callable object");
3977 return NULL;
3978 }
3979 Py_INCREF(cb);
3980 self->set_hostname = cb;
3981 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3982 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3983 }
3984 Py_RETURN_NONE;
3985#else
3986 PyErr_SetString(PyExc_NotImplementedError,
3987 "The TLS extension servername callback, "
3988 "SSL_CTX_set_tlsext_servername_callback, "
3989 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003990 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003991#endif
3992}
3993
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003994/*[clinic input]
3995_ssl._SSLContext.cert_store_stats
3996
3997Returns quantities of loaded X.509 certificates.
3998
3999X.509 certificates with a CA extension and certificate revocation lists
4000inside the context's cert store.
4001
4002NOTE: Certificates in a capath directory aren't loaded unless they have
4003been used at least once.
4004[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004005
4006static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004007_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4008/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004009{
4010 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004011 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004012 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004013 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004014
4015 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004016 objs = X509_STORE_get0_objects(store);
4017 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4018 obj = sk_X509_OBJECT_value(objs, i);
4019 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004020 case X509_LU_X509:
4021 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004022 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004023 ca++;
4024 }
4025 break;
4026 case X509_LU_CRL:
4027 crl++;
4028 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004029 default:
4030 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4031 * As far as I can tell they are internal states and never
4032 * stored in a cert store */
4033 break;
4034 }
4035 }
4036 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4037 "x509_ca", ca);
4038}
4039
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004040/*[clinic input]
4041_ssl._SSLContext.get_ca_certs
4042 binary_form: bool = False
4043
4044Returns a list of dicts with information of loaded CA certs.
4045
4046If the optional argument is True, returns a DER-encoded copy of the CA
4047certificate.
4048
4049NOTE: Certificates in a capath directory aren't loaded unless they have
4050been used at least once.
4051[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004052
4053static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004054_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4055/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004056{
4057 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004058 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004059 PyObject *ci = NULL, *rlist = NULL;
4060 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004061
4062 if ((rlist = PyList_New(0)) == NULL) {
4063 return NULL;
4064 }
4065
4066 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004067 objs = X509_STORE_get0_objects(store);
4068 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004069 X509_OBJECT *obj;
4070 X509 *cert;
4071
Christian Heimes598894f2016-09-05 23:19:05 +02004072 obj = sk_X509_OBJECT_value(objs, i);
4073 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004074 /* not a x509 cert */
4075 continue;
4076 }
4077 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004078 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004079 if (!X509_check_ca(cert)) {
4080 continue;
4081 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004082 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004083 ci = _certificate_to_der(cert);
4084 } else {
4085 ci = _decode_certificate(cert);
4086 }
4087 if (ci == NULL) {
4088 goto error;
4089 }
4090 if (PyList_Append(rlist, ci) == -1) {
4091 goto error;
4092 }
4093 Py_CLEAR(ci);
4094 }
4095 return rlist;
4096
4097 error:
4098 Py_XDECREF(ci);
4099 Py_XDECREF(rlist);
4100 return NULL;
4101}
4102
4103
Antoine Pitrou152efa22010-05-16 18:19:27 +00004104static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004105 {"check_hostname", (getter) get_check_hostname,
4106 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004107 {"options", (getter) get_options,
4108 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004109 {"verify_flags", (getter) get_verify_flags,
4110 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004111 {"verify_mode", (getter) get_verify_mode,
4112 (setter) set_verify_mode, NULL},
4113 {NULL}, /* sentinel */
4114};
4115
4116static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004117 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4118 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4119 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4120 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4121 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4122 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4123 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4124 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4125 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4126 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4127 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4128 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4129 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4130 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004131 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004132 {NULL, NULL} /* sentinel */
4133};
4134
4135static PyTypeObject PySSLContext_Type = {
4136 PyVarObject_HEAD_INIT(NULL, 0)
4137 "_ssl._SSLContext", /*tp_name*/
4138 sizeof(PySSLContext), /*tp_basicsize*/
4139 0, /*tp_itemsize*/
4140 (destructor)context_dealloc, /*tp_dealloc*/
4141 0, /*tp_print*/
4142 0, /*tp_getattr*/
4143 0, /*tp_setattr*/
4144 0, /*tp_reserved*/
4145 0, /*tp_repr*/
4146 0, /*tp_as_number*/
4147 0, /*tp_as_sequence*/
4148 0, /*tp_as_mapping*/
4149 0, /*tp_hash*/
4150 0, /*tp_call*/
4151 0, /*tp_str*/
4152 0, /*tp_getattro*/
4153 0, /*tp_setattro*/
4154 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004155 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004156 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004157 (traverseproc) context_traverse, /*tp_traverse*/
4158 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004159 0, /*tp_richcompare*/
4160 0, /*tp_weaklistoffset*/
4161 0, /*tp_iter*/
4162 0, /*tp_iternext*/
4163 context_methods, /*tp_methods*/
4164 0, /*tp_members*/
4165 context_getsetlist, /*tp_getset*/
4166 0, /*tp_base*/
4167 0, /*tp_dict*/
4168 0, /*tp_descr_get*/
4169 0, /*tp_descr_set*/
4170 0, /*tp_dictoffset*/
4171 0, /*tp_init*/
4172 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004173 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004174};
4175
4176
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004177/*
4178 * MemoryBIO objects
4179 */
4180
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181/*[clinic input]
4182@classmethod
4183_ssl.MemoryBIO.__new__
4184
4185[clinic start generated code]*/
4186
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004188_ssl_MemoryBIO_impl(PyTypeObject *type)
4189/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004190{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004191 BIO *bio;
4192 PySSLMemoryBIO *self;
4193
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004194 bio = BIO_new(BIO_s_mem());
4195 if (bio == NULL) {
4196 PyErr_SetString(PySSLErrorObject,
4197 "failed to allocate BIO");
4198 return NULL;
4199 }
4200 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4201 * just that no data is currently available. The SSL routines should retry
4202 * the read, which we can achieve by calling BIO_set_retry_read(). */
4203 BIO_set_retry_read(bio);
4204 BIO_set_mem_eof_return(bio, -1);
4205
4206 assert(type != NULL && type->tp_alloc != NULL);
4207 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4208 if (self == NULL) {
4209 BIO_free(bio);
4210 return NULL;
4211 }
4212 self->bio = bio;
4213 self->eof_written = 0;
4214
4215 return (PyObject *) self;
4216}
4217
4218static void
4219memory_bio_dealloc(PySSLMemoryBIO *self)
4220{
4221 BIO_free(self->bio);
4222 Py_TYPE(self)->tp_free(self);
4223}
4224
4225static PyObject *
4226memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4227{
Segev Finer5cff6372017-07-27 01:19:17 +03004228 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004229}
4230
4231PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4232"The number of bytes pending in the memory BIO.");
4233
4234static PyObject *
4235memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4236{
4237 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4238 && self->eof_written);
4239}
4240
4241PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4242"Whether the memory BIO is at EOF.");
4243
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004244/*[clinic input]
4245_ssl.MemoryBIO.read
4246 size as len: int = -1
4247 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004248
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004249Read up to size bytes from the memory BIO.
4250
4251If size is not specified, read the entire buffer.
4252If the return value is an empty bytes instance, this means either
4253EOF or that no data is available. Use the "eof" property to
4254distinguish between the two.
4255[clinic start generated code]*/
4256
4257static PyObject *
4258_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4259/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4260{
4261 int avail, nbytes;
4262 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004263
Segev Finer5cff6372017-07-27 01:19:17 +03004264 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004265 if ((len < 0) || (len > avail))
4266 len = avail;
4267
4268 result = PyBytes_FromStringAndSize(NULL, len);
4269 if ((result == NULL) || (len == 0))
4270 return result;
4271
4272 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4273 /* There should never be any short reads but check anyway. */
4274 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4275 Py_DECREF(result);
4276 return NULL;
4277 }
4278
4279 return result;
4280}
4281
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004282/*[clinic input]
4283_ssl.MemoryBIO.write
4284 b: Py_buffer
4285 /
4286
4287Writes the bytes b into the memory BIO.
4288
4289Returns the number of bytes written.
4290[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004291
4292static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004293_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4294/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004295{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004296 int nbytes;
4297
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004298 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004299 PyErr_Format(PyExc_OverflowError,
4300 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004301 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004302 }
4303
4304 if (self->eof_written) {
4305 PyErr_SetString(PySSLErrorObject,
4306 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004307 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004308 }
4309
Segev Finer5cff6372017-07-27 01:19:17 +03004310 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004311 if (nbytes < 0) {
4312 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004313 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004314 }
4315
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004316 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004317}
4318
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004319/*[clinic input]
4320_ssl.MemoryBIO.write_eof
4321
4322Write an EOF marker to the memory BIO.
4323
4324When all data has been read, the "eof" property will be True.
4325[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004326
4327static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004328_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4329/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004330{
4331 self->eof_written = 1;
4332 /* After an EOF is written, a zero return from read() should be a real EOF
4333 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4334 BIO_clear_retry_flags(self->bio);
4335 BIO_set_mem_eof_return(self->bio, 0);
4336
4337 Py_RETURN_NONE;
4338}
4339
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004340static PyGetSetDef memory_bio_getsetlist[] = {
4341 {"pending", (getter) memory_bio_get_pending, NULL,
4342 PySSL_memory_bio_pending_doc},
4343 {"eof", (getter) memory_bio_get_eof, NULL,
4344 PySSL_memory_bio_eof_doc},
4345 {NULL}, /* sentinel */
4346};
4347
4348static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004349 _SSL_MEMORYBIO_READ_METHODDEF
4350 _SSL_MEMORYBIO_WRITE_METHODDEF
4351 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004352 {NULL, NULL} /* sentinel */
4353};
4354
4355static PyTypeObject PySSLMemoryBIO_Type = {
4356 PyVarObject_HEAD_INIT(NULL, 0)
4357 "_ssl.MemoryBIO", /*tp_name*/
4358 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4359 0, /*tp_itemsize*/
4360 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4361 0, /*tp_print*/
4362 0, /*tp_getattr*/
4363 0, /*tp_setattr*/
4364 0, /*tp_reserved*/
4365 0, /*tp_repr*/
4366 0, /*tp_as_number*/
4367 0, /*tp_as_sequence*/
4368 0, /*tp_as_mapping*/
4369 0, /*tp_hash*/
4370 0, /*tp_call*/
4371 0, /*tp_str*/
4372 0, /*tp_getattro*/
4373 0, /*tp_setattro*/
4374 0, /*tp_as_buffer*/
4375 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4376 0, /*tp_doc*/
4377 0, /*tp_traverse*/
4378 0, /*tp_clear*/
4379 0, /*tp_richcompare*/
4380 0, /*tp_weaklistoffset*/
4381 0, /*tp_iter*/
4382 0, /*tp_iternext*/
4383 memory_bio_methods, /*tp_methods*/
4384 0, /*tp_members*/
4385 memory_bio_getsetlist, /*tp_getset*/
4386 0, /*tp_base*/
4387 0, /*tp_dict*/
4388 0, /*tp_descr_get*/
4389 0, /*tp_descr_set*/
4390 0, /*tp_dictoffset*/
4391 0, /*tp_init*/
4392 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004393 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004394};
4395
Antoine Pitrou152efa22010-05-16 18:19:27 +00004396
Christian Heimes99a65702016-09-10 23:44:53 +02004397/*
4398 * SSL Session object
4399 */
4400
4401static void
4402PySSLSession_dealloc(PySSLSession *self)
4403{
INADA Naokia6296d32017-08-24 14:55:17 +09004404 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004405 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004406 Py_XDECREF(self->ctx);
4407 if (self->session != NULL) {
4408 SSL_SESSION_free(self->session);
4409 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004410 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004411}
4412
4413static PyObject *
4414PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4415{
4416 int result;
4417
4418 if (left == NULL || right == NULL) {
4419 PyErr_BadInternalCall();
4420 return NULL;
4421 }
4422
4423 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4424 Py_RETURN_NOTIMPLEMENTED;
4425 }
4426
4427 if (left == right) {
4428 result = 0;
4429 } else {
4430 const unsigned char *left_id, *right_id;
4431 unsigned int left_len, right_len;
4432 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4433 &left_len);
4434 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4435 &right_len);
4436 if (left_len == right_len) {
4437 result = memcmp(left_id, right_id, left_len);
4438 } else {
4439 result = 1;
4440 }
4441 }
4442
4443 switch (op) {
4444 case Py_EQ:
4445 if (result == 0) {
4446 Py_RETURN_TRUE;
4447 } else {
4448 Py_RETURN_FALSE;
4449 }
4450 break;
4451 case Py_NE:
4452 if (result != 0) {
4453 Py_RETURN_TRUE;
4454 } else {
4455 Py_RETURN_FALSE;
4456 }
4457 break;
4458 case Py_LT:
4459 case Py_LE:
4460 case Py_GT:
4461 case Py_GE:
4462 Py_RETURN_NOTIMPLEMENTED;
4463 break;
4464 default:
4465 PyErr_BadArgument();
4466 return NULL;
4467 }
4468}
4469
4470static int
4471PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4472{
4473 Py_VISIT(self->ctx);
4474 return 0;
4475}
4476
4477static int
4478PySSLSession_clear(PySSLSession *self)
4479{
4480 Py_CLEAR(self->ctx);
4481 return 0;
4482}
4483
4484
4485static PyObject *
4486PySSLSession_get_time(PySSLSession *self, void *closure) {
4487 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4488}
4489
4490PyDoc_STRVAR(PySSLSession_get_time_doc,
4491"Session creation time (seconds since epoch).");
4492
4493
4494static PyObject *
4495PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4496 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4497}
4498
4499PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4500"Session timeout (delta in seconds).");
4501
4502
4503static PyObject *
4504PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4505 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4506 return PyLong_FromUnsignedLong(hint);
4507}
4508
4509PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4510"Ticket life time hint.");
4511
4512
4513static PyObject *
4514PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4515 const unsigned char *id;
4516 unsigned int len;
4517 id = SSL_SESSION_get_id(self->session, &len);
4518 return PyBytes_FromStringAndSize((const char *)id, len);
4519}
4520
4521PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4522"Session id");
4523
4524
4525static PyObject *
4526PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4527 if (SSL_SESSION_has_ticket(self->session)) {
4528 Py_RETURN_TRUE;
4529 } else {
4530 Py_RETURN_FALSE;
4531 }
4532}
4533
4534PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4535"Does the session contain a ticket?");
4536
4537
4538static PyGetSetDef PySSLSession_getsetlist[] = {
4539 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4540 PySSLSession_get_has_ticket_doc},
4541 {"id", (getter) PySSLSession_get_session_id, NULL,
4542 PySSLSession_get_session_id_doc},
4543 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4544 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4545 {"time", (getter) PySSLSession_get_time, NULL,
4546 PySSLSession_get_time_doc},
4547 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4548 PySSLSession_get_timeout_doc},
4549 {NULL}, /* sentinel */
4550};
4551
4552static PyTypeObject PySSLSession_Type = {
4553 PyVarObject_HEAD_INIT(NULL, 0)
4554 "_ssl.Session", /*tp_name*/
4555 sizeof(PySSLSession), /*tp_basicsize*/
4556 0, /*tp_itemsize*/
4557 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4558 0, /*tp_print*/
4559 0, /*tp_getattr*/
4560 0, /*tp_setattr*/
4561 0, /*tp_reserved*/
4562 0, /*tp_repr*/
4563 0, /*tp_as_number*/
4564 0, /*tp_as_sequence*/
4565 0, /*tp_as_mapping*/
4566 0, /*tp_hash*/
4567 0, /*tp_call*/
4568 0, /*tp_str*/
4569 0, /*tp_getattro*/
4570 0, /*tp_setattro*/
4571 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004572 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004573 0, /*tp_doc*/
4574 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4575 (inquiry)PySSLSession_clear, /*tp_clear*/
4576 PySSLSession_richcompare, /*tp_richcompare*/
4577 0, /*tp_weaklistoffset*/
4578 0, /*tp_iter*/
4579 0, /*tp_iternext*/
4580 0, /*tp_methods*/
4581 0, /*tp_members*/
4582 PySSLSession_getsetlist, /*tp_getset*/
4583};
4584
4585
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004586/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004587/*[clinic input]
4588_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004589 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004590 entropy: double
4591 /
4592
4593Mix string into the OpenSSL PRNG state.
4594
4595entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304596string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004597[clinic start generated code]*/
4598
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004599static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004600_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004601/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004602{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004603 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004604 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004605
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004606 buf = (const char *)view->buf;
4607 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004608 do {
4609 written = Py_MIN(len, INT_MAX);
4610 RAND_add(buf, (int)written, entropy);
4611 buf += written;
4612 len -= written;
4613 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004614 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004615}
4616
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004617static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004618PySSL_RAND(int len, int pseudo)
4619{
4620 int ok;
4621 PyObject *bytes;
4622 unsigned long err;
4623 const char *errstr;
4624 PyObject *v;
4625
Victor Stinner1e81a392013-12-19 16:47:04 +01004626 if (len < 0) {
4627 PyErr_SetString(PyExc_ValueError, "num must be positive");
4628 return NULL;
4629 }
4630
Victor Stinner99c8b162011-05-24 12:05:19 +02004631 bytes = PyBytes_FromStringAndSize(NULL, len);
4632 if (bytes == NULL)
4633 return NULL;
4634 if (pseudo) {
4635 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4636 if (ok == 0 || ok == 1)
4637 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4638 }
4639 else {
4640 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4641 if (ok == 1)
4642 return bytes;
4643 }
4644 Py_DECREF(bytes);
4645
4646 err = ERR_get_error();
4647 errstr = ERR_reason_error_string(err);
4648 v = Py_BuildValue("(ks)", err, errstr);
4649 if (v != NULL) {
4650 PyErr_SetObject(PySSLErrorObject, v);
4651 Py_DECREF(v);
4652 }
4653 return NULL;
4654}
4655
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004656/*[clinic input]
4657_ssl.RAND_bytes
4658 n: int
4659 /
4660
4661Generate n cryptographically strong pseudo-random bytes.
4662[clinic start generated code]*/
4663
Victor Stinner99c8b162011-05-24 12:05:19 +02004664static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004665_ssl_RAND_bytes_impl(PyObject *module, int n)
4666/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004667{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004668 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004669}
4670
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004671/*[clinic input]
4672_ssl.RAND_pseudo_bytes
4673 n: int
4674 /
4675
4676Generate n pseudo-random bytes.
4677
4678Return a pair (bytes, is_cryptographic). is_cryptographic is True
4679if the bytes generated are cryptographically strong.
4680[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004681
4682static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004683_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4684/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004685{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004686 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004687}
4688
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004689/*[clinic input]
4690_ssl.RAND_status
4691
4692Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4693
4694It is necessary to seed the PRNG with RAND_add() on some platforms before
4695using the ssl() function.
4696[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004697
4698static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004699_ssl_RAND_status_impl(PyObject *module)
4700/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004701{
Christian Heimes217cfd12007-12-02 14:31:20 +00004702 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004703}
4704
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004705#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004706/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004707/*[clinic input]
4708_ssl.RAND_egd
4709 path: object(converter="PyUnicode_FSConverter")
4710 /
4711
4712Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4713
4714Returns number of bytes read. Raises SSLError if connection to EGD
4715fails or if it does not provide enough data to seed PRNG.
4716[clinic start generated code]*/
4717
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004718static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004719_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4720/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004721{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004722 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004723 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004724 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004725 PyErr_SetString(PySSLErrorObject,
4726 "EGD connection failed or EGD did not return "
4727 "enough data to seed the PRNG");
4728 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004729 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004730 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004731}
Christian Heimesa5d07652016-09-24 10:48:05 +02004732/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004733#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004734
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004735
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004736
4737/*[clinic input]
4738_ssl.get_default_verify_paths
4739
4740Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4741
4742The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4743[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004744
4745static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004746_ssl_get_default_verify_paths_impl(PyObject *module)
4747/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004748{
4749 PyObject *ofile_env = NULL;
4750 PyObject *ofile = NULL;
4751 PyObject *odir_env = NULL;
4752 PyObject *odir = NULL;
4753
Benjamin Petersond113c962015-07-18 10:59:13 -07004754#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004755 const char *tmp = (info); \
4756 target = NULL; \
4757 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4758 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4759 target = PyBytes_FromString(tmp); } \
4760 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004761 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004762
Benjamin Petersond113c962015-07-18 10:59:13 -07004763 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4764 CONVERT(X509_get_default_cert_file(), ofile);
4765 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4766 CONVERT(X509_get_default_cert_dir(), odir);
4767#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004768
Christian Heimes200bb1b2013-06-14 15:14:29 +02004769 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004770
4771 error:
4772 Py_XDECREF(ofile_env);
4773 Py_XDECREF(ofile);
4774 Py_XDECREF(odir_env);
4775 Py_XDECREF(odir);
4776 return NULL;
4777}
4778
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004779static PyObject*
4780asn1obj2py(ASN1_OBJECT *obj)
4781{
4782 int nid;
4783 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004784
4785 nid = OBJ_obj2nid(obj);
4786 if (nid == NID_undef) {
4787 PyErr_Format(PyExc_ValueError, "Unknown object");
4788 return NULL;
4789 }
4790 sn = OBJ_nid2sn(nid);
4791 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004792 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004793}
4794
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004795/*[clinic input]
4796_ssl.txt2obj
4797 txt: str
4798 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004799
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004800Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4801
4802By default objects are looked up by OID. With name=True short and
4803long name are also matched.
4804[clinic start generated code]*/
4805
4806static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004807_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4808/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004809{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004810 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004811 ASN1_OBJECT *obj;
4812
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004813 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4814 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004815 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004816 return NULL;
4817 }
4818 result = asn1obj2py(obj);
4819 ASN1_OBJECT_free(obj);
4820 return result;
4821}
4822
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004823/*[clinic input]
4824_ssl.nid2obj
4825 nid: int
4826 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004827
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004828Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4829[clinic start generated code]*/
4830
4831static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004832_ssl_nid2obj_impl(PyObject *module, int nid)
4833/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004834{
4835 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004836 ASN1_OBJECT *obj;
4837
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004838 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004839 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004840 return NULL;
4841 }
4842 obj = OBJ_nid2obj(nid);
4843 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004844 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004845 return NULL;
4846 }
4847 result = asn1obj2py(obj);
4848 ASN1_OBJECT_free(obj);
4849 return result;
4850}
4851
Christian Heimes46bebee2013-06-09 19:03:31 +02004852#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004853
4854static PyObject*
4855certEncodingType(DWORD encodingType)
4856{
4857 static PyObject *x509_asn = NULL;
4858 static PyObject *pkcs_7_asn = NULL;
4859
4860 if (x509_asn == NULL) {
4861 x509_asn = PyUnicode_InternFromString("x509_asn");
4862 if (x509_asn == NULL)
4863 return NULL;
4864 }
4865 if (pkcs_7_asn == NULL) {
4866 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4867 if (pkcs_7_asn == NULL)
4868 return NULL;
4869 }
4870 switch(encodingType) {
4871 case X509_ASN_ENCODING:
4872 Py_INCREF(x509_asn);
4873 return x509_asn;
4874 case PKCS_7_ASN_ENCODING:
4875 Py_INCREF(pkcs_7_asn);
4876 return pkcs_7_asn;
4877 default:
4878 return PyLong_FromLong(encodingType);
4879 }
4880}
4881
4882static PyObject*
4883parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4884{
4885 CERT_ENHKEY_USAGE *usage;
4886 DWORD size, error, i;
4887 PyObject *retval;
4888
4889 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4890 error = GetLastError();
4891 if (error == CRYPT_E_NOT_FOUND) {
4892 Py_RETURN_TRUE;
4893 }
4894 return PyErr_SetFromWindowsErr(error);
4895 }
4896
4897 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4898 if (usage == NULL) {
4899 return PyErr_NoMemory();
4900 }
4901
4902 /* Now get the actual enhanced usage property */
4903 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4904 PyMem_Free(usage);
4905 error = GetLastError();
4906 if (error == CRYPT_E_NOT_FOUND) {
4907 Py_RETURN_TRUE;
4908 }
4909 return PyErr_SetFromWindowsErr(error);
4910 }
4911 retval = PySet_New(NULL);
4912 if (retval == NULL) {
4913 goto error;
4914 }
4915 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4916 if (usage->rgpszUsageIdentifier[i]) {
4917 PyObject *oid;
4918 int err;
4919 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4920 if (oid == NULL) {
4921 Py_CLEAR(retval);
4922 goto error;
4923 }
4924 err = PySet_Add(retval, oid);
4925 Py_DECREF(oid);
4926 if (err == -1) {
4927 Py_CLEAR(retval);
4928 goto error;
4929 }
4930 }
4931 }
4932 error:
4933 PyMem_Free(usage);
4934 return retval;
4935}
4936
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004937/*[clinic input]
4938_ssl.enum_certificates
4939 store_name: str
4940
4941Retrieve certificates from Windows' cert store.
4942
4943store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4944more cert storages, too. The function returns a list of (bytes,
4945encoding_type, trust) tuples. The encoding_type flag can be interpreted
4946with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4947a set of OIDs or the boolean True.
4948[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004949
Christian Heimes46bebee2013-06-09 19:03:31 +02004950static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004951_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4952/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004953{
Christian Heimes46bebee2013-06-09 19:03:31 +02004954 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004955 PCCERT_CONTEXT pCertCtx = NULL;
4956 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004957 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004958
Christian Heimes44109d72013-11-22 01:51:30 +01004959 result = PyList_New(0);
4960 if (result == NULL) {
4961 return NULL;
4962 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004963 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4964 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4965 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004966 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004967 Py_DECREF(result);
4968 return PyErr_SetFromWindowsErr(GetLastError());
4969 }
4970
Christian Heimes44109d72013-11-22 01:51:30 +01004971 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4972 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4973 pCertCtx->cbCertEncoded);
4974 if (!cert) {
4975 Py_CLEAR(result);
4976 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004977 }
Christian Heimes44109d72013-11-22 01:51:30 +01004978 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4979 Py_CLEAR(result);
4980 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004981 }
Christian Heimes44109d72013-11-22 01:51:30 +01004982 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4983 if (keyusage == Py_True) {
4984 Py_DECREF(keyusage);
4985 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004986 }
Christian Heimes44109d72013-11-22 01:51:30 +01004987 if (keyusage == NULL) {
4988 Py_CLEAR(result);
4989 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004990 }
Christian Heimes44109d72013-11-22 01:51:30 +01004991 if ((tup = PyTuple_New(3)) == NULL) {
4992 Py_CLEAR(result);
4993 break;
4994 }
4995 PyTuple_SET_ITEM(tup, 0, cert);
4996 cert = NULL;
4997 PyTuple_SET_ITEM(tup, 1, enc);
4998 enc = NULL;
4999 PyTuple_SET_ITEM(tup, 2, keyusage);
5000 keyusage = NULL;
5001 if (PyList_Append(result, tup) < 0) {
5002 Py_CLEAR(result);
5003 break;
5004 }
5005 Py_CLEAR(tup);
5006 }
5007 if (pCertCtx) {
5008 /* loop ended with an error, need to clean up context manually */
5009 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005010 }
5011
5012 /* In error cases cert, enc and tup may not be NULL */
5013 Py_XDECREF(cert);
5014 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005015 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005016 Py_XDECREF(tup);
5017
5018 if (!CertCloseStore(hStore, 0)) {
5019 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005020 Py_XDECREF(result);
5021 return PyErr_SetFromWindowsErr(GetLastError());
5022 }
5023 return result;
5024}
5025
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005026/*[clinic input]
5027_ssl.enum_crls
5028 store_name: str
5029
5030Retrieve CRLs from Windows' cert store.
5031
5032store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5033more cert storages, too. The function returns a list of (bytes,
5034encoding_type) tuples. The encoding_type flag can be interpreted with
5035X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5036[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005037
5038static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005039_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5040/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005041{
Christian Heimes44109d72013-11-22 01:51:30 +01005042 HCERTSTORE hStore = NULL;
5043 PCCRL_CONTEXT pCrlCtx = NULL;
5044 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5045 PyObject *result = NULL;
5046
Christian Heimes44109d72013-11-22 01:51:30 +01005047 result = PyList_New(0);
5048 if (result == NULL) {
5049 return NULL;
5050 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005051 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5052 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5053 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005054 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005055 Py_DECREF(result);
5056 return PyErr_SetFromWindowsErr(GetLastError());
5057 }
Christian Heimes44109d72013-11-22 01:51:30 +01005058
5059 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5060 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5061 pCrlCtx->cbCrlEncoded);
5062 if (!crl) {
5063 Py_CLEAR(result);
5064 break;
5065 }
5066 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5067 Py_CLEAR(result);
5068 break;
5069 }
5070 if ((tup = PyTuple_New(2)) == NULL) {
5071 Py_CLEAR(result);
5072 break;
5073 }
5074 PyTuple_SET_ITEM(tup, 0, crl);
5075 crl = NULL;
5076 PyTuple_SET_ITEM(tup, 1, enc);
5077 enc = NULL;
5078
5079 if (PyList_Append(result, tup) < 0) {
5080 Py_CLEAR(result);
5081 break;
5082 }
5083 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005084 }
Christian Heimes44109d72013-11-22 01:51:30 +01005085 if (pCrlCtx) {
5086 /* loop ended with an error, need to clean up context manually */
5087 CertFreeCRLContext(pCrlCtx);
5088 }
5089
5090 /* In error cases cert, enc and tup may not be NULL */
5091 Py_XDECREF(crl);
5092 Py_XDECREF(enc);
5093 Py_XDECREF(tup);
5094
5095 if (!CertCloseStore(hStore, 0)) {
5096 /* This error case might shadow another exception.*/
5097 Py_XDECREF(result);
5098 return PyErr_SetFromWindowsErr(GetLastError());
5099 }
5100 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005101}
Christian Heimes44109d72013-11-22 01:51:30 +01005102
5103#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005104
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005105/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005106static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005107 _SSL__TEST_DECODE_CERT_METHODDEF
5108 _SSL_RAND_ADD_METHODDEF
5109 _SSL_RAND_BYTES_METHODDEF
5110 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5111 _SSL_RAND_EGD_METHODDEF
5112 _SSL_RAND_STATUS_METHODDEF
5113 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5114 _SSL_ENUM_CERTIFICATES_METHODDEF
5115 _SSL_ENUM_CRLS_METHODDEF
5116 _SSL_TXT2OBJ_METHODDEF
5117 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005118 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005119};
5120
5121
Christian Heimes598894f2016-09-05 23:19:05 +02005122#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005123
5124/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005125 * of the Python C thread library
5126 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5127 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005128
5129static PyThread_type_lock *_ssl_locks = NULL;
5130
Christian Heimes4d98ca92013-08-19 17:36:29 +02005131#if OPENSSL_VERSION_NUMBER >= 0x10000000
5132/* use new CRYPTO_THREADID API. */
5133static void
5134_ssl_threadid_callback(CRYPTO_THREADID *id)
5135{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005136 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005137}
5138#else
5139/* deprecated CRYPTO_set_id_callback() API. */
5140static unsigned long
5141_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005142 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005143}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005144#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005145
Bill Janssen6e027db2007-11-15 22:23:56 +00005146static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005147 (int mode, int n, const char *file, int line) {
5148 /* this function is needed to perform locking on shared data
5149 structures. (Note that OpenSSL uses a number of global data
5150 structures that will be implicitly shared whenever multiple
5151 threads use OpenSSL.) Multi-threaded applications will
5152 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005153
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005154 locking_function() must be able to handle up to
5155 CRYPTO_num_locks() different mutex locks. It sets the n-th
5156 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005157
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005158 file and line are the file number of the function setting the
5159 lock. They can be useful for debugging.
5160 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005161
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005162 if ((_ssl_locks == NULL) ||
5163 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5164 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005165
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005166 if (mode & CRYPTO_LOCK) {
5167 PyThread_acquire_lock(_ssl_locks[n], 1);
5168 } else {
5169 PyThread_release_lock(_ssl_locks[n]);
5170 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005171}
5172
5173static int _setup_ssl_threads(void) {
5174
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005175 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005176
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005177 if (_ssl_locks == NULL) {
5178 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005179 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5180 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005181 if (_ssl_locks == NULL) {
5182 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005183 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005184 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005185 for (i = 0; i < _ssl_locks_count; i++) {
5186 _ssl_locks[i] = PyThread_allocate_lock();
5187 if (_ssl_locks[i] == NULL) {
5188 unsigned int j;
5189 for (j = 0; j < i; j++) {
5190 PyThread_free_lock(_ssl_locks[j]);
5191 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005192 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005193 return 0;
5194 }
5195 }
5196 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005197#if OPENSSL_VERSION_NUMBER >= 0x10000000
5198 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5199#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005200 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005201#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005202 }
5203 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005204}
5205
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005206#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005207
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005208PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005209"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005210for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005211
Martin v. Löwis1a214512008-06-11 05:26:20 +00005212
5213static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005214 PyModuleDef_HEAD_INIT,
5215 "_ssl",
5216 module_doc,
5217 -1,
5218 PySSL_methods,
5219 NULL,
5220 NULL,
5221 NULL,
5222 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005223};
5224
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005225
5226static void
5227parse_openssl_version(unsigned long libver,
5228 unsigned int *major, unsigned int *minor,
5229 unsigned int *fix, unsigned int *patch,
5230 unsigned int *status)
5231{
5232 *status = libver & 0xF;
5233 libver >>= 4;
5234 *patch = libver & 0xFF;
5235 libver >>= 8;
5236 *fix = libver & 0xFF;
5237 libver >>= 8;
5238 *minor = libver & 0xFF;
5239 libver >>= 8;
5240 *major = libver & 0xFF;
5241}
5242
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005243PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005244PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005245{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005246 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005247 unsigned long libver;
5248 unsigned int major, minor, fix, patch, status;
5249 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005250 struct py_ssl_error_code *errcode;
5251 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005252
Antoine Pitrou152efa22010-05-16 18:19:27 +00005253 if (PyType_Ready(&PySSLContext_Type) < 0)
5254 return NULL;
5255 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005256 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005257 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5258 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005259 if (PyType_Ready(&PySSLSession_Type) < 0)
5260 return NULL;
5261
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005262
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005263 m = PyModule_Create(&_sslmodule);
5264 if (m == NULL)
5265 return NULL;
5266 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005267
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005268 /* Load _socket module and its C API */
5269 socket_api = PySocketModule_ImportModuleAndAPI();
5270 if (!socket_api)
5271 return NULL;
5272 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005273
Christian Heimesc941e622017-09-05 15:47:11 +02005274#ifndef OPENSSL_VERSION_1_1
5275 /* Load all algorithms and initialize cpuid */
5276 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005277 /* Init OpenSSL */
5278 SSL_load_error_strings();
5279 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005280#endif
5281
Christian Heimes598894f2016-09-05 23:19:05 +02005282#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005283 /* note that this will start threading if not already started */
5284 if (!_setup_ssl_threads()) {
5285 return NULL;
5286 }
Christian Heimes598894f2016-09-05 23:19:05 +02005287#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5288 /* OpenSSL 1.1.0 builtin thread support is enabled */
5289 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005290#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005291
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005292 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005293 sslerror_type_slots[0].pfunc = PyExc_OSError;
5294 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005295 if (PySSLErrorObject == NULL)
5296 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005297
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005298 /* ssl.CertificateError used to be a subclass of ValueError */
5299 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5300 if (bases == NULL)
5301 return NULL;
5302 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5303 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5304 bases, NULL);
5305 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005306 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5307 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5308 PySSLErrorObject, NULL);
5309 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5310 "ssl.SSLWantReadError", SSLWantReadError_doc,
5311 PySSLErrorObject, NULL);
5312 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5313 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5314 PySSLErrorObject, NULL);
5315 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5316 "ssl.SSLSyscallError", SSLSyscallError_doc,
5317 PySSLErrorObject, NULL);
5318 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5319 "ssl.SSLEOFError", SSLEOFError_doc,
5320 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005321 if (PySSLCertVerificationErrorObject == NULL
5322 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005323 || PySSLWantReadErrorObject == NULL
5324 || PySSLWantWriteErrorObject == NULL
5325 || PySSLSyscallErrorObject == NULL
5326 || PySSLEOFErrorObject == NULL)
5327 return NULL;
5328 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005329 || PyDict_SetItemString(d, "SSLCertVerificationError",
5330 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005331 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5332 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5333 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5334 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5335 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005336 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005337 if (PyDict_SetItemString(d, "_SSLContext",
5338 (PyObject *)&PySSLContext_Type) != 0)
5339 return NULL;
5340 if (PyDict_SetItemString(d, "_SSLSocket",
5341 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005342 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005343 if (PyDict_SetItemString(d, "MemoryBIO",
5344 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5345 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005346 if (PyDict_SetItemString(d, "SSLSession",
5347 (PyObject *)&PySSLSession_Type) != 0)
5348 return NULL;
5349
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005350 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5351 PY_SSL_ERROR_ZERO_RETURN);
5352 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5353 PY_SSL_ERROR_WANT_READ);
5354 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5355 PY_SSL_ERROR_WANT_WRITE);
5356 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5357 PY_SSL_ERROR_WANT_X509_LOOKUP);
5358 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5359 PY_SSL_ERROR_SYSCALL);
5360 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5361 PY_SSL_ERROR_SSL);
5362 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5363 PY_SSL_ERROR_WANT_CONNECT);
5364 /* non ssl.h errorcodes */
5365 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5366 PY_SSL_ERROR_EOF);
5367 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5368 PY_SSL_ERROR_INVALID_ERROR_CODE);
5369 /* cert requirements */
5370 PyModule_AddIntConstant(m, "CERT_NONE",
5371 PY_SSL_CERT_NONE);
5372 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5373 PY_SSL_CERT_OPTIONAL);
5374 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5375 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005376 /* CRL verification for verification_flags */
5377 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5378 0);
5379 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5380 X509_V_FLAG_CRL_CHECK);
5381 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5382 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5383 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5384 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005385#ifdef X509_V_FLAG_TRUSTED_FIRST
5386 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5387 X509_V_FLAG_TRUSTED_FIRST);
5388#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005389
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005390 /* Alert Descriptions from ssl.h */
5391 /* note RESERVED constants no longer intended for use have been removed */
5392 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5393
5394#define ADD_AD_CONSTANT(s) \
5395 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5396 SSL_AD_##s)
5397
5398 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5399 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5400 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5401 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5402 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5403 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5404 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5405 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5406 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5407 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5408 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5409 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5410 ADD_AD_CONSTANT(UNKNOWN_CA);
5411 ADD_AD_CONSTANT(ACCESS_DENIED);
5412 ADD_AD_CONSTANT(DECODE_ERROR);
5413 ADD_AD_CONSTANT(DECRYPT_ERROR);
5414 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5415 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5416 ADD_AD_CONSTANT(INTERNAL_ERROR);
5417 ADD_AD_CONSTANT(USER_CANCELLED);
5418 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005419 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005420#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5421 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5422#endif
5423#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5424 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5425#endif
5426#ifdef SSL_AD_UNRECOGNIZED_NAME
5427 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5428#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005429#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5430 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5431#endif
5432#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5433 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5434#endif
5435#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5436 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5437#endif
5438
5439#undef ADD_AD_CONSTANT
5440
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005441 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005442#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005443 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5444 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005445#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005446#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005447 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5448 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005449#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005450 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005451 PY_SSL_VERSION_TLS);
5452 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5453 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005454 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5455 PY_SSL_VERSION_TLS_CLIENT);
5456 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5457 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005458 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5459 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005460#if HAVE_TLSv1_2
5461 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5462 PY_SSL_VERSION_TLS1_1);
5463 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5464 PY_SSL_VERSION_TLS1_2);
5465#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005466
Antoine Pitroub5218772010-05-21 09:56:06 +00005467 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005468 PyModule_AddIntConstant(m, "OP_ALL",
5469 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005470 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5471 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5472 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005473#if HAVE_TLSv1_2
5474 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5475 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5476#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005477#ifdef SSL_OP_NO_TLSv1_3
5478 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5479#else
5480 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5481#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005482 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5483 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005484 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005485 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005486#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005487 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005488#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005489#ifdef SSL_OP_NO_COMPRESSION
5490 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5491 SSL_OP_NO_COMPRESSION);
5492#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005493
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005494#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005495 r = Py_True;
5496#else
5497 r = Py_False;
5498#endif
5499 Py_INCREF(r);
5500 PyModule_AddObject(m, "HAS_SNI", r);
5501
Antoine Pitroud6494802011-07-21 01:11:30 +02005502 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005503 Py_INCREF(r);
5504 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5505
Antoine Pitrou501da612011-12-21 09:27:41 +01005506#ifdef OPENSSL_NO_ECDH
5507 r = Py_False;
5508#else
5509 r = Py_True;
5510#endif
5511 Py_INCREF(r);
5512 PyModule_AddObject(m, "HAS_ECDH", r);
5513
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005514#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005515 r = Py_True;
5516#else
5517 r = Py_False;
5518#endif
5519 Py_INCREF(r);
5520 PyModule_AddObject(m, "HAS_NPN", r);
5521
Benjamin Petersoncca27322015-01-23 16:35:37 -05005522#ifdef HAVE_ALPN
5523 r = Py_True;
5524#else
5525 r = Py_False;
5526#endif
5527 Py_INCREF(r);
5528 PyModule_AddObject(m, "HAS_ALPN", r);
5529
Christian Heimescb5b68a2017-09-07 18:07:00 -07005530#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5531 r = Py_True;
5532#else
5533 r = Py_False;
5534#endif
5535 Py_INCREF(r);
5536 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5537
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005538 /* Mappings for error codes */
5539 err_codes_to_names = PyDict_New();
5540 err_names_to_codes = PyDict_New();
5541 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5542 return NULL;
5543 errcode = error_codes;
5544 while (errcode->mnemonic != NULL) {
5545 PyObject *mnemo, *key;
5546 mnemo = PyUnicode_FromString(errcode->mnemonic);
5547 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5548 if (mnemo == NULL || key == NULL)
5549 return NULL;
5550 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5551 return NULL;
5552 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5553 return NULL;
5554 Py_DECREF(key);
5555 Py_DECREF(mnemo);
5556 errcode++;
5557 }
5558 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5559 return NULL;
5560 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5561 return NULL;
5562
5563 lib_codes_to_names = PyDict_New();
5564 if (lib_codes_to_names == NULL)
5565 return NULL;
5566 libcode = library_codes;
5567 while (libcode->library != NULL) {
5568 PyObject *mnemo, *key;
5569 key = PyLong_FromLong(libcode->code);
5570 mnemo = PyUnicode_FromString(libcode->library);
5571 if (key == NULL || mnemo == NULL)
5572 return NULL;
5573 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5574 return NULL;
5575 Py_DECREF(key);
5576 Py_DECREF(mnemo);
5577 libcode++;
5578 }
5579 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5580 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005581
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005582 /* OpenSSL version */
5583 /* SSLeay() gives us the version of the library linked against,
5584 which could be different from the headers version.
5585 */
5586 libver = SSLeay();
5587 r = PyLong_FromUnsignedLong(libver);
5588 if (r == NULL)
5589 return NULL;
5590 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5591 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005592 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005593 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5594 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5595 return NULL;
5596 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5597 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5598 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005599
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005600 libver = OPENSSL_VERSION_NUMBER;
5601 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5602 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5603 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5604 return NULL;
5605
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005606 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005607}