blob: 73abad3dcf1c7c452ba688b39edee0ca5e4dcb46 [file] [log] [blame]
Thomas Woutersed03b412007-08-28 21:37:11 +00001/* SSL socket module
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002
3 SSL support based on patches by Brian E Gallew and Laszlo Kovacs.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00004 Re-worked a bit by Bill Janssen to add server-side support and
Bill Janssen6e027db2007-11-15 22:23:56 +00005 certificate decoding. Chris Stawarz contributed some non-blocking
6 patches.
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00007
Thomas Wouters1b7f8912007-09-19 03:06:30 +00008 This module is imported by ssl.py. It should *not* be used
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00009 directly.
10
Thomas Wouters1b7f8912007-09-19 03:06:30 +000011 XXX should partial writes be enabled, SSL_MODE_ENABLE_PARTIAL_WRITE?
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +000012
13 XXX integrate several "shutdown modes" as suggested in
14 http://bugs.python.org/issue8108#msg102867 ?
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000015*/
16
Victor Stinner2e57b4e2014-07-01 16:37:17 +020017#define PY_SSIZE_T_CLEAN
18
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +000019#include "Python.h"
Thomas Woutersed03b412007-08-28 21:37:11 +000020
Thomas Wouters1b7f8912007-09-19 03:06:30 +000021#include "pythread.h"
Christian Heimesf77b4b22013-08-21 13:26:05 +020022
Steve Dower68d663c2017-07-17 11:15:48 +020023/* Redefined below for Windows debug builds after important #includes */
24#define _PySSL_FIX_ERRNO
Christian Heimesf77b4b22013-08-21 13:26:05 +020025
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020026#define PySSL_BEGIN_ALLOW_THREADS_S(save) \
27 do { if (_ssl_locks_count>0) { (save) = PyEval_SaveThread(); } } while (0)
28#define PySSL_END_ALLOW_THREADS_S(save) \
Steve Dower68d663c2017-07-17 11:15:48 +020029 do { if (_ssl_locks_count>0) { PyEval_RestoreThread(save); } _PySSL_FIX_ERRNO; } while (0)
Thomas Wouters1b7f8912007-09-19 03:06:30 +000030#define PySSL_BEGIN_ALLOW_THREADS { \
Antoine Pitroucbb82eb2010-05-05 15:57:33 +000031 PyThreadState *_save = NULL; \
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +020032 PySSL_BEGIN_ALLOW_THREADS_S(_save);
33#define PySSL_BLOCK_THREADS PySSL_END_ALLOW_THREADS_S(_save);
34#define PySSL_UNBLOCK_THREADS PySSL_BEGIN_ALLOW_THREADS_S(_save);
35#define PySSL_END_ALLOW_THREADS PySSL_END_ALLOW_THREADS_S(_save); }
Thomas Wouters1b7f8912007-09-19 03:06:30 +000036
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010037/* Include symbols from _socket module */
38#include "socketmodule.h"
39
40static PySocketModule_APIObject PySocketModule;
41
42#if defined(HAVE_POLL_H)
43#include <poll.h>
44#elif defined(HAVE_SYS_POLL_H)
45#include <sys/poll.h>
46#endif
47
Christian Heimes598894f2016-09-05 23:19:05 +020048/* Don't warn about deprecated functions */
49#ifdef __GNUC__
50#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
51#endif
52#ifdef __clang__
53#pragma clang diagnostic ignored "-Wdeprecated-declarations"
54#endif
55
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010056/* Include OpenSSL header files */
57#include "openssl/rsa.h"
58#include "openssl/crypto.h"
59#include "openssl/x509.h"
60#include "openssl/x509v3.h"
61#include "openssl/pem.h"
62#include "openssl/ssl.h"
63#include "openssl/err.h"
64#include "openssl/rand.h"
Antoine Pitroub1fdf472014-10-05 20:41:53 +020065#include "openssl/bio.h"
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010066
67/* SSL error object */
68static PyObject *PySSLErrorObject;
Christian Heimesb3ad0e52017-09-08 12:00:19 -070069static PyObject *PySSLCertVerificationErrorObject;
Antoine Pitrou2463e5f2013-03-28 22:24:43 +010070static PyObject *PySSLZeroReturnErrorObject;
71static PyObject *PySSLWantReadErrorObject;
72static PyObject *PySSLWantWriteErrorObject;
73static PyObject *PySSLSyscallErrorObject;
74static PyObject *PySSLEOFErrorObject;
75
76/* Error mappings */
77static PyObject *err_codes_to_names;
78static PyObject *err_names_to_codes;
79static PyObject *lib_codes_to_names;
80
81struct py_ssl_error_code {
82 const char *mnemonic;
83 int library, reason;
84};
85struct py_ssl_library_code {
86 const char *library;
87 int code;
88};
89
Steve Dower68d663c2017-07-17 11:15:48 +020090#if defined(MS_WINDOWS) && defined(Py_DEBUG)
91/* Debug builds on Windows rely on getting errno directly from OpenSSL.
92 * However, because it uses a different CRT, we need to transfer the
93 * value of errno from OpenSSL into our debug CRT.
94 *
95 * Don't be fooled - this is horribly ugly code. The only reasonable
96 * alternative is to do both debug and release builds of OpenSSL, which
97 * requires much uglier code to transform their automatically generated
98 * makefile. This is the lesser of all the evils.
99 */
100
101static void _PySSLFixErrno(void) {
102 HMODULE ucrtbase = GetModuleHandleW(L"ucrtbase.dll");
103 if (!ucrtbase) {
104 /* If ucrtbase.dll is not loaded but the SSL DLLs are, we likely
105 * have a catastrophic failure, but this function is not the
106 * place to raise it. */
107 return;
108 }
109
110 typedef int *(__stdcall *errno_func)(void);
111 errno_func ssl_errno = (errno_func)GetProcAddress(ucrtbase, "_errno");
112 if (ssl_errno) {
113 errno = *ssl_errno();
114 *ssl_errno() = 0;
115 } else {
116 errno = ENOTRECOVERABLE;
117 }
118}
119
120#undef _PySSL_FIX_ERRNO
121#define _PySSL_FIX_ERRNO _PySSLFixErrno()
122#endif
123
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100124/* Include generated data (error codes) */
125#include "_ssl_data.h"
126
Christian Heimes598894f2016-09-05 23:19:05 +0200127#if (OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
128# define OPENSSL_VERSION_1_1 1
129#endif
130
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100131/* Openssl comes with TLSv1.1 and TLSv1.2 between 1.0.0h and 1.0.1
132 http://www.openssl.org/news/changelog.html
133 */
134#if OPENSSL_VERSION_NUMBER >= 0x10001000L
135# define HAVE_TLSv1_2 1
136#else
137# define HAVE_TLSv1_2 0
138#endif
139
Christian Heimes470fba12013-11-28 15:12:15 +0100140/* SNI support (client- and server-side) appeared in OpenSSL 1.0.0 and 0.9.8f
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100141 * This includes the SSL_set_SSL_CTX() function.
142 */
143#ifdef SSL_CTRL_SET_TLSEXT_HOSTNAME
144# define HAVE_SNI 1
145#else
146# define HAVE_SNI 0
147#endif
148
Benjamin Petersond3308222015-09-27 00:09:02 -0700149#ifdef TLSEXT_TYPE_application_layer_protocol_negotiation
Benjamin Petersoncca27322015-01-23 16:35:37 -0500150# define HAVE_ALPN
151#endif
152
Victor Stinner524714e2016-07-22 17:43:59 +0200153#ifndef INVALID_SOCKET /* MS defines this */
154#define INVALID_SOCKET (-1)
155#endif
156
Christian Heimes598894f2016-09-05 23:19:05 +0200157#ifdef OPENSSL_VERSION_1_1
158/* OpenSSL 1.1.0+ */
159#ifndef OPENSSL_NO_SSL2
160#define OPENSSL_NO_SSL2
161#endif
162#else /* OpenSSL < 1.1.0 */
Christian Heimes598894f2016-09-05 23:19:05 +0200163#define HAVE_OPENSSL_CRYPTO_LOCK
Christian Heimes598894f2016-09-05 23:19:05 +0200164
165#define TLS_method SSLv23_method
Christian Heimes5fe668c2016-09-12 00:01:11 +0200166#define TLS_client_method SSLv23_client_method
167#define TLS_server_method SSLv23_server_method
Christian Heimes598894f2016-09-05 23:19:05 +0200168
169static int X509_NAME_ENTRY_set(const X509_NAME_ENTRY *ne)
170{
171 return ne->set;
172}
173
174#ifndef OPENSSL_NO_COMP
Christian Heimesa5d07652016-09-24 10:48:05 +0200175/* LCOV_EXCL_START */
Christian Heimes598894f2016-09-05 23:19:05 +0200176static int COMP_get_type(const COMP_METHOD *meth)
177{
178 return meth->type;
179}
Christian Heimes1a63b9f2016-09-24 12:07:21 +0200180/* LCOV_EXCL_STOP */
Christian Heimes598894f2016-09-05 23:19:05 +0200181#endif
182
183static pem_password_cb *SSL_CTX_get_default_passwd_cb(SSL_CTX *ctx)
184{
185 return ctx->default_passwd_callback;
186}
187
188static void *SSL_CTX_get_default_passwd_cb_userdata(SSL_CTX *ctx)
189{
190 return ctx->default_passwd_callback_userdata;
191}
192
193static int X509_OBJECT_get_type(X509_OBJECT *x)
194{
195 return x->type;
196}
197
198static X509 *X509_OBJECT_get0_X509(X509_OBJECT *x)
199{
200 return x->data.x509;
201}
202
203static int BIO_up_ref(BIO *b)
204{
205 CRYPTO_add(&b->references, 1, CRYPTO_LOCK_BIO);
206 return 1;
207}
208
209static STACK_OF(X509_OBJECT) *X509_STORE_get0_objects(X509_STORE *store) {
210 return store->objs;
211}
212
213static X509_VERIFY_PARAM *X509_STORE_get0_param(X509_STORE *store)
214{
215 return store->param;
216}
Christian Heimes99a65702016-09-10 23:44:53 +0200217
218static int
219SSL_SESSION_has_ticket(const SSL_SESSION *s)
220{
221 return (s->tlsext_ticklen > 0) ? 1 : 0;
222}
223
224static unsigned long
225SSL_SESSION_get_ticket_lifetime_hint(const SSL_SESSION *s)
226{
227 return s->tlsext_tick_lifetime_hint;
228}
229
Christian Heimes598894f2016-09-05 23:19:05 +0200230#endif /* OpenSSL < 1.1.0 or LibreSSL */
231
232
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000233enum py_ssl_error {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000234 /* these mirror ssl.h */
235 PY_SSL_ERROR_NONE,
236 PY_SSL_ERROR_SSL,
237 PY_SSL_ERROR_WANT_READ,
238 PY_SSL_ERROR_WANT_WRITE,
239 PY_SSL_ERROR_WANT_X509_LOOKUP,
240 PY_SSL_ERROR_SYSCALL, /* look at error stack/return value/errno */
241 PY_SSL_ERROR_ZERO_RETURN,
242 PY_SSL_ERROR_WANT_CONNECT,
243 /* start of non ssl.h errorcodes */
244 PY_SSL_ERROR_EOF, /* special case of SSL_ERROR_SYSCALL */
245 PY_SSL_ERROR_NO_SOCKET, /* socket has been GC'd */
246 PY_SSL_ERROR_INVALID_ERROR_CODE
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000247};
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000248
Thomas Woutersed03b412007-08-28 21:37:11 +0000249enum py_ssl_server_or_client {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000250 PY_SSL_CLIENT,
251 PY_SSL_SERVER
Thomas Woutersed03b412007-08-28 21:37:11 +0000252};
253
254enum py_ssl_cert_requirements {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000255 PY_SSL_CERT_NONE,
256 PY_SSL_CERT_OPTIONAL,
257 PY_SSL_CERT_REQUIRED
Thomas Woutersed03b412007-08-28 21:37:11 +0000258};
259
260enum py_ssl_version {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000261 PY_SSL_VERSION_SSL2,
Victor Stinner3de49192011-05-09 00:42:58 +0200262 PY_SSL_VERSION_SSL3=1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200263 PY_SSL_VERSION_TLS, /* SSLv23 */
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100264#if HAVE_TLSv1_2
265 PY_SSL_VERSION_TLS1,
266 PY_SSL_VERSION_TLS1_1,
Christian Heimes5fe668c2016-09-12 00:01:11 +0200267 PY_SSL_VERSION_TLS1_2,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100268#else
Christian Heimes5fe668c2016-09-12 00:01:11 +0200269 PY_SSL_VERSION_TLS1,
Thomas Wouters0e3f5912006-08-11 14:57:12 +0000270#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +0200271 PY_SSL_VERSION_TLS_CLIENT=0x10,
272 PY_SSL_VERSION_TLS_SERVER,
Antoine Pitrou2463e5f2013-03-28 22:24:43 +0100273};
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200274
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000275/* serves as a flag to see whether we've initialized the SSL thread support. */
276/* 0 means no, greater than 0 means yes */
277
278static unsigned int _ssl_locks_count = 0;
279
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000280/* SSL socket object */
281
282#define X509_NAME_MAXLEN 256
283
Gregory P. Smithbd4dacb2010-10-13 03:53:21 +0000284/* SSL_CTX_clear_options() and SSL_clear_options() were first added in
285 * OpenSSL 0.9.8m but do not appear in some 0.9.9-dev versions such the
286 * 0.9.9 from "May 2008" that NetBSD 5.0 uses. */
287#if OPENSSL_VERSION_NUMBER >= 0x009080dfL && OPENSSL_VERSION_NUMBER != 0x00909000L
Antoine Pitroub5218772010-05-21 09:56:06 +0000288# define HAVE_SSL_CTX_CLEAR_OPTIONS
289#else
290# undef HAVE_SSL_CTX_CLEAR_OPTIONS
291#endif
292
Antoine Pitroud6494802011-07-21 01:11:30 +0200293/* In case of 'tls-unique' it will be 12 bytes for TLS, 36 bytes for
294 * older SSL, but let's be safe */
295#define PySSL_CB_MAXLEN 128
296
Antoine Pitroua9bf2ac2012-02-17 18:47:54 +0100297
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000298typedef struct {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000299 PyObject_HEAD
Antoine Pitrou152efa22010-05-16 18:19:27 +0000300 SSL_CTX *ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +0200301#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -0500302 unsigned char *npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +0100303 int npn_protocols_len;
304#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -0500305#ifdef HAVE_ALPN
306 unsigned char *alpn_protocols;
Segev Finer5cff6372017-07-27 01:19:17 +0300307 unsigned int alpn_protocols_len;
Benjamin Petersoncca27322015-01-23 16:35:37 -0500308#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100309#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +0200310 PyObject *set_hostname;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100311#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +0100312 int check_hostname;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000313} PySSLContext;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000314
Antoine Pitrou152efa22010-05-16 18:19:27 +0000315typedef struct {
316 PyObject_HEAD
317 PyObject *Socket; /* weakref to socket on which we're layered */
318 SSL *ssl;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100319 PySSLContext *ctx; /* weakref to SSL context */
Antoine Pitrou20b85552013-09-29 19:50:53 +0200320 char shutdown_seen_zero;
Antoine Pitroud6494802011-07-21 01:11:30 +0200321 enum py_ssl_server_or_client socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200322 PyObject *owner; /* Python level "owner" passed to servername callback */
323 PyObject *server_hostname;
Steve Dowere6eb48c2017-09-08 15:16:15 -0700324 int ssl_errno; /* last seen error from SSL */
325 int c_errno; /* last seen error from libc */
326#ifdef MS_WINDOWS
327 int ws_errno; /* last seen error from winsock */
328#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +0000329} PySSLSocket;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000330
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200331typedef struct {
332 PyObject_HEAD
333 BIO *bio;
334 int eof_written;
335} PySSLMemoryBIO;
336
Christian Heimes99a65702016-09-10 23:44:53 +0200337typedef struct {
338 PyObject_HEAD
339 SSL_SESSION *session;
340 PySSLContext *ctx;
341} PySSLSession;
342
Antoine Pitrou152efa22010-05-16 18:19:27 +0000343static PyTypeObject PySSLContext_Type;
344static PyTypeObject PySSLSocket_Type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200345static PyTypeObject PySSLMemoryBIO_Type;
Christian Heimes99a65702016-09-10 23:44:53 +0200346static PyTypeObject PySSLSession_Type;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000347
Steve Dowere6eb48c2017-09-08 15:16:15 -0700348#ifdef MS_WINDOWS
349#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
350 (sock)->ws_errno = WSAGetLastError(); \
351 _PySSL_FIX_ERRNO; \
352 (sock)->c_errno = errno; \
353 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
354 } else { sock->ws_errno = 0; sock->c_errno = 0; sock->ssl_errno = 0; }
355#else
356#define _PySSL_UPDATE_ERRNO_IF(cond, sock, retcode) if (cond) { \
357 (sock)->c_errno = errno; \
358 (sock)->ssl_errno = SSL_get_error((sock->ssl), (retcode)); \
359 } else { (sock)->c_errno = 0; (sock)->ssl_errno = 0; }
360#endif
361#define _PySSL_UPDATE_ERRNO(sock, retcode) _PySSL_UPDATE_ERRNO_IF(1, (sock), (retcode))
362
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300363/*[clinic input]
364module _ssl
365class _ssl._SSLContext "PySSLContext *" "&PySSLContext_Type"
366class _ssl._SSLSocket "PySSLSocket *" "&PySSLSocket_Type"
367class _ssl.MemoryBIO "PySSLMemoryBIO *" "&PySSLMemoryBIO_Type"
Christian Heimes99a65702016-09-10 23:44:53 +0200368class _ssl.SSLSession "PySSLSession *" "&PySSLSession_Type"
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300369[clinic start generated code]*/
Christian Heimes99a65702016-09-10 23:44:53 +0200370/*[clinic end generated code: output=da39a3ee5e6b4b0d input=bdc67fafeeaa8109]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300371
372#include "clinic/_ssl.c.h"
373
Victor Stinner14690702015-04-06 22:46:13 +0200374static int PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000375
Christian Heimes99a65702016-09-10 23:44:53 +0200376
Antoine Pitrou152efa22010-05-16 18:19:27 +0000377#define PySSLContext_Check(v) (Py_TYPE(v) == &PySSLContext_Type)
378#define PySSLSocket_Check(v) (Py_TYPE(v) == &PySSLSocket_Type)
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200379#define PySSLMemoryBIO_Check(v) (Py_TYPE(v) == &PySSLMemoryBIO_Type)
Christian Heimes99a65702016-09-10 23:44:53 +0200380#define PySSLSession_Check(v) (Py_TYPE(v) == &PySSLSession_Type)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000381
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000382typedef enum {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000383 SOCKET_IS_NONBLOCKING,
384 SOCKET_IS_BLOCKING,
385 SOCKET_HAS_TIMED_OUT,
386 SOCKET_HAS_BEEN_CLOSED,
387 SOCKET_TOO_LARGE_FOR_SELECT,
388 SOCKET_OPERATION_OK
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +0000389} timeout_state;
390
Thomas Woutersed03b412007-08-28 21:37:11 +0000391/* Wrap error strings with filename and line # */
Thomas Woutersed03b412007-08-28 21:37:11 +0000392#define ERRSTR1(x,y,z) (x ":" y ": " z)
Victor Stinner45e8e2f2014-05-14 17:24:35 +0200393#define ERRSTR(x) ERRSTR1("_ssl.c", Py_STRINGIFY(__LINE__), x)
Thomas Woutersed03b412007-08-28 21:37:11 +0000394
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200395/* Get the socket from a PySSLSocket, if it has one */
396#define GET_SOCKET(obj) ((obj)->Socket ? \
397 (PySocketSockObject *) PyWeakref_GetObject((obj)->Socket) : NULL)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200398
Victor Stinner14690702015-04-06 22:46:13 +0200399/* If sock is NULL, use a timeout of 0 second */
400#define GET_SOCKET_TIMEOUT(sock) \
401 ((sock != NULL) ? (sock)->sock_timeout : 0)
402
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200403/*
404 * SSL errors.
405 */
406
407PyDoc_STRVAR(SSLError_doc,
408"An error occurred in the SSL implementation.");
409
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700410PyDoc_STRVAR(SSLCertVerificationError_doc,
411"A certificate could not be verified.");
412
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200413PyDoc_STRVAR(SSLZeroReturnError_doc,
414"SSL/TLS session closed cleanly.");
415
416PyDoc_STRVAR(SSLWantReadError_doc,
417"Non-blocking SSL socket needs to read more data\n"
418"before the requested operation can be completed.");
419
420PyDoc_STRVAR(SSLWantWriteError_doc,
421"Non-blocking SSL socket needs to write more data\n"
422"before the requested operation can be completed.");
423
424PyDoc_STRVAR(SSLSyscallError_doc,
425"System error when attempting SSL operation.");
426
427PyDoc_STRVAR(SSLEOFError_doc,
428"SSL/TLS connection terminated abruptly.");
429
430static PyObject *
431SSLError_str(PyOSErrorObject *self)
432{
433 if (self->strerror != NULL && PyUnicode_Check(self->strerror)) {
434 Py_INCREF(self->strerror);
435 return self->strerror;
436 }
437 else
438 return PyObject_Str(self->args);
439}
440
441static PyType_Slot sslerror_type_slots[] = {
442 {Py_tp_base, NULL}, /* Filled out in module init as it's not a constant */
443 {Py_tp_doc, SSLError_doc},
444 {Py_tp_str, SSLError_str},
445 {0, 0},
446};
447
448static PyType_Spec sslerror_type_spec = {
449 "ssl.SSLError",
450 sizeof(PyOSErrorObject),
451 0,
452 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,
453 sslerror_type_slots
454};
455
456static void
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700457fill_and_set_sslerror(PySSLSocket *sslsock, PyObject *type, int ssl_errno,
458 const char *errstr, int lineno, unsigned long errcode)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200459{
460 PyObject *err_value = NULL, *reason_obj = NULL, *lib_obj = NULL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700461 PyObject *verify_obj = NULL, *verify_code_obj = NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200462 PyObject *init_value, *msg, *key;
463 _Py_IDENTIFIER(reason);
464 _Py_IDENTIFIER(library);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700465 _Py_IDENTIFIER(verify_message);
466 _Py_IDENTIFIER(verify_code);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200467
468 if (errcode != 0) {
469 int lib, reason;
470
471 lib = ERR_GET_LIB(errcode);
472 reason = ERR_GET_REASON(errcode);
473 key = Py_BuildValue("ii", lib, reason);
474 if (key == NULL)
475 goto fail;
476 reason_obj = PyDict_GetItem(err_codes_to_names, key);
477 Py_DECREF(key);
478 if (reason_obj == NULL) {
479 /* XXX if reason < 100, it might reflect a library number (!!) */
480 PyErr_Clear();
481 }
482 key = PyLong_FromLong(lib);
483 if (key == NULL)
484 goto fail;
485 lib_obj = PyDict_GetItem(lib_codes_to_names, key);
486 Py_DECREF(key);
487 if (lib_obj == NULL) {
488 PyErr_Clear();
489 }
490 if (errstr == NULL)
491 errstr = ERR_reason_error_string(errcode);
492 }
493 if (errstr == NULL)
494 errstr = "unknown error";
495
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700496 /* verify code for cert validation error */
497 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
498 const char *verify_str = NULL;
499 long verify_code;
500
501 verify_code = SSL_get_verify_result(sslsock->ssl);
502 verify_code_obj = PyLong_FromLong(verify_code);
503 if (verify_code_obj == NULL) {
504 goto fail;
505 }
506
507 switch (verify_code) {
Christian Heimes09153602017-09-08 14:47:58 -0700508#ifdef X509_V_ERR_HOSTNAME_MISMATCH
509 /* OpenSSL >= 1.0.2, LibreSSL >= 2.5.3 */
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700510 case X509_V_ERR_HOSTNAME_MISMATCH:
511 verify_obj = PyUnicode_FromFormat(
512 "Hostname mismatch, certificate is not valid for '%S'.",
513 sslsock->server_hostname
514 );
515 break;
Christian Heimes09153602017-09-08 14:47:58 -0700516#endif
517#ifdef X509_V_ERR_IP_ADDRESS_MISMATCH
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700518 case X509_V_ERR_IP_ADDRESS_MISMATCH:
519 verify_obj = PyUnicode_FromFormat(
520 "IP address mismatch, certificate is not valid for '%S'.",
521 sslsock->server_hostname
522 );
523 break;
Christian Heimes09153602017-09-08 14:47:58 -0700524#endif
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700525 default:
526 verify_str = X509_verify_cert_error_string(verify_code);
527 if (verify_str != NULL) {
528 verify_obj = PyUnicode_FromString(verify_str);
529 } else {
530 verify_obj = Py_None;
531 Py_INCREF(verify_obj);
532 }
533 break;
534 }
535 if (verify_obj == NULL) {
536 goto fail;
537 }
538 }
539
540 if (verify_obj && reason_obj && lib_obj)
541 msg = PyUnicode_FromFormat("[%S: %S] %s: %S (_ssl.c:%d)",
542 lib_obj, reason_obj, errstr, verify_obj,
543 lineno);
544 else if (reason_obj && lib_obj)
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200545 msg = PyUnicode_FromFormat("[%S: %S] %s (_ssl.c:%d)",
546 lib_obj, reason_obj, errstr, lineno);
547 else if (lib_obj)
548 msg = PyUnicode_FromFormat("[%S] %s (_ssl.c:%d)",
549 lib_obj, errstr, lineno);
550 else
551 msg = PyUnicode_FromFormat("%s (_ssl.c:%d)", errstr, lineno);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200552 if (msg == NULL)
553 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100554
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200555 init_value = Py_BuildValue("iN", ssl_errno, msg);
Victor Stinnerba9be472013-10-31 15:00:24 +0100556 if (init_value == NULL)
557 goto fail;
558
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200559 err_value = PyObject_CallObject(type, init_value);
560 Py_DECREF(init_value);
561 if (err_value == NULL)
562 goto fail;
Victor Stinnerba9be472013-10-31 15:00:24 +0100563
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200564 if (reason_obj == NULL)
565 reason_obj = Py_None;
566 if (_PyObject_SetAttrId(err_value, &PyId_reason, reason_obj))
567 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700568
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200569 if (lib_obj == NULL)
570 lib_obj = Py_None;
571 if (_PyObject_SetAttrId(err_value, &PyId_library, lib_obj))
572 goto fail;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700573
574 if ((sslsock != NULL) && (type == PySSLCertVerificationErrorObject)) {
575 /* Only set verify code / message for SSLCertVerificationError */
576 if (_PyObject_SetAttrId(err_value, &PyId_verify_code,
577 verify_code_obj))
578 goto fail;
579 if (_PyObject_SetAttrId(err_value, &PyId_verify_message, verify_obj))
580 goto fail;
581 }
582
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200583 PyErr_SetObject(type, err_value);
584fail:
585 Py_XDECREF(err_value);
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700586 Py_XDECREF(verify_code_obj);
587 Py_XDECREF(verify_obj);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200588}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000589
590static PyObject *
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700591PySSL_SetError(PySSLSocket *sslsock, int ret, const char *filename, int lineno)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000592{
Antoine Pitrou41032a62011-10-27 23:56:55 +0200593 PyObject *type = PySSLErrorObject;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200594 char *errstr = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000595 int err;
596 enum py_ssl_error p = PY_SSL_ERROR_NONE;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200597 unsigned long e = 0;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000599 assert(ret <= 0);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200600 e = ERR_peek_last_error();
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +0000601
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700602 if (sslsock->ssl != NULL) {
Steve Dowere6eb48c2017-09-08 15:16:15 -0700603 err = sslsock->ssl_errno;
Thomas Woutersed03b412007-08-28 21:37:11 +0000604
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000605 switch (err) {
606 case SSL_ERROR_ZERO_RETURN:
Antoine Pitrou41032a62011-10-27 23:56:55 +0200607 errstr = "TLS/SSL connection has been closed (EOF)";
608 type = PySSLZeroReturnErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000609 p = PY_SSL_ERROR_ZERO_RETURN;
610 break;
611 case SSL_ERROR_WANT_READ:
612 errstr = "The operation did not complete (read)";
Antoine Pitrou41032a62011-10-27 23:56:55 +0200613 type = PySSLWantReadErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000614 p = PY_SSL_ERROR_WANT_READ;
615 break;
616 case SSL_ERROR_WANT_WRITE:
617 p = PY_SSL_ERROR_WANT_WRITE;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200618 type = PySSLWantWriteErrorObject;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000619 errstr = "The operation did not complete (write)";
620 break;
621 case SSL_ERROR_WANT_X509_LOOKUP:
622 p = PY_SSL_ERROR_WANT_X509_LOOKUP;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000623 errstr = "The operation did not complete (X509 lookup)";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000624 break;
625 case SSL_ERROR_WANT_CONNECT:
626 p = PY_SSL_ERROR_WANT_CONNECT;
627 errstr = "The operation did not complete (connect)";
628 break;
629 case SSL_ERROR_SYSCALL:
630 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000631 if (e == 0) {
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700632 PySocketSockObject *s = GET_SOCKET(sslsock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000633 if (ret == 0 || (((PyObject *)s) == Py_None)) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000634 p = PY_SSL_ERROR_EOF;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200635 type = PySSLEOFErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000636 errstr = "EOF occurred in violation of protocol";
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200637 } else if (s && ret == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +0000638 /* underlying BIO reported an I/O error */
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000639 ERR_clear_error();
Steve Dowere6eb48c2017-09-08 15:16:15 -0700640#ifdef MS_WINDOWS
641 if (sslsock->ws_errno)
642 return PyErr_SetFromWindowsErr(sslsock->ws_errno);
643#endif
644 if (sslsock->c_errno) {
645 errno = sslsock->c_errno;
646 return PyErr_SetFromErrno(PyExc_OSError);
647 }
648 Py_INCREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200649 s->errorhandler();
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000650 Py_DECREF(s);
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200651 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000652 } else { /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000653 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitrou41032a62011-10-27 23:56:55 +0200654 type = PySSLSyscallErrorObject;
Antoine Pitrou525807b2010-05-12 14:05:24 +0000655 errstr = "Some I/O error occurred";
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000656 }
657 } else {
658 p = PY_SSL_ERROR_SYSCALL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000659 }
660 break;
661 }
662 case SSL_ERROR_SSL:
663 {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000664 p = PY_SSL_ERROR_SSL;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700665 if (e == 0) {
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200666 /* possible? */
Antoine Pitrou525807b2010-05-12 14:05:24 +0000667 errstr = "A failure in the SSL library occurred";
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700668 }
669 if (ERR_GET_LIB(e) == ERR_LIB_SSL &&
670 ERR_GET_REASON(e) == SSL_R_CERTIFICATE_VERIFY_FAILED) {
671 type = PySSLCertVerificationErrorObject;
672 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000673 break;
674 }
675 default:
676 p = PY_SSL_ERROR_INVALID_ERROR_CODE;
677 errstr = "Invalid error code";
678 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000679 }
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700680 fill_and_set_sslerror(sslsock, type, p, errstr, lineno, e);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000681 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000682 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000683}
684
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000685static PyObject *
Serhiy Storchakaef1585e2015-12-25 20:01:53 +0200686_setSSLError (const char *errstr, int errcode, const char *filename, int lineno) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000687
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200688 if (errstr == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000689 errcode = ERR_peek_last_error();
Antoine Pitrou3b36fb12012-06-22 21:11:52 +0200690 else
691 errcode = 0;
Christian Heimesb3ad0e52017-09-08 12:00:19 -0700692 fill_and_set_sslerror(NULL, PySSLErrorObject, errcode, errstr, lineno, errcode);
Antoine Pitrou9d74b422010-05-16 23:14:22 +0000693 ERR_clear_error();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000694 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000695}
696
Antoine Pitrou152efa22010-05-16 18:19:27 +0000697static PySSLSocket *
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100698newPySSLSocket(PySSLContext *sslctx, PySocketSockObject *sock,
Antoine Pitroud5323212010-10-22 18:19:07 +0000699 enum py_ssl_server_or_client socket_type,
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200700 char *server_hostname,
701 PySSLMemoryBIO *inbio, PySSLMemoryBIO *outbio)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000702{
Antoine Pitrou152efa22010-05-16 18:19:27 +0000703 PySSLSocket *self;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100704 SSL_CTX *ctx = sslctx->ctx;
Antoine Pitrou19fef692013-05-25 13:23:03 +0200705 long mode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000706
Antoine Pitrou152efa22010-05-16 18:19:27 +0000707 self = PyObject_New(PySSLSocket, &PySSLSocket_Type);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000708 if (self == NULL)
709 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +0000710
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000711 self->ssl = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000712 self->Socket = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +0100713 self->ctx = sslctx;
Nathaniel J. Smith65ece7c2017-06-07 23:30:43 -0700714 Py_INCREF(sslctx);
Antoine Pitrou860aee72013-09-29 19:52:45 +0200715 self->shutdown_seen_zero = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200716 self->owner = NULL;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700717 self->server_hostname = NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200718 if (server_hostname != NULL) {
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700719 PyObject *hostname = PyUnicode_Decode(server_hostname, strlen(server_hostname),
720 "idna", "strict");
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200721 if (hostname == NULL) {
722 Py_DECREF(self);
723 return NULL;
724 }
725 self->server_hostname = hostname;
Benjamin Peterson81b9ecd2016-08-15 21:55:37 -0700726 }
Steve Dowere6eb48c2017-09-08 15:16:15 -0700727 self->ssl_errno = 0;
728 self->c_errno = 0;
729#ifdef MS_WINDOWS
730 self->ws_errno = 0;
731#endif
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200732
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000733 /* Make sure the SSL error state is initialized */
734 (void) ERR_get_state();
735 ERR_clear_error();
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000736
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000737 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitrou152efa22010-05-16 18:19:27 +0000738 self->ssl = SSL_new(ctx);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000739 PySSL_END_ALLOW_THREADS
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200740 SSL_set_app_data(self->ssl, self);
741 if (sock) {
742 SSL_set_fd(self->ssl, Py_SAFE_DOWNCAST(sock->sock_fd, SOCKET_T, int));
743 } else {
744 /* BIOs are reference counted and SSL_set_bio borrows our reference.
745 * To prevent a double free in memory_bio_dealloc() we need to take an
746 * extra reference here. */
Christian Heimes598894f2016-09-05 23:19:05 +0200747 BIO_up_ref(inbio->bio);
748 BIO_up_ref(outbio->bio);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200749 SSL_set_bio(self->ssl, inbio->bio, outbio->bio);
750 }
Antoine Pitrou19fef692013-05-25 13:23:03 +0200751 mode = SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000752#ifdef SSL_MODE_AUTO_RETRY
Antoine Pitrou19fef692013-05-25 13:23:03 +0200753 mode |= SSL_MODE_AUTO_RETRY;
Antoine Pitrou0ae7b582010-04-09 20:42:09 +0000754#endif
Antoine Pitrou19fef692013-05-25 13:23:03 +0200755 SSL_set_mode(self->ssl, mode);
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000756
Antoine Pitrou912fbff2013-03-30 16:29:32 +0100757#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +0000758 if (server_hostname != NULL)
759 SSL_set_tlsext_host_name(self->ssl, server_hostname);
760#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000761 /* If the socket is in non-blocking mode or timeout mode, set the BIO
762 * to non-blocking mode (blocking is the default)
763 */
Victor Stinnere2452312015-03-28 03:00:46 +0100764 if (sock && sock->sock_timeout >= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000765 BIO_set_nbio(SSL_get_rbio(self->ssl), 1);
766 BIO_set_nbio(SSL_get_wbio(self->ssl), 1);
767 }
Guido van Rossum4f707ac2003-01-31 18:13:18 +0000768
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000769 PySSL_BEGIN_ALLOW_THREADS
770 if (socket_type == PY_SSL_CLIENT)
771 SSL_set_connect_state(self->ssl);
772 else
773 SSL_set_accept_state(self->ssl);
774 PySSL_END_ALLOW_THREADS
Martin v. Löwis09c35f72002-07-28 09:57:45 +0000775
Antoine Pitroud6494802011-07-21 01:11:30 +0200776 self->socket_type = socket_type;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200777 if (sock != NULL) {
778 self->Socket = PyWeakref_NewRef((PyObject *) sock, NULL);
779 if (self->Socket == NULL) {
780 Py_DECREF(self);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200781 return NULL;
782 }
Victor Stinnera9eb38f2013-10-31 16:35:38 +0100783 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000784 return self;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000785}
786
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000787/* SSL object methods */
788
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +0300789/*[clinic input]
790_ssl._SSLSocket.do_handshake
791[clinic start generated code]*/
792
793static PyObject *
794_ssl__SSLSocket_do_handshake_impl(PySSLSocket *self)
795/*[clinic end generated code: output=6c0898a8936548f6 input=d2d737de3df018c8]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000796{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000797 int ret;
798 int err;
799 int sockstate, nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200800 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +0200801 _PyTime_t timeout, deadline = 0;
802 int has_timeout;
Antoine Pitroud3f8ab82010-04-24 21:26:44 +0000803
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200804 if (sock) {
805 if (((PyObject*)sock) == Py_None) {
806 _setSSLError("Underlying socket connection gone",
807 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
808 return NULL;
809 }
810 Py_INCREF(sock);
811
812 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +0100813 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200814 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
815 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000816 }
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000817
Victor Stinner14690702015-04-06 22:46:13 +0200818 timeout = GET_SOCKET_TIMEOUT(sock);
819 has_timeout = (timeout > 0);
820 if (has_timeout)
821 deadline = _PyTime_GetMonotonicClock() + timeout;
822
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000823 /* Actually negotiate SSL connection */
824 /* XXX If SSL_do_handshake() returns 0, it's also a failure. */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000825 do {
Bill Janssen6e027db2007-11-15 22:23:56 +0000826 PySSL_BEGIN_ALLOW_THREADS
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000827 ret = SSL_do_handshake(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -0700828 _PySSL_UPDATE_ERRNO_IF(ret < 1, self, ret);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000829 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -0700830 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200831
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000832 if (PyErr_CheckSignals())
833 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200834
Victor Stinner14690702015-04-06 22:46:13 +0200835 if (has_timeout)
836 timeout = deadline - _PyTime_GetMonotonicClock();
837
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000838 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +0200839 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000840 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +0200841 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000842 } else {
843 sockstate = SOCKET_OPERATION_OK;
844 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +0200845
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000846 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +0000847 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000848 ERRSTR("The handshake operation timed out"));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000849 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000850 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
851 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000852 ERRSTR("Underlying socket has been closed."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000853 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000854 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
855 PyErr_SetString(PySSLErrorObject,
Antoine Pitrou525807b2010-05-12 14:05:24 +0000856 ERRSTR("Underlying socket too large for select()."));
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000857 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000858 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
859 break;
860 }
861 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200862 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000863 if (ret < 1)
864 return PySSL_SetError(self, ret, __FILE__, __LINE__);
Bill Janssen6e027db2007-11-15 22:23:56 +0000865
Serhiy Storchaka228b12e2017-01-23 09:47:21 +0200866 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000867
868error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +0200869 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +0000870 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +0000871}
872
Thomas Woutersed03b412007-08-28 21:37:11 +0000873static PyObject *
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300874_asn1obj2py(const ASN1_OBJECT *name, int no_name)
875{
876 char buf[X509_NAME_MAXLEN];
877 char *namebuf = buf;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000878 int buflen;
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300879 PyObject *name_obj = NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +0000880
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300881 buflen = OBJ_obj2txt(namebuf, X509_NAME_MAXLEN, name, no_name);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000882 if (buflen < 0) {
883 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300884 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000885 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300886 /* initial buffer is too small for oid + terminating null byte */
887 if (buflen > X509_NAME_MAXLEN - 1) {
888 /* make OBJ_obj2txt() calculate the required buflen */
889 buflen = OBJ_obj2txt(NULL, 0, name, no_name);
890 /* allocate len + 1 for terminating NULL byte */
891 namebuf = PyMem_Malloc(buflen + 1);
892 if (namebuf == NULL) {
893 PyErr_NoMemory();
894 return NULL;
895 }
896 buflen = OBJ_obj2txt(namebuf, buflen + 1, name, no_name);
897 if (buflen < 0) {
898 _setSSLError(NULL, 0, __FILE__, __LINE__);
899 goto done;
900 }
901 }
902 if (!buflen && no_name) {
903 Py_INCREF(Py_None);
904 name_obj = Py_None;
905 }
906 else {
907 name_obj = PyUnicode_FromStringAndSize(namebuf, buflen);
908 }
909
910 done:
911 if (buf != namebuf) {
912 PyMem_Free(namebuf);
913 }
914 return name_obj;
915}
916
917static PyObject *
918_create_tuple_for_attribute(ASN1_OBJECT *name, ASN1_STRING *value)
919{
920 Py_ssize_t buflen;
921 unsigned char *valuebuf = NULL;
922 PyObject *attr;
Guido van Rossumf06628b2007-11-21 20:01:53 +0000923
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000924 buflen = ASN1_STRING_to_UTF8(&valuebuf, value);
925 if (buflen < 0) {
926 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300927 return NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000928 }
Serhiy Storchakae503ca52017-09-05 01:28:53 +0300929 attr = Py_BuildValue("Ns#", _asn1obj2py(name, 0), valuebuf, buflen);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000930 OPENSSL_free(valuebuf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000931 return attr;
Thomas Woutersed03b412007-08-28 21:37:11 +0000932}
933
934static PyObject *
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000935_create_tuple_for_X509_NAME (X509_NAME *xname)
Thomas Woutersed03b412007-08-28 21:37:11 +0000936{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000937 PyObject *dn = NULL; /* tuple which represents the "distinguished name" */
938 PyObject *rdn = NULL; /* tuple to hold a "relative distinguished name" */
939 PyObject *rdnt;
940 PyObject *attr = NULL; /* tuple to hold an attribute */
941 int entry_count = X509_NAME_entry_count(xname);
942 X509_NAME_ENTRY *entry;
943 ASN1_OBJECT *name;
944 ASN1_STRING *value;
945 int index_counter;
946 int rdn_level = -1;
947 int retcode;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000948
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000949 dn = PyList_New(0);
950 if (dn == NULL)
951 return NULL;
952 /* now create another tuple to hold the top-level RDN */
953 rdn = PyList_New(0);
954 if (rdn == NULL)
955 goto fail0;
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000956
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000957 for (index_counter = 0;
958 index_counter < entry_count;
959 index_counter++)
960 {
961 entry = X509_NAME_get_entry(xname, index_counter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000962
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000963 /* check to see if we've gotten to a new RDN */
964 if (rdn_level >= 0) {
Christian Heimes598894f2016-09-05 23:19:05 +0200965 if (rdn_level != X509_NAME_ENTRY_set(entry)) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000966 /* yes, new RDN */
967 /* add old RDN to DN */
968 rdnt = PyList_AsTuple(rdn);
969 Py_DECREF(rdn);
970 if (rdnt == NULL)
971 goto fail0;
972 retcode = PyList_Append(dn, rdnt);
973 Py_DECREF(rdnt);
974 if (retcode < 0)
975 goto fail0;
976 /* create new RDN */
977 rdn = PyList_New(0);
978 if (rdn == NULL)
979 goto fail0;
980 }
981 }
Christian Heimes598894f2016-09-05 23:19:05 +0200982 rdn_level = X509_NAME_ENTRY_set(entry);
Thomas Wouters1b7f8912007-09-19 03:06:30 +0000983
Antoine Pitroucbb82eb2010-05-05 15:57:33 +0000984 /* now add this attribute to the current RDN */
985 name = X509_NAME_ENTRY_get_object(entry);
986 value = X509_NAME_ENTRY_get_data(entry);
987 attr = _create_tuple_for_attribute(name, value);
988 /*
989 fprintf(stderr, "RDN level %d, attribute %s: %s\n",
990 entry->set,
991 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 0)),
992 PyBytes_AS_STRING(PyTuple_GET_ITEM(attr, 1)));
993 */
994 if (attr == NULL)
995 goto fail1;
996 retcode = PyList_Append(rdn, attr);
997 Py_DECREF(attr);
998 if (retcode < 0)
999 goto fail1;
1000 }
1001 /* now, there's typically a dangling RDN */
Antoine Pitrou2f5a1632012-02-15 22:25:27 +01001002 if (rdn != NULL) {
1003 if (PyList_GET_SIZE(rdn) > 0) {
1004 rdnt = PyList_AsTuple(rdn);
1005 Py_DECREF(rdn);
1006 if (rdnt == NULL)
1007 goto fail0;
1008 retcode = PyList_Append(dn, rdnt);
1009 Py_DECREF(rdnt);
1010 if (retcode < 0)
1011 goto fail0;
1012 }
1013 else {
1014 Py_DECREF(rdn);
1015 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001016 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001017
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001018 /* convert list to tuple */
1019 rdnt = PyList_AsTuple(dn);
1020 Py_DECREF(dn);
1021 if (rdnt == NULL)
1022 return NULL;
1023 return rdnt;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001024
1025 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001026 Py_XDECREF(rdn);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001027
1028 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001029 Py_XDECREF(dn);
1030 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001031}
1032
1033static PyObject *
1034_get_peer_alt_names (X509 *certificate) {
Guido van Rossumf06628b2007-11-21 20:01:53 +00001035
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001036 /* this code follows the procedure outlined in
1037 OpenSSL's crypto/x509v3/v3_prn.c:X509v3_EXT_print()
1038 function to extract the STACK_OF(GENERAL_NAME),
1039 then iterates through the stack to add the
1040 names. */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001041
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001042 int j;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001043 PyObject *peer_alt_names = Py_None;
Christian Heimes60bf2fc2013-09-05 16:04:35 +02001044 PyObject *v = NULL, *t;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001045 GENERAL_NAMES *names = NULL;
1046 GENERAL_NAME *name;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001047 BIO *biobuf = NULL;
1048 char buf[2048];
1049 char *vptr;
1050 int len;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001051
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001052 if (certificate == NULL)
1053 return peer_alt_names;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001054
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001055 /* get a memory buffer */
1056 biobuf = BIO_new(BIO_s_mem());
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001057
Alex Gaynorb87c0df2017-06-06 07:53:11 -04001058 names = (GENERAL_NAMES *)X509_get_ext_d2i(
1059 certificate, NID_subject_alt_name, NULL, NULL);
1060 if (names != NULL) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001061 if (peer_alt_names == Py_None) {
1062 peer_alt_names = PyList_New(0);
1063 if (peer_alt_names == NULL)
1064 goto fail;
1065 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001066
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001067 for(j = 0; j < sk_GENERAL_NAME_num(names); j++) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001068 /* get a rendering of each name in the set of names */
Christian Heimes824f7f32013-08-17 00:54:47 +02001069 int gntype;
1070 ASN1_STRING *as = NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001071
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001072 name = sk_GENERAL_NAME_value(names, j);
Christian Heimes474afdd2013-08-17 17:18:56 +02001073 gntype = name->type;
Christian Heimes824f7f32013-08-17 00:54:47 +02001074 switch (gntype) {
1075 case GEN_DIRNAME:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001076 /* we special-case DirName as a tuple of
1077 tuples of attributes */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001078
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001079 t = PyTuple_New(2);
1080 if (t == NULL) {
1081 goto fail;
1082 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001083
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001084 v = PyUnicode_FromString("DirName");
1085 if (v == NULL) {
1086 Py_DECREF(t);
1087 goto fail;
1088 }
1089 PyTuple_SET_ITEM(t, 0, v);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001090
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001091 v = _create_tuple_for_X509_NAME (name->d.dirn);
1092 if (v == NULL) {
1093 Py_DECREF(t);
1094 goto fail;
1095 }
1096 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001097 break;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001098
Christian Heimes824f7f32013-08-17 00:54:47 +02001099 case GEN_EMAIL:
1100 case GEN_DNS:
1101 case GEN_URI:
1102 /* GENERAL_NAME_print() doesn't handle NULL bytes in ASN1_string
1103 correctly, CVE-2013-4238 */
1104 t = PyTuple_New(2);
1105 if (t == NULL)
1106 goto fail;
1107 switch (gntype) {
1108 case GEN_EMAIL:
1109 v = PyUnicode_FromString("email");
1110 as = name->d.rfc822Name;
1111 break;
1112 case GEN_DNS:
1113 v = PyUnicode_FromString("DNS");
1114 as = name->d.dNSName;
1115 break;
1116 case GEN_URI:
1117 v = PyUnicode_FromString("URI");
1118 as = name->d.uniformResourceIdentifier;
1119 break;
1120 }
1121 if (v == NULL) {
1122 Py_DECREF(t);
1123 goto fail;
1124 }
1125 PyTuple_SET_ITEM(t, 0, v);
1126 v = PyUnicode_FromStringAndSize((char *)ASN1_STRING_data(as),
1127 ASN1_STRING_length(as));
1128 if (v == NULL) {
1129 Py_DECREF(t);
1130 goto fail;
1131 }
1132 PyTuple_SET_ITEM(t, 1, v);
1133 break;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001134
Christian Heimes1c03abd2016-09-06 23:25:35 +02001135 case GEN_RID:
1136 t = PyTuple_New(2);
1137 if (t == NULL)
1138 goto fail;
1139
1140 v = PyUnicode_FromString("Registered ID");
1141 if (v == NULL) {
1142 Py_DECREF(t);
1143 goto fail;
1144 }
1145 PyTuple_SET_ITEM(t, 0, v);
1146
1147 len = i2t_ASN1_OBJECT(buf, sizeof(buf)-1, name->d.rid);
1148 if (len < 0) {
1149 Py_DECREF(t);
1150 _setSSLError(NULL, 0, __FILE__, __LINE__);
1151 goto fail;
1152 } else if (len >= (int)sizeof(buf)) {
1153 v = PyUnicode_FromString("<INVALID>");
1154 } else {
1155 v = PyUnicode_FromStringAndSize(buf, len);
1156 }
1157 if (v == NULL) {
1158 Py_DECREF(t);
1159 goto fail;
1160 }
1161 PyTuple_SET_ITEM(t, 1, v);
1162 break;
1163
Christian Heimes824f7f32013-08-17 00:54:47 +02001164 default:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001165 /* for everything else, we use the OpenSSL print form */
Christian Heimes824f7f32013-08-17 00:54:47 +02001166 switch (gntype) {
1167 /* check for new general name type */
1168 case GEN_OTHERNAME:
1169 case GEN_X400:
1170 case GEN_EDIPARTY:
1171 case GEN_IPADD:
1172 case GEN_RID:
1173 break;
1174 default:
1175 if (PyErr_WarnFormat(PyExc_RuntimeWarning, 1,
1176 "Unknown general name type %d",
1177 gntype) == -1) {
1178 goto fail;
1179 }
1180 break;
1181 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001182 (void) BIO_reset(biobuf);
1183 GENERAL_NAME_print(biobuf, name);
1184 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1185 if (len < 0) {
1186 _setSSLError(NULL, 0, __FILE__, __LINE__);
1187 goto fail;
1188 }
1189 vptr = strchr(buf, ':');
Christian Heimes1c03abd2016-09-06 23:25:35 +02001190 if (vptr == NULL) {
1191 PyErr_Format(PyExc_ValueError,
1192 "Invalid value %.200s",
1193 buf);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001194 goto fail;
Christian Heimes1c03abd2016-09-06 23:25:35 +02001195 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001196 t = PyTuple_New(2);
1197 if (t == NULL)
1198 goto fail;
1199 v = PyUnicode_FromStringAndSize(buf, (vptr - buf));
1200 if (v == NULL) {
1201 Py_DECREF(t);
1202 goto fail;
1203 }
1204 PyTuple_SET_ITEM(t, 0, v);
1205 v = PyUnicode_FromStringAndSize((vptr + 1),
1206 (len - (vptr - buf + 1)));
1207 if (v == NULL) {
1208 Py_DECREF(t);
1209 goto fail;
1210 }
1211 PyTuple_SET_ITEM(t, 1, v);
Christian Heimes824f7f32013-08-17 00:54:47 +02001212 break;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001213 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001214
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001215 /* and add that rendering to the list */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001216
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001217 if (PyList_Append(peer_alt_names, t) < 0) {
1218 Py_DECREF(t);
1219 goto fail;
1220 }
1221 Py_DECREF(t);
1222 }
Antoine Pitrou116d6b92011-11-23 01:39:19 +01001223 sk_GENERAL_NAME_pop_free(names, GENERAL_NAME_free);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001224 }
1225 BIO_free(biobuf);
1226 if (peer_alt_names != Py_None) {
1227 v = PyList_AsTuple(peer_alt_names);
1228 Py_DECREF(peer_alt_names);
1229 return v;
1230 } else {
1231 return peer_alt_names;
1232 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001233
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001234
1235 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001236 if (biobuf != NULL)
1237 BIO_free(biobuf);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001238
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001239 if (peer_alt_names != Py_None) {
1240 Py_XDECREF(peer_alt_names);
1241 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001243 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001244}
1245
1246static PyObject *
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001247_get_aia_uri(X509 *certificate, int nid) {
1248 PyObject *lst = NULL, *ostr = NULL;
1249 int i, result;
1250 AUTHORITY_INFO_ACCESS *info;
1251
1252 info = X509_get_ext_d2i(certificate, NID_info_access, NULL, NULL);
Benjamin Petersonf0c90382015-11-14 15:12:18 -08001253 if (info == NULL)
1254 return Py_None;
1255 if (sk_ACCESS_DESCRIPTION_num(info) == 0) {
1256 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001257 return Py_None;
1258 }
1259
1260 if ((lst = PyList_New(0)) == NULL) {
1261 goto fail;
1262 }
1263
1264 for (i = 0; i < sk_ACCESS_DESCRIPTION_num(info); i++) {
1265 ACCESS_DESCRIPTION *ad = sk_ACCESS_DESCRIPTION_value(info, i);
1266 ASN1_IA5STRING *uri;
1267
1268 if ((OBJ_obj2nid(ad->method) != nid) ||
1269 (ad->location->type != GEN_URI)) {
1270 continue;
1271 }
1272 uri = ad->location->d.uniformResourceIdentifier;
1273 ostr = PyUnicode_FromStringAndSize((char *)uri->data,
1274 uri->length);
1275 if (ostr == NULL) {
1276 goto fail;
1277 }
1278 result = PyList_Append(lst, ostr);
1279 Py_DECREF(ostr);
1280 if (result < 0) {
1281 goto fail;
1282 }
1283 }
1284 AUTHORITY_INFO_ACCESS_free(info);
1285
1286 /* convert to tuple or None */
1287 if (PyList_Size(lst) == 0) {
1288 Py_DECREF(lst);
1289 return Py_None;
1290 } else {
1291 PyObject *tup;
1292 tup = PyList_AsTuple(lst);
1293 Py_DECREF(lst);
1294 return tup;
1295 }
1296
1297 fail:
1298 AUTHORITY_INFO_ACCESS_free(info);
Christian Heimes18fc7be2013-11-21 23:57:49 +01001299 Py_XDECREF(lst);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001300 return NULL;
1301}
1302
1303static PyObject *
1304_get_crl_dp(X509 *certificate) {
1305 STACK_OF(DIST_POINT) *dps;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001306 int i, j;
1307 PyObject *lst, *res = NULL;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001308
Christian Heimes598894f2016-09-05 23:19:05 +02001309 dps = X509_get_ext_d2i(certificate, NID_crl_distribution_points, NULL, NULL);
Christian Heimes949ec142013-11-21 16:26:51 +01001310
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001311 if (dps == NULL)
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001312 return Py_None;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001313
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001314 lst = PyList_New(0);
1315 if (lst == NULL)
1316 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001317
1318 for (i=0; i < sk_DIST_POINT_num(dps); i++) {
1319 DIST_POINT *dp;
1320 STACK_OF(GENERAL_NAME) *gns;
1321
1322 dp = sk_DIST_POINT_value(dps, i);
1323 gns = dp->distpoint->name.fullname;
1324
1325 for (j=0; j < sk_GENERAL_NAME_num(gns); j++) {
1326 GENERAL_NAME *gn;
1327 ASN1_IA5STRING *uri;
1328 PyObject *ouri;
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001329 int err;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001330
1331 gn = sk_GENERAL_NAME_value(gns, j);
1332 if (gn->type != GEN_URI) {
1333 continue;
1334 }
1335 uri = gn->d.uniformResourceIdentifier;
1336 ouri = PyUnicode_FromStringAndSize((char *)uri->data,
1337 uri->length);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001338 if (ouri == NULL)
1339 goto done;
1340
1341 err = PyList_Append(lst, ouri);
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001342 Py_DECREF(ouri);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001343 if (err < 0)
1344 goto done;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001345 }
1346 }
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001347
1348 /* Convert to tuple. */
1349 res = (PyList_GET_SIZE(lst) > 0) ? PyList_AsTuple(lst) : Py_None;
1350
1351 done:
1352 Py_XDECREF(lst);
Olivier Vielpeau2849cc32017-04-14 21:06:07 -04001353 CRL_DIST_POINTS_free(dps);
Benjamin Petersoneda06c82015-11-11 22:07:38 -08001354 return res;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001355}
1356
1357static PyObject *
Antoine Pitroufb046912010-11-09 20:21:19 +00001358_decode_certificate(X509 *certificate) {
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001359
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001360 PyObject *retval = NULL;
1361 BIO *biobuf = NULL;
1362 PyObject *peer;
1363 PyObject *peer_alt_names = NULL;
1364 PyObject *issuer;
1365 PyObject *version;
1366 PyObject *sn_obj;
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001367 PyObject *obj;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001368 ASN1_INTEGER *serialNumber;
1369 char buf[2048];
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001370 int len, result;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001371 ASN1_TIME *notBefore, *notAfter;
1372 PyObject *pnotBefore, *pnotAfter;
Thomas Woutersed03b412007-08-28 21:37:11 +00001373
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001374 retval = PyDict_New();
1375 if (retval == NULL)
1376 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001377
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001378 peer = _create_tuple_for_X509_NAME(
1379 X509_get_subject_name(certificate));
1380 if (peer == NULL)
1381 goto fail0;
1382 if (PyDict_SetItemString(retval, (const char *) "subject", peer) < 0) {
1383 Py_DECREF(peer);
1384 goto fail0;
1385 }
1386 Py_DECREF(peer);
Thomas Woutersed03b412007-08-28 21:37:11 +00001387
Antoine Pitroufb046912010-11-09 20:21:19 +00001388 issuer = _create_tuple_for_X509_NAME(
1389 X509_get_issuer_name(certificate));
1390 if (issuer == NULL)
1391 goto fail0;
1392 if (PyDict_SetItemString(retval, (const char *)"issuer", issuer) < 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001393 Py_DECREF(issuer);
Antoine Pitroufb046912010-11-09 20:21:19 +00001394 goto fail0;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001395 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001396 Py_DECREF(issuer);
1397
1398 version = PyLong_FromLong(X509_get_version(certificate) + 1);
Christian Heimes5962bef2013-07-26 15:51:18 +02001399 if (version == NULL)
1400 goto fail0;
Antoine Pitroufb046912010-11-09 20:21:19 +00001401 if (PyDict_SetItemString(retval, "version", version) < 0) {
1402 Py_DECREF(version);
1403 goto fail0;
1404 }
1405 Py_DECREF(version);
Guido van Rossumf06628b2007-11-21 20:01:53 +00001406
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001407 /* get a memory buffer */
1408 biobuf = BIO_new(BIO_s_mem());
Guido van Rossumf06628b2007-11-21 20:01:53 +00001409
Antoine Pitroufb046912010-11-09 20:21:19 +00001410 (void) BIO_reset(biobuf);
1411 serialNumber = X509_get_serialNumber(certificate);
1412 /* should not exceed 20 octets, 160 bits, so buf is big enough */
1413 i2a_ASN1_INTEGER(biobuf, serialNumber);
1414 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1415 if (len < 0) {
1416 _setSSLError(NULL, 0, __FILE__, __LINE__);
1417 goto fail1;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001418 }
Antoine Pitroufb046912010-11-09 20:21:19 +00001419 sn_obj = PyUnicode_FromStringAndSize(buf, len);
1420 if (sn_obj == NULL)
1421 goto fail1;
1422 if (PyDict_SetItemString(retval, "serialNumber", sn_obj) < 0) {
1423 Py_DECREF(sn_obj);
1424 goto fail1;
1425 }
1426 Py_DECREF(sn_obj);
1427
1428 (void) BIO_reset(biobuf);
1429 notBefore = X509_get_notBefore(certificate);
1430 ASN1_TIME_print(biobuf, notBefore);
1431 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1432 if (len < 0) {
1433 _setSSLError(NULL, 0, __FILE__, __LINE__);
1434 goto fail1;
1435 }
1436 pnotBefore = PyUnicode_FromStringAndSize(buf, len);
1437 if (pnotBefore == NULL)
1438 goto fail1;
1439 if (PyDict_SetItemString(retval, "notBefore", pnotBefore) < 0) {
1440 Py_DECREF(pnotBefore);
1441 goto fail1;
1442 }
1443 Py_DECREF(pnotBefore);
Thomas Woutersed03b412007-08-28 21:37:11 +00001444
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001445 (void) BIO_reset(biobuf);
1446 notAfter = X509_get_notAfter(certificate);
1447 ASN1_TIME_print(biobuf, notAfter);
1448 len = BIO_gets(biobuf, buf, sizeof(buf)-1);
1449 if (len < 0) {
1450 _setSSLError(NULL, 0, __FILE__, __LINE__);
1451 goto fail1;
1452 }
1453 pnotAfter = PyUnicode_FromStringAndSize(buf, len);
1454 if (pnotAfter == NULL)
1455 goto fail1;
1456 if (PyDict_SetItemString(retval, "notAfter", pnotAfter) < 0) {
1457 Py_DECREF(pnotAfter);
1458 goto fail1;
1459 }
1460 Py_DECREF(pnotAfter);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001461
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001462 /* Now look for subjectAltName */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001463
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001464 peer_alt_names = _get_peer_alt_names(certificate);
1465 if (peer_alt_names == NULL)
1466 goto fail1;
1467 else if (peer_alt_names != Py_None) {
1468 if (PyDict_SetItemString(retval, "subjectAltName",
1469 peer_alt_names) < 0) {
1470 Py_DECREF(peer_alt_names);
1471 goto fail1;
1472 }
1473 Py_DECREF(peer_alt_names);
1474 }
Guido van Rossumf06628b2007-11-21 20:01:53 +00001475
Christian Heimesbd3a7f92013-11-21 03:40:15 +01001476 /* Authority Information Access: OCSP URIs */
1477 obj = _get_aia_uri(certificate, NID_ad_OCSP);
1478 if (obj == NULL) {
1479 goto fail1;
1480 } else if (obj != Py_None) {
1481 result = PyDict_SetItemString(retval, "OCSP", obj);
1482 Py_DECREF(obj);
1483 if (result < 0) {
1484 goto fail1;
1485 }
1486 }
1487
1488 obj = _get_aia_uri(certificate, NID_ad_ca_issuers);
1489 if (obj == NULL) {
1490 goto fail1;
1491 } else if (obj != Py_None) {
1492 result = PyDict_SetItemString(retval, "caIssuers", obj);
1493 Py_DECREF(obj);
1494 if (result < 0) {
1495 goto fail1;
1496 }
1497 }
1498
1499 /* CDP (CRL distribution points) */
1500 obj = _get_crl_dp(certificate);
1501 if (obj == NULL) {
1502 goto fail1;
1503 } else if (obj != Py_None) {
1504 result = PyDict_SetItemString(retval, "crlDistributionPoints", obj);
1505 Py_DECREF(obj);
1506 if (result < 0) {
1507 goto fail1;
1508 }
1509 }
1510
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001511 BIO_free(biobuf);
1512 return retval;
Thomas Woutersed03b412007-08-28 21:37:11 +00001513
1514 fail1:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001515 if (biobuf != NULL)
1516 BIO_free(biobuf);
Thomas Woutersed03b412007-08-28 21:37:11 +00001517 fail0:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001518 Py_XDECREF(retval);
1519 return NULL;
Thomas Woutersed03b412007-08-28 21:37:11 +00001520}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001521
Christian Heimes9a5395a2013-06-17 15:44:12 +02001522static PyObject *
1523_certificate_to_der(X509 *certificate)
1524{
1525 unsigned char *bytes_buf = NULL;
1526 int len;
1527 PyObject *retval;
1528
1529 bytes_buf = NULL;
1530 len = i2d_X509(certificate, &bytes_buf);
1531 if (len < 0) {
1532 _setSSLError(NULL, 0, __FILE__, __LINE__);
1533 return NULL;
1534 }
1535 /* this is actually an immutable bytes sequence */
1536 retval = PyBytes_FromStringAndSize((const char *) bytes_buf, len);
1537 OPENSSL_free(bytes_buf);
1538 return retval;
1539}
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001540
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001541/*[clinic input]
1542_ssl._test_decode_cert
1543 path: object(converter="PyUnicode_FSConverter")
1544 /
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001545
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001546[clinic start generated code]*/
1547
1548static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03001549_ssl__test_decode_cert_impl(PyObject *module, PyObject *path)
1550/*[clinic end generated code: output=96becb9abb23c091 input=cdeaaf02d4346628]*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001551{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001552 PyObject *retval = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001553 X509 *x=NULL;
1554 BIO *cert;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001555
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001556 if ((cert=BIO_new(BIO_s_file())) == NULL) {
1557 PyErr_SetString(PySSLErrorObject,
1558 "Can't malloc memory to read file");
1559 goto fail0;
1560 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001561
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001562 if (BIO_read_filename(cert, PyBytes_AsString(path)) <= 0) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001563 PyErr_SetString(PySSLErrorObject,
1564 "Can't open file");
1565 goto fail0;
1566 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001567
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001568 x = PEM_read_bio_X509_AUX(cert,NULL, NULL, NULL);
1569 if (x == NULL) {
1570 PyErr_SetString(PySSLErrorObject,
1571 "Error decoding PEM-encoded file");
1572 goto fail0;
1573 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001574
Antoine Pitroufb046912010-11-09 20:21:19 +00001575 retval = _decode_certificate(x);
Mark Dickinsonee55df52010-08-03 18:31:54 +00001576 X509_free(x);
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001577
1578 fail0:
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001579 Py_DECREF(path);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001580 if (cert != NULL) BIO_free(cert);
1581 return retval;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001582}
1583
1584
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001585/*[clinic input]
1586_ssl._SSLSocket.peer_certificate
1587 der as binary_mode: bool = False
1588 /
1589
1590Returns the certificate for the peer.
1591
1592If no certificate was provided, returns None. If a certificate was
1593provided, but not validated, returns an empty dictionary. Otherwise
1594returns a dict containing information about the peer certificate.
1595
1596If the optional argument is True, returns a DER-encoded copy of the
1597peer certificate, or None if no certificate was provided. This will
1598return the certificate even if it wasn't validated.
1599[clinic start generated code]*/
1600
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001601static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001602_ssl__SSLSocket_peer_certificate_impl(PySSLSocket *self, int binary_mode)
1603/*[clinic end generated code: output=f0dc3e4d1d818a1d input=8281bd1d193db843]*/
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001604{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001605 int verification;
Christian Heimes66dc33b2017-05-23 16:02:02 -07001606 X509 *peer_cert;
1607 PyObject *result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001608
Christian Heimes66dc33b2017-05-23 16:02:02 -07001609 if (!SSL_is_init_finished(self->ssl)) {
Antoine Pitrou20b85552013-09-29 19:50:53 +02001610 PyErr_SetString(PyExc_ValueError,
1611 "handshake not done yet");
1612 return NULL;
1613 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001614 peer_cert = SSL_get_peer_certificate(self->ssl);
1615 if (peer_cert == NULL)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001616 Py_RETURN_NONE;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001617
Antoine Pitrou721738f2012-08-15 23:20:39 +02001618 if (binary_mode) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001619 /* return cert in DER-encoded format */
Christian Heimes66dc33b2017-05-23 16:02:02 -07001620 result = _certificate_to_der(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001621 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00001622 verification = SSL_CTX_get_verify_mode(SSL_get_SSL_CTX(self->ssl));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001623 if ((verification & SSL_VERIFY_PEER) == 0)
Christian Heimes66dc33b2017-05-23 16:02:02 -07001624 result = PyDict_New();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001625 else
Christian Heimes66dc33b2017-05-23 16:02:02 -07001626 result = _decode_certificate(peer_cert);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001627 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07001628 X509_free(peer_cert);
1629 return result;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001630}
1631
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001632static PyObject *
1633cipher_to_tuple(const SSL_CIPHER *cipher)
1634{
1635 const char *cipher_name, *cipher_protocol;
1636 PyObject *v, *retval = PyTuple_New(3);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001637 if (retval == NULL)
1638 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001639
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001640 cipher_name = SSL_CIPHER_get_name(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001641 if (cipher_name == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001642 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001643 PyTuple_SET_ITEM(retval, 0, Py_None);
1644 } else {
1645 v = PyUnicode_FromString(cipher_name);
1646 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001647 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001648 PyTuple_SET_ITEM(retval, 0, v);
1649 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001650
1651 cipher_protocol = SSL_CIPHER_get_version(cipher);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001652 if (cipher_protocol == NULL) {
Hirokazu Yamamoto524f1032010-12-09 10:49:00 +00001653 Py_INCREF(Py_None);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001654 PyTuple_SET_ITEM(retval, 1, Py_None);
1655 } else {
1656 v = PyUnicode_FromString(cipher_protocol);
1657 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001658 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001659 PyTuple_SET_ITEM(retval, 1, v);
1660 }
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001661
1662 v = PyLong_FromLong(SSL_CIPHER_get_bits(cipher, NULL));
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001663 if (v == NULL)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001664 goto fail;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001665 PyTuple_SET_ITEM(retval, 2, v);
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001666
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001667 return retval;
Guido van Rossumf06628b2007-11-21 20:01:53 +00001668
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001669 fail:
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001670 Py_DECREF(retval);
1671 return NULL;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00001672}
1673
Christian Heimes25bfcd52016-09-06 00:04:45 +02001674#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
1675static PyObject *
1676cipher_to_dict(const SSL_CIPHER *cipher)
1677{
1678 const char *cipher_name, *cipher_protocol;
1679
1680 unsigned long cipher_id;
1681 int alg_bits, strength_bits, len;
1682 char buf[512] = {0};
1683#if OPENSSL_VERSION_1_1
1684 int aead, nid;
1685 const char *skcipher = NULL, *digest = NULL, *kx = NULL, *auth = NULL;
1686#endif
Christian Heimes25bfcd52016-09-06 00:04:45 +02001687
1688 /* can be NULL */
1689 cipher_name = SSL_CIPHER_get_name(cipher);
1690 cipher_protocol = SSL_CIPHER_get_version(cipher);
1691 cipher_id = SSL_CIPHER_get_id(cipher);
1692 SSL_CIPHER_description(cipher, buf, sizeof(buf) - 1);
Segev Finer5cff6372017-07-27 01:19:17 +03001693 /* Downcast to avoid a warning. Safe since buf is always 512 bytes */
1694 len = (int)strlen(buf);
Christian Heimes25bfcd52016-09-06 00:04:45 +02001695 if (len > 1 && buf[len-1] == '\n')
1696 buf[len-1] = '\0';
1697 strength_bits = SSL_CIPHER_get_bits(cipher, &alg_bits);
1698
1699#if OPENSSL_VERSION_1_1
1700 aead = SSL_CIPHER_is_aead(cipher);
1701 nid = SSL_CIPHER_get_cipher_nid(cipher);
1702 skcipher = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1703 nid = SSL_CIPHER_get_digest_nid(cipher);
1704 digest = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1705 nid = SSL_CIPHER_get_kx_nid(cipher);
1706 kx = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1707 nid = SSL_CIPHER_get_auth_nid(cipher);
1708 auth = nid != NID_undef ? OBJ_nid2ln(nid) : NULL;
1709#endif
1710
Victor Stinner410b9882016-09-12 12:00:23 +02001711 return Py_BuildValue(
Christian Heimes25bfcd52016-09-06 00:04:45 +02001712 "{sksssssssisi"
1713#if OPENSSL_VERSION_1_1
1714 "sOssssssss"
1715#endif
1716 "}",
1717 "id", cipher_id,
1718 "name", cipher_name,
1719 "protocol", cipher_protocol,
1720 "description", buf,
1721 "strength_bits", strength_bits,
1722 "alg_bits", alg_bits
1723#if OPENSSL_VERSION_1_1
1724 ,"aead", aead ? Py_True : Py_False,
1725 "symmetric", skcipher,
1726 "digest", digest,
1727 "kea", kx,
1728 "auth", auth
1729#endif
1730 );
Christian Heimes25bfcd52016-09-06 00:04:45 +02001731}
1732#endif
1733
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001734/*[clinic input]
1735_ssl._SSLSocket.shared_ciphers
1736[clinic start generated code]*/
1737
1738static PyObject *
1739_ssl__SSLSocket_shared_ciphers_impl(PySSLSocket *self)
1740/*[clinic end generated code: output=3d174ead2e42c4fd input=0bfe149da8fe6306]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001741{
1742 STACK_OF(SSL_CIPHER) *ciphers;
1743 int i;
1744 PyObject *res;
1745
Christian Heimes598894f2016-09-05 23:19:05 +02001746 ciphers = SSL_get_ciphers(self->ssl);
1747 if (!ciphers)
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001748 Py_RETURN_NONE;
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001749 res = PyList_New(sk_SSL_CIPHER_num(ciphers));
1750 if (!res)
1751 return NULL;
1752 for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1753 PyObject *tup = cipher_to_tuple(sk_SSL_CIPHER_value(ciphers, i));
1754 if (!tup) {
1755 Py_DECREF(res);
1756 return NULL;
1757 }
1758 PyList_SET_ITEM(res, i, tup);
1759 }
1760 return res;
1761}
1762
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001763/*[clinic input]
1764_ssl._SSLSocket.cipher
1765[clinic start generated code]*/
1766
1767static PyObject *
1768_ssl__SSLSocket_cipher_impl(PySSLSocket *self)
1769/*[clinic end generated code: output=376417c16d0e5815 input=548fb0e27243796d]*/
Benjamin Peterson4cb17812015-01-07 11:14:26 -06001770{
1771 const SSL_CIPHER *current;
1772
1773 if (self->ssl == NULL)
1774 Py_RETURN_NONE;
1775 current = SSL_get_current_cipher(self->ssl);
1776 if (current == NULL)
1777 Py_RETURN_NONE;
1778 return cipher_to_tuple(current);
1779}
1780
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001781/*[clinic input]
1782_ssl._SSLSocket.version
1783[clinic start generated code]*/
1784
1785static PyObject *
1786_ssl__SSLSocket_version_impl(PySSLSocket *self)
1787/*[clinic end generated code: output=178aed33193b2cdb input=900186a503436fd6]*/
Antoine Pitrou47e40422014-09-04 21:00:10 +02001788{
1789 const char *version;
1790
1791 if (self->ssl == NULL)
1792 Py_RETURN_NONE;
Christian Heimes68771112017-09-05 21:55:40 -07001793 if (!SSL_is_init_finished(self->ssl)) {
1794 /* handshake not finished */
1795 Py_RETURN_NONE;
1796 }
Antoine Pitrou47e40422014-09-04 21:00:10 +02001797 version = SSL_get_version(self->ssl);
1798 if (!strcmp(version, "unknown"))
1799 Py_RETURN_NONE;
1800 return PyUnicode_FromString(version);
1801}
1802
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02001803#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001804/*[clinic input]
1805_ssl._SSLSocket.selected_npn_protocol
1806[clinic start generated code]*/
1807
1808static PyObject *
1809_ssl__SSLSocket_selected_npn_protocol_impl(PySSLSocket *self)
1810/*[clinic end generated code: output=b91d494cd207ecf6 input=c28fde139204b826]*/
1811{
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001812 const unsigned char *out;
1813 unsigned int outlen;
1814
Victor Stinner4569cd52013-06-23 14:58:43 +02001815 SSL_get0_next_proto_negotiated(self->ssl,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001816 &out, &outlen);
1817
1818 if (out == NULL)
1819 Py_RETURN_NONE;
Benjamin Petersoncca27322015-01-23 16:35:37 -05001820 return PyUnicode_FromStringAndSize((char *)out, outlen);
1821}
1822#endif
1823
1824#ifdef HAVE_ALPN
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001825/*[clinic input]
1826_ssl._SSLSocket.selected_alpn_protocol
1827[clinic start generated code]*/
1828
1829static PyObject *
1830_ssl__SSLSocket_selected_alpn_protocol_impl(PySSLSocket *self)
1831/*[clinic end generated code: output=ec33688b303d250f input=442de30e35bc2913]*/
1832{
Benjamin Petersoncca27322015-01-23 16:35:37 -05001833 const unsigned char *out;
1834 unsigned int outlen;
1835
1836 SSL_get0_alpn_selected(self->ssl, &out, &outlen);
1837
1838 if (out == NULL)
1839 Py_RETURN_NONE;
1840 return PyUnicode_FromStringAndSize((char *)out, outlen);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01001841}
1842#endif
1843
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03001844/*[clinic input]
1845_ssl._SSLSocket.compression
1846[clinic start generated code]*/
1847
1848static PyObject *
1849_ssl__SSLSocket_compression_impl(PySSLSocket *self)
1850/*[clinic end generated code: output=bd16cb1bb4646ae7 input=5d059d0a2bbc32c8]*/
1851{
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001852#ifdef OPENSSL_NO_COMP
1853 Py_RETURN_NONE;
1854#else
1855 const COMP_METHOD *comp_method;
1856 const char *short_name;
1857
1858 if (self->ssl == NULL)
1859 Py_RETURN_NONE;
1860 comp_method = SSL_get_current_compression(self->ssl);
Christian Heimes598894f2016-09-05 23:19:05 +02001861 if (comp_method == NULL || COMP_get_type(comp_method) == NID_undef)
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001862 Py_RETURN_NONE;
Christian Heimes281e5f82016-09-06 01:10:39 +02001863 short_name = OBJ_nid2sn(COMP_get_type(comp_method));
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01001864 if (short_name == NULL)
1865 Py_RETURN_NONE;
1866 return PyUnicode_DecodeFSDefault(short_name);
1867#endif
1868}
1869
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001870static PySSLContext *PySSL_get_context(PySSLSocket *self, void *closure) {
1871 Py_INCREF(self->ctx);
1872 return self->ctx;
1873}
1874
1875static int PySSL_set_context(PySSLSocket *self, PyObject *value,
1876 void *closure) {
1877
1878 if (PyObject_TypeCheck(value, &PySSLContext_Type)) {
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001879#if !HAVE_SNI
1880 PyErr_SetString(PyExc_NotImplementedError, "setting a socket's "
1881 "context is not supported by your OpenSSL library");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01001882 return -1;
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001883#else
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001884 Py_INCREF(value);
Serhiy Storchaka57a01d32016-04-10 18:05:40 +03001885 Py_SETREF(self->ctx, (PySSLContext *)value);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001886 SSL_set_SSL_CTX(self->ssl, self->ctx->ctx);
Antoine Pitrou912fbff2013-03-30 16:29:32 +01001887#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001888 } else {
1889 PyErr_SetString(PyExc_TypeError, "The value must be a SSLContext");
1890 return -1;
1891 }
1892
1893 return 0;
1894}
1895
1896PyDoc_STRVAR(PySSL_set_context_doc,
1897"_setter_context(ctx)\n\
1898\
1899This changes the context associated with the SSLSocket. This is typically\n\
1900used from within a callback function set by the set_servername_callback\n\
1901on the SSLContext to change the certificate information associated with the\n\
1902SSLSocket before the cryptographic exchange handshake messages\n");
1903
1904
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001905static PyObject *
1906PySSL_get_server_side(PySSLSocket *self, void *c)
1907{
1908 return PyBool_FromLong(self->socket_type == PY_SSL_SERVER);
1909}
1910
1911PyDoc_STRVAR(PySSL_get_server_side_doc,
1912"Whether this is a server-side socket.");
1913
1914static PyObject *
1915PySSL_get_server_hostname(PySSLSocket *self, void *c)
1916{
1917 if (self->server_hostname == NULL)
1918 Py_RETURN_NONE;
1919 Py_INCREF(self->server_hostname);
1920 return self->server_hostname;
1921}
1922
1923PyDoc_STRVAR(PySSL_get_server_hostname_doc,
1924"The currently set server hostname (for SNI).");
1925
1926static PyObject *
1927PySSL_get_owner(PySSLSocket *self, void *c)
1928{
1929 PyObject *owner;
1930
1931 if (self->owner == NULL)
1932 Py_RETURN_NONE;
1933
1934 owner = PyWeakref_GetObject(self->owner);
1935 Py_INCREF(owner);
1936 return owner;
1937}
1938
1939static int
1940PySSL_set_owner(PySSLSocket *self, PyObject *value, void *c)
1941{
Serhiy Storchaka48842712016-04-06 09:45:48 +03001942 Py_XSETREF(self->owner, PyWeakref_NewRef(value, NULL));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001943 if (self->owner == NULL)
1944 return -1;
1945 return 0;
1946}
1947
1948PyDoc_STRVAR(PySSL_get_owner_doc,
1949"The Python-level owner of this object.\
1950Passed as \"self\" in servername callback.");
1951
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001952
Antoine Pitrou152efa22010-05-16 18:19:27 +00001953static void PySSL_dealloc(PySSLSocket *self)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001954{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001955 if (self->ssl)
1956 SSL_free(self->ssl);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001957 Py_XDECREF(self->Socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01001958 Py_XDECREF(self->ctx);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02001959 Py_XDECREF(self->server_hostname);
1960 Py_XDECREF(self->owner);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001961 PyObject_Del(self);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00001962}
1963
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001964/* If the socket has a timeout, do a select()/poll() on the socket.
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001965 The argument writing indicates the direction.
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001966 Returns one of the possibilities in the timeout_state enum (above).
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001967 */
Andrew M. Kuchling9c3efe32004-07-10 21:15:17 +00001968
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001969static int
Victor Stinner14690702015-04-06 22:46:13 +02001970PySSL_select(PySocketSockObject *s, int writing, _PyTime_t timeout)
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001971{
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001972 int rc;
1973#ifdef HAVE_POLL
1974 struct pollfd pollfd;
1975 _PyTime_t ms;
1976#else
1977 int nfds;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001978 fd_set fds;
1979 struct timeval tv;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001980#endif
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001981
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001982 /* Nothing to do unless we're in timeout mode (not non-blocking) */
Victor Stinner14690702015-04-06 22:46:13 +02001983 if ((s == NULL) || (timeout == 0))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001984 return SOCKET_IS_NONBLOCKING;
Victor Stinner14690702015-04-06 22:46:13 +02001985 else if (timeout < 0) {
1986 if (s->sock_timeout > 0)
1987 return SOCKET_HAS_TIMED_OUT;
1988 else
1989 return SOCKET_IS_BLOCKING;
1990 }
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001991
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001992 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02001993 if (s->sock_fd == INVALID_SOCKET)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001994 return SOCKET_HAS_BEEN_CLOSED;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00001995
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00001996 /* Prefer poll, if available, since you can poll() any fd
1997 * which can't be done with select(). */
Thomas Wouters0e3f5912006-08-11 14:57:12 +00001998#ifdef HAVE_POLL
Victor Stinner4e3cfa42015-04-02 21:28:28 +02001999 pollfd.fd = s->sock_fd;
2000 pollfd.events = writing ? POLLOUT : POLLIN;
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002001
Victor Stinner14690702015-04-06 22:46:13 +02002002 /* timeout is in seconds, poll() uses milliseconds */
2003 ms = (int)_PyTime_AsMilliseconds(timeout, _PyTime_ROUND_CEILING);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002004 assert(ms <= INT_MAX);
Thomas Wouters0e3f5912006-08-11 14:57:12 +00002005
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002006 PySSL_BEGIN_ALLOW_THREADS
2007 rc = poll(&pollfd, 1, (int)ms);
2008 PySSL_END_ALLOW_THREADS
2009#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002010 /* Guard against socket too large for select*/
Charles-François Nataliaa26b272011-08-28 17:51:43 +02002011 if (!_PyIsSelectable_fd(s->sock_fd))
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002012 return SOCKET_TOO_LARGE_FOR_SELECT;
Neal Norwitz082b2df2006-02-07 07:04:46 +00002013
Victor Stinner14690702015-04-06 22:46:13 +02002014 _PyTime_AsTimeval_noraise(timeout, &tv, _PyTime_ROUND_CEILING);
Victor Stinnere2452312015-03-28 03:00:46 +01002015
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002016 FD_ZERO(&fds);
2017 FD_SET(s->sock_fd, &fds);
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002018
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002019 /* Wait until the socket becomes ready */
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002020 PySSL_BEGIN_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002021 nfds = Py_SAFE_DOWNCAST(s->sock_fd+1, SOCKET_T, int);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002022 if (writing)
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002023 rc = select(nfds, NULL, &fds, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002024 else
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002025 rc = select(nfds, &fds, NULL, NULL, &tv);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002026 PySSL_END_ALLOW_THREADS
Bill Janssen6e027db2007-11-15 22:23:56 +00002027#endif
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002028
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002029 /* Return SOCKET_TIMED_OUT on timeout, SOCKET_OPERATION_OK otherwise
2030 (when we are able to write or when there's something to read) */
2031 return rc == 0 ? SOCKET_HAS_TIMED_OUT : SOCKET_OPERATION_OK;
Guido van Rossum99d4abf2003-01-27 22:22:50 +00002032}
2033
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002034/*[clinic input]
2035_ssl._SSLSocket.write
2036 b: Py_buffer
2037 /
2038
2039Writes the bytes-like object b into the SSL object.
2040
2041Returns the number of bytes written.
2042[clinic start generated code]*/
2043
2044static PyObject *
2045_ssl__SSLSocket_write_impl(PySSLSocket *self, Py_buffer *b)
2046/*[clinic end generated code: output=aa7a6be5527358d8 input=77262d994fe5100a]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002047{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002048 int len;
2049 int sockstate;
2050 int err;
2051 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002052 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002053 _PyTime_t timeout, deadline = 0;
2054 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002055
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002056 if (sock != NULL) {
2057 if (((PyObject*)sock) == Py_None) {
2058 _setSSLError("Underlying socket connection gone",
2059 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2060 return NULL;
2061 }
2062 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002063 }
2064
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002065 if (b->len > INT_MAX) {
Victor Stinner6efa9652013-06-25 00:42:31 +02002066 PyErr_Format(PyExc_OverflowError,
2067 "string longer than %d bytes", INT_MAX);
2068 goto error;
2069 }
2070
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002071 if (sock != NULL) {
2072 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002073 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002074 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2075 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2076 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002077
Victor Stinner14690702015-04-06 22:46:13 +02002078 timeout = GET_SOCKET_TIMEOUT(sock);
2079 has_timeout = (timeout > 0);
2080 if (has_timeout)
2081 deadline = _PyTime_GetMonotonicClock() + timeout;
2082
2083 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002084 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002085 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002086 "The write operation timed out");
2087 goto error;
2088 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2089 PyErr_SetString(PySSLErrorObject,
2090 "Underlying socket has been closed.");
2091 goto error;
2092 } else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2093 PyErr_SetString(PySSLErrorObject,
2094 "Underlying socket too large for select().");
2095 goto error;
2096 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002097
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002098 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002099 PySSL_BEGIN_ALLOW_THREADS
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002100 len = SSL_write(self->ssl, b->buf, (int)b->len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002101 _PySSL_UPDATE_ERRNO_IF(len <= 0, self, len);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002102 PySSL_END_ALLOW_THREADS
Steve Dowere6eb48c2017-09-08 15:16:15 -07002103 err = self->ssl_errno;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002104
2105 if (PyErr_CheckSignals())
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002106 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002107
Victor Stinner14690702015-04-06 22:46:13 +02002108 if (has_timeout)
2109 timeout = deadline - _PyTime_GetMonotonicClock();
2110
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002111 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002112 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002113 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002114 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002115 } else {
2116 sockstate = SOCKET_OPERATION_OK;
2117 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002118
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002119 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002120 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002121 "The write operation timed out");
2122 goto error;
2123 } else if (sockstate == SOCKET_HAS_BEEN_CLOSED) {
2124 PyErr_SetString(PySSLErrorObject,
2125 "Underlying socket has been closed.");
2126 goto error;
2127 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2128 break;
2129 }
2130 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002131
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002132 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002133 if (len > 0)
2134 return PyLong_FromLong(len);
2135 else
2136 return PySSL_SetError(self, len, __FILE__, __LINE__);
Antoine Pitrou7d7aede2009-11-25 18:55:32 +00002137
2138error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002139 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002140 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002141}
2142
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002143/*[clinic input]
2144_ssl._SSLSocket.pending
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002145
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002146Returns the number of already decrypted bytes available for read, pending on the connection.
2147[clinic start generated code]*/
2148
2149static PyObject *
2150_ssl__SSLSocket_pending_impl(PySSLSocket *self)
2151/*[clinic end generated code: output=983d9fecdc308a83 input=2b77487d6dfd597f]*/
Bill Janssen6e027db2007-11-15 22:23:56 +00002152{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002153 int count = 0;
Bill Janssen6e027db2007-11-15 22:23:56 +00002154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002155 PySSL_BEGIN_ALLOW_THREADS
2156 count = SSL_pending(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002157 _PySSL_UPDATE_ERRNO_IF(count < 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002158 PySSL_END_ALLOW_THREADS
2159 if (count < 0)
2160 return PySSL_SetError(self, count, __FILE__, __LINE__);
2161 else
2162 return PyLong_FromLong(count);
Bill Janssen6e027db2007-11-15 22:23:56 +00002163}
2164
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002165/*[clinic input]
2166_ssl._SSLSocket.read
2167 size as len: int
2168 [
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002169 buffer: Py_buffer(accept={rwbuffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002170 ]
2171 /
Bill Janssen6e027db2007-11-15 22:23:56 +00002172
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002173Read up to size bytes from the SSL socket.
2174[clinic start generated code]*/
2175
2176static PyObject *
2177_ssl__SSLSocket_read_impl(PySSLSocket *self, int len, int group_right_1,
2178 Py_buffer *buffer)
Larry Hastingsdbfdc382015-05-04 06:59:46 -07002179/*[clinic end generated code: output=00097776cec2a0af input=ff157eb918d0905b]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002180{
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002181 PyObject *dest = NULL;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002182 char *mem;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002183 int count;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002184 int sockstate;
2185 int err;
2186 int nonblocking;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002187 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002188 _PyTime_t timeout, deadline = 0;
2189 int has_timeout;
Bill Janssen54cc54c2007-12-14 22:08:56 +00002190
Martin Panter5503d472016-03-27 05:35:19 +00002191 if (!group_right_1 && len < 0) {
2192 PyErr_SetString(PyExc_ValueError, "size should not be negative");
2193 return NULL;
2194 }
2195
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002196 if (sock != NULL) {
2197 if (((PyObject*)sock) == Py_None) {
2198 _setSSLError("Underlying socket connection gone",
2199 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2200 return NULL;
2201 }
2202 Py_INCREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002203 }
2204
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002205 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002206 dest = PyBytes_FromStringAndSize(NULL, len);
2207 if (dest == NULL)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002208 goto error;
Martin Panterbed7f1a2016-07-11 00:17:13 +00002209 if (len == 0) {
2210 Py_XDECREF(sock);
2211 return dest;
2212 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002213 mem = PyBytes_AS_STRING(dest);
2214 }
2215 else {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002216 mem = buffer->buf;
2217 if (len <= 0 || len > buffer->len) {
2218 len = (int) buffer->len;
2219 if (buffer->len != len) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002220 PyErr_SetString(PyExc_OverflowError,
2221 "maximum length can't fit in a C 'int'");
2222 goto error;
2223 }
Martin Panterbed7f1a2016-07-11 00:17:13 +00002224 if (len == 0) {
2225 count = 0;
2226 goto done;
2227 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002228 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002229 }
2230
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002231 if (sock != NULL) {
2232 /* just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002233 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002234 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2235 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
2236 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002237
Victor Stinner14690702015-04-06 22:46:13 +02002238 timeout = GET_SOCKET_TIMEOUT(sock);
2239 has_timeout = (timeout > 0);
2240 if (has_timeout)
2241 deadline = _PyTime_GetMonotonicClock() + timeout;
2242
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002243 do {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002244 PySSL_BEGIN_ALLOW_THREADS
2245 count = SSL_read(self->ssl, mem, len);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002246 _PySSL_UPDATE_ERRNO_IF(count <= 0, self, count);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002247 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002248
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002249 if (PyErr_CheckSignals())
2250 goto error;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002251
Victor Stinner14690702015-04-06 22:46:13 +02002252 if (has_timeout)
2253 timeout = deadline - _PyTime_GetMonotonicClock();
2254
Steve Dowere6eb48c2017-09-08 15:16:15 -07002255 err = self->ssl_errno;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002256 if (err == SSL_ERROR_WANT_READ) {
Victor Stinner14690702015-04-06 22:46:13 +02002257 sockstate = PySSL_select(sock, 0, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002258 } else if (err == SSL_ERROR_WANT_WRITE) {
Victor Stinner14690702015-04-06 22:46:13 +02002259 sockstate = PySSL_select(sock, 1, timeout);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002260 } else if (err == SSL_ERROR_ZERO_RETURN &&
2261 SSL_get_shutdown(self->ssl) == SSL_RECEIVED_SHUTDOWN)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002262 {
2263 count = 0;
2264 goto done;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002265 }
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002266 else
2267 sockstate = SOCKET_OPERATION_OK;
2268
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002269 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002270 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002271 "The read operation timed out");
2272 goto error;
2273 } else if (sockstate == SOCKET_IS_NONBLOCKING) {
2274 break;
2275 }
2276 } while (err == SSL_ERROR_WANT_READ || err == SSL_ERROR_WANT_WRITE);
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002277
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002278 if (count <= 0) {
2279 PySSL_SetError(self, count, __FILE__, __LINE__);
2280 goto error;
2281 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002282
2283done:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002284 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002285 if (!group_right_1) {
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002286 _PyBytes_Resize(&dest, count);
2287 return dest;
2288 }
2289 else {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002290 return PyLong_FromLong(count);
2291 }
Antoine Pitrou24e561a2010-09-03 18:38:17 +00002292
2293error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002294 Py_XDECREF(sock);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002295 if (!group_right_1)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002296 Py_XDECREF(dest);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002297 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002298}
2299
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002300/*[clinic input]
2301_ssl._SSLSocket.shutdown
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002302
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002303Does the SSL shutdown handshake with the remote end.
2304
2305Returns the underlying socket object.
2306[clinic start generated code]*/
2307
2308static PyObject *
2309_ssl__SSLSocket_shutdown_impl(PySSLSocket *self)
2310/*[clinic end generated code: output=ca1aa7ed9d25ca42 input=ede2cc1a2ddf0ee4]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002311{
Steve Dowere6eb48c2017-09-08 15:16:15 -07002312 int err, sockstate, nonblocking;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002313 int zeros = 0;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002314 PySocketSockObject *sock = GET_SOCKET(self);
Victor Stinner14690702015-04-06 22:46:13 +02002315 _PyTime_t timeout, deadline = 0;
2316 int has_timeout;
Bill Janssen40a0f662008-08-12 16:56:25 +00002317
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002318 if (sock != NULL) {
2319 /* Guard against closed socket */
Victor Stinner524714e2016-07-22 17:43:59 +02002320 if ((((PyObject*)sock) == Py_None) || (sock->sock_fd == INVALID_SOCKET)) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002321 _setSSLError("Underlying socket connection gone",
2322 PY_SSL_ERROR_NO_SOCKET, __FILE__, __LINE__);
2323 return NULL;
2324 }
2325 Py_INCREF(sock);
2326
2327 /* Just in case the blocking state of the socket has been changed */
Victor Stinnere2452312015-03-28 03:00:46 +01002328 nonblocking = (sock->sock_timeout >= 0);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002329 BIO_set_nbio(SSL_get_rbio(self->ssl), nonblocking);
2330 BIO_set_nbio(SSL_get_wbio(self->ssl), nonblocking);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002331 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002332
Victor Stinner14690702015-04-06 22:46:13 +02002333 timeout = GET_SOCKET_TIMEOUT(sock);
2334 has_timeout = (timeout > 0);
2335 if (has_timeout)
2336 deadline = _PyTime_GetMonotonicClock() + timeout;
2337
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002338 while (1) {
2339 PySSL_BEGIN_ALLOW_THREADS
2340 /* Disable read-ahead so that unwrap can work correctly.
2341 * Otherwise OpenSSL might read in too much data,
2342 * eating clear text data that happens to be
2343 * transmitted after the SSL shutdown.
Ezio Melotti85a86292013-08-17 16:57:41 +03002344 * Should be safe to call repeatedly every time this
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002345 * function is used and the shutdown_seen_zero != 0
2346 * condition is met.
2347 */
2348 if (self->shutdown_seen_zero)
2349 SSL_set_read_ahead(self->ssl, 0);
2350 err = SSL_shutdown(self->ssl);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002351 _PySSL_UPDATE_ERRNO_IF(err < 0, self, err);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002352 PySSL_END_ALLOW_THREADS
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002353
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002354 /* If err == 1, a secure shutdown with SSL_shutdown() is complete */
2355 if (err > 0)
2356 break;
2357 if (err == 0) {
2358 /* Don't loop endlessly; instead preserve legacy
2359 behaviour of trying SSL_shutdown() only twice.
2360 This looks necessary for OpenSSL < 0.9.8m */
2361 if (++zeros > 1)
2362 break;
2363 /* Shutdown was sent, now try receiving */
2364 self->shutdown_seen_zero = 1;
2365 continue;
Bill Janssen40a0f662008-08-12 16:56:25 +00002366 }
2367
Victor Stinner14690702015-04-06 22:46:13 +02002368 if (has_timeout)
2369 timeout = deadline - _PyTime_GetMonotonicClock();
2370
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002371 /* Possibly retry shutdown until timeout or failure */
Steve Dowere6eb48c2017-09-08 15:16:15 -07002372 _PySSL_UPDATE_ERRNO(self, err);
2373 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Victor Stinner14690702015-04-06 22:46:13 +02002374 sockstate = PySSL_select(sock, 0, timeout);
Steve Dowere6eb48c2017-09-08 15:16:15 -07002375 else if (self->ssl_errno == SSL_ERROR_WANT_WRITE)
Victor Stinner14690702015-04-06 22:46:13 +02002376 sockstate = PySSL_select(sock, 1, timeout);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002377 else
2378 break;
Victor Stinner4e3cfa42015-04-02 21:28:28 +02002379
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002380 if (sockstate == SOCKET_HAS_TIMED_OUT) {
Steve Dowere6eb48c2017-09-08 15:16:15 -07002381 if (self->ssl_errno == SSL_ERROR_WANT_READ)
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002382 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002383 "The read operation timed out");
2384 else
Antoine Pitrouc4df7842010-12-03 19:59:41 +00002385 PyErr_SetString(PySocketModule.timeout_error,
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002386 "The write operation timed out");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002387 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002388 }
2389 else if (sockstate == SOCKET_TOO_LARGE_FOR_SELECT) {
2390 PyErr_SetString(PySSLErrorObject,
2391 "Underlying socket too large for select().");
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002392 goto error;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002393 }
2394 else if (sockstate != SOCKET_OPERATION_OK)
2395 /* Retain the SSL error code */
2396 break;
2397 }
Antoine Pitrou2c4f98b2010-04-23 00:16:21 +00002398
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002399 if (err < 0) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002400 Py_XDECREF(sock);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002401 return PySSL_SetError(self, err, __FILE__, __LINE__);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002402 }
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002403 if (sock)
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002404 /* It's already INCREF'ed */
2405 return (PyObject *) sock;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002406 else
2407 Py_RETURN_NONE;
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002408
2409error:
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002410 Py_XDECREF(sock);
Antoine Pitrou8bae4ec2010-06-24 22:34:04 +00002411 return NULL;
Bill Janssen40a0f662008-08-12 16:56:25 +00002412}
2413
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002414/*[clinic input]
2415_ssl._SSLSocket.tls_unique_cb
2416
2417Returns the 'tls-unique' channel binding data, as defined by RFC 5929.
2418
2419If the TLS handshake is not yet complete, None is returned.
2420[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00002421
Antoine Pitroud6494802011-07-21 01:11:30 +02002422static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002423_ssl__SSLSocket_tls_unique_cb_impl(PySSLSocket *self)
2424/*[clinic end generated code: output=f3a832d603f586af input=439525c7b3d8d34d]*/
Antoine Pitroud6494802011-07-21 01:11:30 +02002425{
2426 PyObject *retval = NULL;
2427 char buf[PySSL_CB_MAXLEN];
Victor Stinner9ee02032013-06-23 15:08:23 +02002428 size_t len;
Antoine Pitroud6494802011-07-21 01:11:30 +02002429
2430 if (SSL_session_reused(self->ssl) ^ !self->socket_type) {
2431 /* if session is resumed XOR we are the client */
2432 len = SSL_get_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2433 }
2434 else {
2435 /* if a new session XOR we are the server */
2436 len = SSL_get_peer_finished(self->ssl, buf, PySSL_CB_MAXLEN);
2437 }
2438
2439 /* It cannot be negative in current OpenSSL version as of July 2011 */
Antoine Pitroud6494802011-07-21 01:11:30 +02002440 if (len == 0)
2441 Py_RETURN_NONE;
2442
2443 retval = PyBytes_FromStringAndSize(buf, len);
2444
2445 return retval;
2446}
2447
Christian Heimes99a65702016-09-10 23:44:53 +02002448#ifdef OPENSSL_VERSION_1_1
2449
2450static SSL_SESSION*
2451_ssl_session_dup(SSL_SESSION *session) {
2452 SSL_SESSION *newsession = NULL;
2453 int slen;
2454 unsigned char *senc = NULL, *p;
2455 const unsigned char *const_p;
2456
2457 if (session == NULL) {
2458 PyErr_SetString(PyExc_ValueError, "Invalid session");
2459 goto error;
2460 }
2461
2462 /* get length */
2463 slen = i2d_SSL_SESSION(session, NULL);
2464 if (slen == 0 || slen > 0xFF00) {
2465 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2466 goto error;
2467 }
2468 if ((senc = PyMem_Malloc(slen)) == NULL) {
2469 PyErr_NoMemory();
2470 goto error;
2471 }
2472 p = senc;
2473 if (!i2d_SSL_SESSION(session, &p)) {
2474 PyErr_SetString(PyExc_ValueError, "i2d() failed.");
2475 goto error;
2476 }
2477 const_p = senc;
2478 newsession = d2i_SSL_SESSION(NULL, &const_p, slen);
2479 if (session == NULL) {
2480 goto error;
2481 }
2482 PyMem_Free(senc);
2483 return newsession;
2484 error:
2485 if (senc != NULL) {
2486 PyMem_Free(senc);
2487 }
2488 return NULL;
2489}
2490#endif
2491
2492static PyObject *
2493PySSL_get_session(PySSLSocket *self, void *closure) {
2494 /* get_session can return sessions from a server-side connection,
2495 * it does not check for handshake done or client socket. */
2496 PySSLSession *pysess;
2497 SSL_SESSION *session;
2498
2499#ifdef OPENSSL_VERSION_1_1
2500 /* duplicate session as workaround for session bug in OpenSSL 1.1.0,
2501 * https://github.com/openssl/openssl/issues/1550 */
2502 session = SSL_get0_session(self->ssl); /* borrowed reference */
2503 if (session == NULL) {
2504 Py_RETURN_NONE;
2505 }
2506 if ((session = _ssl_session_dup(session)) == NULL) {
2507 return NULL;
2508 }
2509#else
2510 session = SSL_get1_session(self->ssl);
2511 if (session == NULL) {
2512 Py_RETURN_NONE;
2513 }
2514#endif
Christian Heimesa5d07652016-09-24 10:48:05 +02002515 pysess = PyObject_GC_New(PySSLSession, &PySSLSession_Type);
Christian Heimes99a65702016-09-10 23:44:53 +02002516 if (pysess == NULL) {
2517 SSL_SESSION_free(session);
2518 return NULL;
2519 }
2520
2521 assert(self->ctx);
2522 pysess->ctx = self->ctx;
2523 Py_INCREF(pysess->ctx);
2524 pysess->session = session;
Christian Heimesa5d07652016-09-24 10:48:05 +02002525 PyObject_GC_Track(pysess);
Christian Heimes99a65702016-09-10 23:44:53 +02002526 return (PyObject *)pysess;
2527}
2528
2529static int PySSL_set_session(PySSLSocket *self, PyObject *value,
2530 void *closure)
2531 {
2532 PySSLSession *pysess;
2533#ifdef OPENSSL_VERSION_1_1
2534 SSL_SESSION *session;
2535#endif
2536 int result;
2537
2538 if (!PySSLSession_Check(value)) {
2539 PyErr_SetString(PyExc_TypeError, "Value is not a SSLSession.");
2540 return -1;
2541 }
2542 pysess = (PySSLSession *)value;
2543
2544 if (self->ctx->ctx != pysess->ctx->ctx) {
2545 PyErr_SetString(PyExc_ValueError,
2546 "Session refers to a different SSLContext.");
2547 return -1;
2548 }
2549 if (self->socket_type != PY_SSL_CLIENT) {
2550 PyErr_SetString(PyExc_ValueError,
2551 "Cannot set session for server-side SSLSocket.");
2552 return -1;
2553 }
Christian Heimes66dc33b2017-05-23 16:02:02 -07002554 if (SSL_is_init_finished(self->ssl)) {
Christian Heimes99a65702016-09-10 23:44:53 +02002555 PyErr_SetString(PyExc_ValueError,
2556 "Cannot set session after handshake.");
2557 return -1;
2558 }
2559#ifdef OPENSSL_VERSION_1_1
2560 /* duplicate session */
2561 if ((session = _ssl_session_dup(pysess->session)) == NULL) {
2562 return -1;
2563 }
2564 result = SSL_set_session(self->ssl, session);
2565 /* free duplicate, SSL_set_session() bumps ref count */
2566 SSL_SESSION_free(session);
2567#else
2568 result = SSL_set_session(self->ssl, pysess->session);
2569#endif
2570 if (result == 0) {
2571 _setSSLError(NULL, 0, __FILE__, __LINE__);
2572 return -1;
2573 }
2574 return 0;
2575}
2576
2577PyDoc_STRVAR(PySSL_set_session_doc,
2578"_setter_session(session)\n\
2579\
2580Get / set SSLSession.");
2581
2582static PyObject *
2583PySSL_get_session_reused(PySSLSocket *self, void *closure) {
2584 if (SSL_session_reused(self->ssl)) {
2585 Py_RETURN_TRUE;
2586 } else {
2587 Py_RETURN_FALSE;
2588 }
2589}
2590
2591PyDoc_STRVAR(PySSL_get_session_reused_doc,
2592"Was the client session reused during handshake?");
2593
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002594static PyGetSetDef ssl_getsetlist[] = {
2595 {"context", (getter) PySSL_get_context,
2596 (setter) PySSL_set_context, PySSL_set_context_doc},
Antoine Pitroub1fdf472014-10-05 20:41:53 +02002597 {"server_side", (getter) PySSL_get_server_side, NULL,
2598 PySSL_get_server_side_doc},
2599 {"server_hostname", (getter) PySSL_get_server_hostname, NULL,
2600 PySSL_get_server_hostname_doc},
2601 {"owner", (getter) PySSL_get_owner, (setter) PySSL_set_owner,
2602 PySSL_get_owner_doc},
Christian Heimes99a65702016-09-10 23:44:53 +02002603 {"session", (getter) PySSL_get_session,
2604 (setter) PySSL_set_session, PySSL_set_session_doc},
2605 {"session_reused", (getter) PySSL_get_session_reused, NULL,
2606 PySSL_get_session_reused_doc},
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002607 {NULL}, /* sentinel */
2608};
2609
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002610static PyMethodDef PySSLMethods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002611 _SSL__SSLSOCKET_DO_HANDSHAKE_METHODDEF
2612 _SSL__SSLSOCKET_WRITE_METHODDEF
2613 _SSL__SSLSOCKET_READ_METHODDEF
2614 _SSL__SSLSOCKET_PENDING_METHODDEF
2615 _SSL__SSLSOCKET_PEER_CERTIFICATE_METHODDEF
2616 _SSL__SSLSOCKET_CIPHER_METHODDEF
2617 _SSL__SSLSOCKET_SHARED_CIPHERS_METHODDEF
2618 _SSL__SSLSOCKET_VERSION_METHODDEF
2619 _SSL__SSLSOCKET_SELECTED_NPN_PROTOCOL_METHODDEF
2620 _SSL__SSLSOCKET_SELECTED_ALPN_PROTOCOL_METHODDEF
2621 _SSL__SSLSOCKET_COMPRESSION_METHODDEF
2622 _SSL__SSLSOCKET_SHUTDOWN_METHODDEF
2623 _SSL__SSLSOCKET_TLS_UNIQUE_CB_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002624 {NULL, NULL}
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002625};
2626
Antoine Pitrou152efa22010-05-16 18:19:27 +00002627static PyTypeObject PySSLSocket_Type = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002628 PyVarObject_HEAD_INIT(NULL, 0)
Antoine Pitrou152efa22010-05-16 18:19:27 +00002629 "_ssl._SSLSocket", /*tp_name*/
2630 sizeof(PySSLSocket), /*tp_basicsize*/
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00002631 0, /*tp_itemsize*/
2632 /* methods */
2633 (destructor)PySSL_dealloc, /*tp_dealloc*/
2634 0, /*tp_print*/
2635 0, /*tp_getattr*/
2636 0, /*tp_setattr*/
2637 0, /*tp_reserved*/
2638 0, /*tp_repr*/
2639 0, /*tp_as_number*/
2640 0, /*tp_as_sequence*/
2641 0, /*tp_as_mapping*/
2642 0, /*tp_hash*/
2643 0, /*tp_call*/
2644 0, /*tp_str*/
2645 0, /*tp_getattro*/
2646 0, /*tp_setattro*/
2647 0, /*tp_as_buffer*/
2648 Py_TPFLAGS_DEFAULT, /*tp_flags*/
2649 0, /*tp_doc*/
2650 0, /*tp_traverse*/
2651 0, /*tp_clear*/
2652 0, /*tp_richcompare*/
2653 0, /*tp_weaklistoffset*/
2654 0, /*tp_iter*/
2655 0, /*tp_iternext*/
2656 PySSLMethods, /*tp_methods*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002657 0, /*tp_members*/
2658 ssl_getsetlist, /*tp_getset*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00002659};
2660
Antoine Pitrou152efa22010-05-16 18:19:27 +00002661
2662/*
2663 * _SSLContext objects
2664 */
2665
Christian Heimes5fe668c2016-09-12 00:01:11 +02002666static int
2667_set_verify_mode(SSL_CTX *ctx, enum py_ssl_cert_requirements n)
2668{
2669 int mode;
2670 int (*verify_cb)(int, X509_STORE_CTX *) = NULL;
2671
2672 switch(n) {
2673 case PY_SSL_CERT_NONE:
2674 mode = SSL_VERIFY_NONE;
2675 break;
2676 case PY_SSL_CERT_OPTIONAL:
2677 mode = SSL_VERIFY_PEER;
2678 break;
2679 case PY_SSL_CERT_REQUIRED:
2680 mode = SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT;
2681 break;
2682 default:
2683 PyErr_SetString(PyExc_ValueError,
2684 "invalid value for verify_mode");
2685 return -1;
2686 }
2687 /* keep current verify cb */
2688 verify_cb = SSL_CTX_get_verify_callback(ctx);
2689 SSL_CTX_set_verify(ctx, mode, verify_cb);
2690 return 0;
2691}
2692
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002693/*[clinic input]
2694@classmethod
2695_ssl._SSLContext.__new__
2696 protocol as proto_version: int
2697 /
2698[clinic start generated code]*/
2699
Antoine Pitrou152efa22010-05-16 18:19:27 +00002700static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002701_ssl__SSLContext_impl(PyTypeObject *type, int proto_version)
2702/*[clinic end generated code: output=2cf0d7a0741b6bd1 input=8d58a805b95fc534]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002703{
Antoine Pitrou152efa22010-05-16 18:19:27 +00002704 PySSLContext *self;
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002705 long options;
Antoine Pitrou152efa22010-05-16 18:19:27 +00002706 SSL_CTX *ctx = NULL;
Christian Heimes358cfd42016-09-10 22:43:48 +02002707 int result;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002708#if defined(SSL_MODE_RELEASE_BUFFERS)
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002709 unsigned long libver;
Berker Peksagdfcb0412016-04-14 16:48:48 +03002710#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002711
Antoine Pitrou152efa22010-05-16 18:19:27 +00002712 PySSL_BEGIN_ALLOW_THREADS
2713 if (proto_version == PY_SSL_VERSION_TLS1)
2714 ctx = SSL_CTX_new(TLSv1_method());
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01002715#if HAVE_TLSv1_2
2716 else if (proto_version == PY_SSL_VERSION_TLS1_1)
2717 ctx = SSL_CTX_new(TLSv1_1_method());
2718 else if (proto_version == PY_SSL_VERSION_TLS1_2)
2719 ctx = SSL_CTX_new(TLSv1_2_method());
2720#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05002721#ifndef OPENSSL_NO_SSL3
Antoine Pitrou152efa22010-05-16 18:19:27 +00002722 else if (proto_version == PY_SSL_VERSION_SSL3)
2723 ctx = SSL_CTX_new(SSLv3_method());
Benjamin Petersone32467c2014-12-05 21:59:35 -05002724#endif
Victor Stinner3de49192011-05-09 00:42:58 +02002725#ifndef OPENSSL_NO_SSL2
Antoine Pitrou152efa22010-05-16 18:19:27 +00002726 else if (proto_version == PY_SSL_VERSION_SSL2)
2727 ctx = SSL_CTX_new(SSLv2_method());
Victor Stinner3de49192011-05-09 00:42:58 +02002728#endif
Christian Heimes5fe668c2016-09-12 00:01:11 +02002729 else if (proto_version == PY_SSL_VERSION_TLS) /* SSLv23 */
Christian Heimes598894f2016-09-05 23:19:05 +02002730 ctx = SSL_CTX_new(TLS_method());
Christian Heimes5fe668c2016-09-12 00:01:11 +02002731 else if (proto_version == PY_SSL_VERSION_TLS_CLIENT)
2732 ctx = SSL_CTX_new(TLS_client_method());
2733 else if (proto_version == PY_SSL_VERSION_TLS_SERVER)
2734 ctx = SSL_CTX_new(TLS_server_method());
Antoine Pitrou152efa22010-05-16 18:19:27 +00002735 else
2736 proto_version = -1;
2737 PySSL_END_ALLOW_THREADS
2738
2739 if (proto_version == -1) {
2740 PyErr_SetString(PyExc_ValueError,
2741 "invalid protocol version");
2742 return NULL;
2743 }
2744 if (ctx == NULL) {
Christian Heimes17c9ac92017-09-07 14:14:00 -07002745 _setSSLError(NULL, 0, __FILE__, __LINE__);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002746 return NULL;
2747 }
2748
2749 assert(type != NULL && type->tp_alloc != NULL);
2750 self = (PySSLContext *) type->tp_alloc(type, 0);
2751 if (self == NULL) {
2752 SSL_CTX_free(ctx);
2753 return NULL;
2754 }
2755 self->ctx = ctx;
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002756#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Christian Heimes5cb31c92012-09-20 12:42:54 +02002757 self->npn_protocols = NULL;
2758#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002759#ifdef HAVE_ALPN
2760 self->alpn_protocols = NULL;
2761#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002762#ifndef OPENSSL_NO_TLSEXT
Victor Stinner7e001512013-06-25 00:44:31 +02002763 self->set_hostname = NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002764#endif
Christian Heimes1aa9a752013-12-02 02:41:19 +01002765 /* Don't check host name by default */
Christian Heimes5fe668c2016-09-12 00:01:11 +02002766 if (proto_version == PY_SSL_VERSION_TLS_CLIENT) {
2767 self->check_hostname = 1;
2768 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
2769 Py_DECREF(self);
2770 return NULL;
2771 }
2772 } else {
2773 self->check_hostname = 0;
2774 if (_set_verify_mode(self->ctx, PY_SSL_CERT_NONE) == -1) {
2775 Py_DECREF(self);
2776 return NULL;
2777 }
2778 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00002779 /* Defaults */
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002780 options = SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS;
2781 if (proto_version != PY_SSL_VERSION_SSL2)
2782 options |= SSL_OP_NO_SSLv2;
Benjamin Petersona9dcdab2015-11-11 22:38:41 -08002783 if (proto_version != PY_SSL_VERSION_SSL3)
2784 options |= SSL_OP_NO_SSLv3;
Christian Heimes358cfd42016-09-10 22:43:48 +02002785 /* Minimal security flags for server and client side context.
2786 * Client sockets ignore server-side parameters. */
2787#ifdef SSL_OP_NO_COMPRESSION
2788 options |= SSL_OP_NO_COMPRESSION;
2789#endif
2790#ifdef SSL_OP_CIPHER_SERVER_PREFERENCE
2791 options |= SSL_OP_CIPHER_SERVER_PREFERENCE;
2792#endif
2793#ifdef SSL_OP_SINGLE_DH_USE
2794 options |= SSL_OP_SINGLE_DH_USE;
2795#endif
2796#ifdef SSL_OP_SINGLE_ECDH_USE
2797 options |= SSL_OP_SINGLE_ECDH_USE;
2798#endif
Antoine Pitroucd3d7ca2014-01-09 20:02:20 +01002799 SSL_CTX_set_options(self->ctx, options);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002800
Christian Heimes358cfd42016-09-10 22:43:48 +02002801 /* A bare minimum cipher list without completly broken cipher suites.
2802 * It's far from perfect but gives users a better head start. */
2803 if (proto_version != PY_SSL_VERSION_SSL2) {
2804 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL:!MD5");
2805 } else {
2806 /* SSLv2 needs MD5 */
2807 result = SSL_CTX_set_cipher_list(ctx, "HIGH:!aNULL:!eNULL");
2808 }
2809 if (result == 0) {
2810 Py_DECREF(self);
2811 ERR_clear_error();
2812 PyErr_SetString(PySSLErrorObject,
2813 "No cipher can be selected.");
2814 return NULL;
2815 }
2816
Benjamin Peterson3b1a8b32016-01-07 21:37:37 -08002817#if defined(SSL_MODE_RELEASE_BUFFERS)
2818 /* Set SSL_MODE_RELEASE_BUFFERS. This potentially greatly reduces memory
2819 usage for no cost at all. However, don't do this for OpenSSL versions
2820 between 1.0.1 and 1.0.1h or 1.0.0 and 1.0.0m, which are affected by CVE
2821 2014-0198. I can't find exactly which beta fixed this CVE, so be
2822 conservative and assume it wasn't fixed until release. We do this check
2823 at runtime to avoid problems from the dynamic linker.
2824 See #25672 for more on this. */
2825 libver = SSLeay();
2826 if (!(libver >= 0x10001000UL && libver < 0x1000108fUL) &&
2827 !(libver >= 0x10000000UL && libver < 0x100000dfUL)) {
2828 SSL_CTX_set_mode(self->ctx, SSL_MODE_RELEASE_BUFFERS);
2829 }
2830#endif
2831
2832
Donald Stufft8ae264c2017-03-02 11:45:29 -05002833#if !defined(OPENSSL_NO_ECDH) && !defined(OPENSSL_VERSION_1_1)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002834 /* Allow automatic ECDH curve selection (on OpenSSL 1.0.2+), or use
2835 prime256v1 by default. This is Apache mod_ssl's initialization
Christian Heimes598894f2016-09-05 23:19:05 +02002836 policy, so we should be safe. OpenSSL 1.1 has it enabled by default.
2837 */
Donald Stufft8ae264c2017-03-02 11:45:29 -05002838#if defined(SSL_CTX_set_ecdh_auto)
Antoine Pitrou0bebbc32014-03-22 18:13:50 +01002839 SSL_CTX_set_ecdh_auto(self->ctx, 1);
2840#else
2841 {
2842 EC_KEY *key = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
2843 SSL_CTX_set_tmp_ecdh(self->ctx, key);
2844 EC_KEY_free(key);
2845 }
2846#endif
2847#endif
2848
Antoine Pitroufc113ee2010-10-13 12:46:13 +00002849#define SID_CTX "Python"
2850 SSL_CTX_set_session_id_context(self->ctx, (const unsigned char *) SID_CTX,
2851 sizeof(SID_CTX));
2852#undef SID_CTX
2853
Benjamin Petersonfdb19712015-03-04 22:11:12 -05002854#ifdef X509_V_FLAG_TRUSTED_FIRST
2855 {
2856 /* Improve trust chain building when cross-signed intermediate
2857 certificates are present. See https://bugs.python.org/issue23476. */
2858 X509_STORE *store = SSL_CTX_get_cert_store(self->ctx);
2859 X509_STORE_set_flags(store, X509_V_FLAG_TRUSTED_FIRST);
2860 }
2861#endif
2862
Antoine Pitrou152efa22010-05-16 18:19:27 +00002863 return (PyObject *)self;
2864}
2865
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002866static int
2867context_traverse(PySSLContext *self, visitproc visit, void *arg)
2868{
2869#ifndef OPENSSL_NO_TLSEXT
2870 Py_VISIT(self->set_hostname);
2871#endif
2872 return 0;
2873}
2874
2875static int
2876context_clear(PySSLContext *self)
2877{
2878#ifndef OPENSSL_NO_TLSEXT
2879 Py_CLEAR(self->set_hostname);
2880#endif
2881 return 0;
2882}
2883
Antoine Pitrou152efa22010-05-16 18:19:27 +00002884static void
2885context_dealloc(PySSLContext *self)
2886{
INADA Naokia6296d32017-08-24 14:55:17 +09002887 /* bpo-31095: UnTrack is needed before calling any callbacks */
2888 PyObject_GC_UnTrack(self);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01002889 context_clear(self);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002890 SSL_CTX_free(self->ctx);
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002891#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002892 PyMem_FREE(self->npn_protocols);
2893#endif
2894#ifdef HAVE_ALPN
2895 PyMem_FREE(self->alpn_protocols);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002896#endif
Antoine Pitrou152efa22010-05-16 18:19:27 +00002897 Py_TYPE(self)->tp_free(self);
2898}
2899
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002900/*[clinic input]
2901_ssl._SSLContext.set_ciphers
2902 cipherlist: str
2903 /
2904[clinic start generated code]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00002905
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03002906static PyObject *
2907_ssl__SSLContext_set_ciphers_impl(PySSLContext *self, const char *cipherlist)
2908/*[clinic end generated code: output=3a3162f3557c0f3f input=a7ac931b9f3ca7fc]*/
2909{
2910 int ret = SSL_CTX_set_cipher_list(self->ctx, cipherlist);
Antoine Pitrou152efa22010-05-16 18:19:27 +00002911 if (ret == 0) {
Antoine Pitrou65ec8ae2010-05-16 19:56:32 +00002912 /* Clearing the error queue is necessary on some OpenSSL versions,
2913 otherwise the error will be reported again when another SSL call
2914 is done. */
2915 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00002916 PyErr_SetString(PySSLErrorObject,
2917 "No cipher can be selected.");
2918 return NULL;
2919 }
2920 Py_RETURN_NONE;
2921}
2922
Christian Heimes25bfcd52016-09-06 00:04:45 +02002923#if OPENSSL_VERSION_NUMBER >= 0x10002000UL
2924/*[clinic input]
2925_ssl._SSLContext.get_ciphers
2926[clinic start generated code]*/
2927
2928static PyObject *
2929_ssl__SSLContext_get_ciphers_impl(PySSLContext *self)
2930/*[clinic end generated code: output=a56e4d68a406dfc4 input=a2aadc9af89b79c5]*/
2931{
2932 SSL *ssl = NULL;
2933 STACK_OF(SSL_CIPHER) *sk = NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02002934 const SSL_CIPHER *cipher;
Christian Heimes25bfcd52016-09-06 00:04:45 +02002935 int i=0;
2936 PyObject *result = NULL, *dct;
2937
2938 ssl = SSL_new(self->ctx);
2939 if (ssl == NULL) {
2940 _setSSLError(NULL, 0, __FILE__, __LINE__);
2941 goto exit;
2942 }
2943 sk = SSL_get_ciphers(ssl);
2944
2945 result = PyList_New(sk_SSL_CIPHER_num(sk));
2946 if (result == NULL) {
2947 goto exit;
2948 }
2949
2950 for (i = 0; i < sk_SSL_CIPHER_num(sk); i++) {
2951 cipher = sk_SSL_CIPHER_value(sk, i);
2952 dct = cipher_to_dict(cipher);
2953 if (dct == NULL) {
2954 Py_CLEAR(result);
2955 goto exit;
2956 }
2957 PyList_SET_ITEM(result, i, dct);
2958 }
2959
2960 exit:
2961 if (ssl != NULL)
2962 SSL_free(ssl);
2963 return result;
2964
2965}
2966#endif
2967
2968
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002969#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG) || defined(HAVE_ALPN)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002970static int
Benjamin Peterson88615022015-01-23 17:30:26 -05002971do_protocol_selection(int alpn, unsigned char **out, unsigned char *outlen,
2972 const unsigned char *server_protocols, unsigned int server_protocols_len,
2973 const unsigned char *client_protocols, unsigned int client_protocols_len)
Benjamin Petersoncca27322015-01-23 16:35:37 -05002974{
Benjamin Peterson88615022015-01-23 17:30:26 -05002975 int ret;
2976 if (client_protocols == NULL) {
2977 client_protocols = (unsigned char *)"";
2978 client_protocols_len = 0;
2979 }
2980 if (server_protocols == NULL) {
2981 server_protocols = (unsigned char *)"";
2982 server_protocols_len = 0;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002983 }
2984
Benjamin Peterson88615022015-01-23 17:30:26 -05002985 ret = SSL_select_next_proto(out, outlen,
2986 server_protocols, server_protocols_len,
2987 client_protocols, client_protocols_len);
2988 if (alpn && ret != OPENSSL_NPN_NEGOTIATED)
2989 return SSL_TLSEXT_ERR_NOACK;
Benjamin Petersoncca27322015-01-23 16:35:37 -05002990
2991 return SSL_TLSEXT_ERR_OK;
2992}
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002993#endif
Benjamin Petersoncca27322015-01-23 16:35:37 -05002994
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02002995#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01002996/* this callback gets passed to SSL_CTX_set_next_protos_advertise_cb */
2997static int
Victor Stinner4569cd52013-06-23 14:58:43 +02002998_advertiseNPN_cb(SSL *s,
2999 const unsigned char **data, unsigned int *len,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003000 void *args)
3001{
3002 PySSLContext *ssl_ctx = (PySSLContext *) args;
3003
3004 if (ssl_ctx->npn_protocols == NULL) {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003005 *data = (unsigned char *)"";
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003006 *len = 0;
3007 } else {
Benjamin Petersoncca27322015-01-23 16:35:37 -05003008 *data = ssl_ctx->npn_protocols;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003009 *len = ssl_ctx->npn_protocols_len;
3010 }
3011
3012 return SSL_TLSEXT_ERR_OK;
3013}
3014/* this callback gets passed to SSL_CTX_set_next_proto_select_cb */
3015static int
Victor Stinner4569cd52013-06-23 14:58:43 +02003016_selectNPN_cb(SSL *s,
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003017 unsigned char **out, unsigned char *outlen,
3018 const unsigned char *server, unsigned int server_len,
3019 void *args)
3020{
Benjamin Petersoncca27322015-01-23 16:35:37 -05003021 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003022 return do_protocol_selection(0, out, outlen, server, server_len,
Benjamin Petersoncca27322015-01-23 16:35:37 -05003023 ctx->npn_protocols, ctx->npn_protocols_len);
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003024}
3025#endif
3026
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003027/*[clinic input]
3028_ssl._SSLContext._set_npn_protocols
3029 protos: Py_buffer
3030 /
3031[clinic start generated code]*/
3032
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003033static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003034_ssl__SSLContext__set_npn_protocols_impl(PySSLContext *self,
3035 Py_buffer *protos)
3036/*[clinic end generated code: output=72b002c3324390c6 input=319fcb66abf95bd7]*/
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003037{
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02003038#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003039 PyMem_Free(self->npn_protocols);
3040 self->npn_protocols = PyMem_Malloc(protos->len);
3041 if (self->npn_protocols == NULL)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003042 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003043 memcpy(self->npn_protocols, protos->buf, protos->len);
3044 self->npn_protocols_len = (int) protos->len;
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003045
3046 /* set both server and client callbacks, because the context can
3047 * be used to create both types of sockets */
3048 SSL_CTX_set_next_protos_advertised_cb(self->ctx,
3049 _advertiseNPN_cb,
3050 self);
3051 SSL_CTX_set_next_proto_select_cb(self->ctx,
3052 _selectNPN_cb,
3053 self);
3054
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01003055 Py_RETURN_NONE;
3056#else
3057 PyErr_SetString(PyExc_NotImplementedError,
3058 "The NPN extension requires OpenSSL 1.0.1 or later.");
3059 return NULL;
3060#endif
3061}
3062
Benjamin Petersoncca27322015-01-23 16:35:37 -05003063#ifdef HAVE_ALPN
3064static int
3065_selectALPN_cb(SSL *s,
3066 const unsigned char **out, unsigned char *outlen,
3067 const unsigned char *client_protocols, unsigned int client_protocols_len,
3068 void *args)
3069{
3070 PySSLContext *ctx = (PySSLContext *)args;
Benjamin Peterson88615022015-01-23 17:30:26 -05003071 return do_protocol_selection(1, (unsigned char **)out, outlen,
3072 ctx->alpn_protocols, ctx->alpn_protocols_len,
3073 client_protocols, client_protocols_len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003074}
3075#endif
3076
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003077/*[clinic input]
3078_ssl._SSLContext._set_alpn_protocols
3079 protos: Py_buffer
3080 /
3081[clinic start generated code]*/
3082
Benjamin Petersoncca27322015-01-23 16:35:37 -05003083static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003084_ssl__SSLContext__set_alpn_protocols_impl(PySSLContext *self,
3085 Py_buffer *protos)
3086/*[clinic end generated code: output=87599a7f76651a9b input=9bba964595d519be]*/
Benjamin Petersoncca27322015-01-23 16:35:37 -05003087{
3088#ifdef HAVE_ALPN
Victor Stinner5a615592017-09-14 01:10:30 -07003089 if ((size_t)protos->len > UINT_MAX) {
Segev Finer5cff6372017-07-27 01:19:17 +03003090 PyErr_Format(PyExc_OverflowError,
3091 "protocols longer than %d bytes", UINT_MAX);
3092 return NULL;
3093 }
3094
Benjamin Petersoncca27322015-01-23 16:35:37 -05003095 PyMem_FREE(self->alpn_protocols);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003096 self->alpn_protocols = PyMem_Malloc(protos->len);
Benjamin Petersoncca27322015-01-23 16:35:37 -05003097 if (!self->alpn_protocols)
3098 return PyErr_NoMemory();
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003099 memcpy(self->alpn_protocols, protos->buf, protos->len);
Segev Finer5cff6372017-07-27 01:19:17 +03003100 self->alpn_protocols_len = (unsigned int)protos->len;
Benjamin Petersoncca27322015-01-23 16:35:37 -05003101
3102 if (SSL_CTX_set_alpn_protos(self->ctx, self->alpn_protocols, self->alpn_protocols_len))
3103 return PyErr_NoMemory();
3104 SSL_CTX_set_alpn_select_cb(self->ctx, _selectALPN_cb, self);
3105
Benjamin Petersoncca27322015-01-23 16:35:37 -05003106 Py_RETURN_NONE;
3107#else
3108 PyErr_SetString(PyExc_NotImplementedError,
3109 "The ALPN extension requires OpenSSL 1.0.2 or later.");
3110 return NULL;
3111#endif
3112}
3113
Antoine Pitrou152efa22010-05-16 18:19:27 +00003114static PyObject *
3115get_verify_mode(PySSLContext *self, void *c)
3116{
3117 switch (SSL_CTX_get_verify_mode(self->ctx)) {
3118 case SSL_VERIFY_NONE:
3119 return PyLong_FromLong(PY_SSL_CERT_NONE);
3120 case SSL_VERIFY_PEER:
3121 return PyLong_FromLong(PY_SSL_CERT_OPTIONAL);
3122 case SSL_VERIFY_PEER | SSL_VERIFY_FAIL_IF_NO_PEER_CERT:
3123 return PyLong_FromLong(PY_SSL_CERT_REQUIRED);
3124 }
3125 PyErr_SetString(PySSLErrorObject,
3126 "invalid return value from SSL_CTX_get_verify_mode");
3127 return NULL;
3128}
3129
3130static int
3131set_verify_mode(PySSLContext *self, PyObject *arg, void *c)
3132{
Christian Heimes5fe668c2016-09-12 00:01:11 +02003133 int n;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003134 if (!PyArg_Parse(arg, "i", &n))
3135 return -1;
Christian Heimes5fe668c2016-09-12 00:01:11 +02003136 if (n == PY_SSL_CERT_NONE && self->check_hostname) {
Christian Heimes1aa9a752013-12-02 02:41:19 +01003137 PyErr_SetString(PyExc_ValueError,
3138 "Cannot set verify_mode to CERT_NONE when "
3139 "check_hostname is enabled.");
3140 return -1;
3141 }
Christian Heimes5fe668c2016-09-12 00:01:11 +02003142 return _set_verify_mode(self->ctx, n);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003143}
3144
3145static PyObject *
Christian Heimes22587792013-11-21 23:56:13 +01003146get_verify_flags(PySSLContext *self, void *c)
3147{
3148 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003149 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003150 unsigned long flags;
3151
3152 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003153 param = X509_STORE_get0_param(store);
3154 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003155 return PyLong_FromUnsignedLong(flags);
3156}
3157
3158static int
3159set_verify_flags(PySSLContext *self, PyObject *arg, void *c)
3160{
3161 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02003162 X509_VERIFY_PARAM *param;
Christian Heimes22587792013-11-21 23:56:13 +01003163 unsigned long new_flags, flags, set, clear;
3164
3165 if (!PyArg_Parse(arg, "k", &new_flags))
3166 return -1;
3167 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02003168 param = X509_STORE_get0_param(store);
3169 flags = X509_VERIFY_PARAM_get_flags(param);
Christian Heimes22587792013-11-21 23:56:13 +01003170 clear = flags & ~new_flags;
3171 set = ~flags & new_flags;
3172 if (clear) {
Christian Heimes598894f2016-09-05 23:19:05 +02003173 if (!X509_VERIFY_PARAM_clear_flags(param, clear)) {
Christian Heimes22587792013-11-21 23:56:13 +01003174 _setSSLError(NULL, 0, __FILE__, __LINE__);
3175 return -1;
3176 }
3177 }
3178 if (set) {
Christian Heimes598894f2016-09-05 23:19:05 +02003179 if (!X509_VERIFY_PARAM_set_flags(param, set)) {
Christian Heimes22587792013-11-21 23:56:13 +01003180 _setSSLError(NULL, 0, __FILE__, __LINE__);
3181 return -1;
3182 }
3183 }
3184 return 0;
3185}
3186
3187static PyObject *
Antoine Pitroub5218772010-05-21 09:56:06 +00003188get_options(PySSLContext *self, void *c)
3189{
3190 return PyLong_FromLong(SSL_CTX_get_options(self->ctx));
3191}
3192
3193static int
3194set_options(PySSLContext *self, PyObject *arg, void *c)
3195{
3196 long new_opts, opts, set, clear;
3197 if (!PyArg_Parse(arg, "l", &new_opts))
3198 return -1;
3199 opts = SSL_CTX_get_options(self->ctx);
3200 clear = opts & ~new_opts;
3201 set = ~opts & new_opts;
3202 if (clear) {
3203#ifdef HAVE_SSL_CTX_CLEAR_OPTIONS
3204 SSL_CTX_clear_options(self->ctx, clear);
3205#else
3206 PyErr_SetString(PyExc_ValueError,
3207 "can't clear options before OpenSSL 0.9.8m");
3208 return -1;
3209#endif
3210 }
3211 if (set)
3212 SSL_CTX_set_options(self->ctx, set);
3213 return 0;
3214}
3215
Christian Heimes1aa9a752013-12-02 02:41:19 +01003216static PyObject *
3217get_check_hostname(PySSLContext *self, void *c)
3218{
3219 return PyBool_FromLong(self->check_hostname);
3220}
3221
3222static int
3223set_check_hostname(PySSLContext *self, PyObject *arg, void *c)
3224{
3225 int check_hostname;
3226 if (!PyArg_Parse(arg, "p", &check_hostname))
3227 return -1;
3228 if (check_hostname &&
3229 SSL_CTX_get_verify_mode(self->ctx) == SSL_VERIFY_NONE) {
Christian Heimese82c0342017-09-15 20:29:57 +02003230 /* check_hostname = True sets verify_mode = CERT_REQUIRED */
3231 if (_set_verify_mode(self->ctx, PY_SSL_CERT_REQUIRED) == -1) {
3232 return -1;
3233 }
Christian Heimes1aa9a752013-12-02 02:41:19 +01003234 }
3235 self->check_hostname = check_hostname;
3236 return 0;
3237}
3238
3239
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003240typedef struct {
3241 PyThreadState *thread_state;
3242 PyObject *callable;
3243 char *password;
Victor Stinner9ee02032013-06-23 15:08:23 +02003244 int size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003245 int error;
3246} _PySSLPasswordInfo;
3247
3248static int
3249_pwinfo_set(_PySSLPasswordInfo *pw_info, PyObject* password,
3250 const char *bad_type_error)
3251{
3252 /* Set the password and size fields of a _PySSLPasswordInfo struct
3253 from a unicode, bytes, or byte array object.
3254 The password field will be dynamically allocated and must be freed
3255 by the caller */
3256 PyObject *password_bytes = NULL;
3257 const char *data = NULL;
3258 Py_ssize_t size;
3259
3260 if (PyUnicode_Check(password)) {
3261 password_bytes = PyUnicode_AsEncodedString(password, NULL, NULL);
3262 if (!password_bytes) {
3263 goto error;
3264 }
3265 data = PyBytes_AS_STRING(password_bytes);
3266 size = PyBytes_GET_SIZE(password_bytes);
3267 } else if (PyBytes_Check(password)) {
3268 data = PyBytes_AS_STRING(password);
3269 size = PyBytes_GET_SIZE(password);
3270 } else if (PyByteArray_Check(password)) {
3271 data = PyByteArray_AS_STRING(password);
3272 size = PyByteArray_GET_SIZE(password);
3273 } else {
3274 PyErr_SetString(PyExc_TypeError, bad_type_error);
3275 goto error;
3276 }
3277
Victor Stinner9ee02032013-06-23 15:08:23 +02003278 if (size > (Py_ssize_t)INT_MAX) {
3279 PyErr_Format(PyExc_ValueError,
3280 "password cannot be longer than %d bytes", INT_MAX);
3281 goto error;
3282 }
3283
Victor Stinner11ebff22013-07-07 17:07:52 +02003284 PyMem_Free(pw_info->password);
3285 pw_info->password = PyMem_Malloc(size);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003286 if (!pw_info->password) {
3287 PyErr_SetString(PyExc_MemoryError,
3288 "unable to allocate password buffer");
3289 goto error;
3290 }
3291 memcpy(pw_info->password, data, size);
Victor Stinner9ee02032013-06-23 15:08:23 +02003292 pw_info->size = (int)size;
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003293
3294 Py_XDECREF(password_bytes);
3295 return 1;
3296
3297error:
3298 Py_XDECREF(password_bytes);
3299 return 0;
3300}
3301
3302static int
3303_password_callback(char *buf, int size, int rwflag, void *userdata)
3304{
3305 _PySSLPasswordInfo *pw_info = (_PySSLPasswordInfo*) userdata;
3306 PyObject *fn_ret = NULL;
3307
3308 PySSL_END_ALLOW_THREADS_S(pw_info->thread_state);
3309
3310 if (pw_info->callable) {
Victor Stinnerf17c3de2016-12-06 18:46:19 +01003311 fn_ret = _PyObject_CallNoArg(pw_info->callable);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003312 if (!fn_ret) {
3313 /* TODO: It would be nice to move _ctypes_add_traceback() into the
3314 core python API, so we could use it to add a frame here */
3315 goto error;
3316 }
3317
3318 if (!_pwinfo_set(pw_info, fn_ret,
3319 "password callback must return a string")) {
3320 goto error;
3321 }
3322 Py_CLEAR(fn_ret);
3323 }
3324
3325 if (pw_info->size > size) {
3326 PyErr_Format(PyExc_ValueError,
3327 "password cannot be longer than %d bytes", size);
3328 goto error;
3329 }
3330
3331 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3332 memcpy(buf, pw_info->password, pw_info->size);
3333 return pw_info->size;
3334
3335error:
3336 Py_XDECREF(fn_ret);
3337 PySSL_BEGIN_ALLOW_THREADS_S(pw_info->thread_state);
3338 pw_info->error = 1;
3339 return -1;
3340}
3341
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003342/*[clinic input]
3343_ssl._SSLContext.load_cert_chain
3344 certfile: object
3345 keyfile: object = NULL
3346 password: object = NULL
3347
3348[clinic start generated code]*/
3349
Antoine Pitroub5218772010-05-21 09:56:06 +00003350static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003351_ssl__SSLContext_load_cert_chain_impl(PySSLContext *self, PyObject *certfile,
3352 PyObject *keyfile, PyObject *password)
3353/*[clinic end generated code: output=9480bc1c380e2095 input=7cf9ac673cbee6fc]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003354{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003355 PyObject *certfile_bytes = NULL, *keyfile_bytes = NULL;
Christian Heimes598894f2016-09-05 23:19:05 +02003356 pem_password_cb *orig_passwd_cb = SSL_CTX_get_default_passwd_cb(self->ctx);
3357 void *orig_passwd_userdata = SSL_CTX_get_default_passwd_cb_userdata(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003358 _PySSLPasswordInfo pw_info = { NULL, NULL, NULL, 0, 0 };
Antoine Pitrou152efa22010-05-16 18:19:27 +00003359 int r;
3360
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003361 errno = 0;
Antoine Pitrou67e8e562010-09-01 20:55:41 +00003362 ERR_clear_error();
Antoine Pitrou152efa22010-05-16 18:19:27 +00003363 if (keyfile == Py_None)
3364 keyfile = NULL;
3365 if (!PyUnicode_FSConverter(certfile, &certfile_bytes)) {
3366 PyErr_SetString(PyExc_TypeError,
3367 "certfile should be a valid filesystem path");
3368 return NULL;
3369 }
3370 if (keyfile && !PyUnicode_FSConverter(keyfile, &keyfile_bytes)) {
3371 PyErr_SetString(PyExc_TypeError,
3372 "keyfile should be a valid filesystem path");
3373 goto error;
3374 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003375 if (password && password != Py_None) {
3376 if (PyCallable_Check(password)) {
3377 pw_info.callable = password;
3378 } else if (!_pwinfo_set(&pw_info, password,
3379 "password should be a string or callable")) {
3380 goto error;
3381 }
3382 SSL_CTX_set_default_passwd_cb(self->ctx, _password_callback);
3383 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, &pw_info);
3384 }
3385 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003386 r = SSL_CTX_use_certificate_chain_file(self->ctx,
3387 PyBytes_AS_STRING(certfile_bytes));
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003388 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003389 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003390 if (pw_info.error) {
3391 ERR_clear_error();
3392 /* the password callback has already set the error information */
3393 }
3394 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003395 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003396 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003397 }
3398 else {
3399 _setSSLError(NULL, 0, __FILE__, __LINE__);
3400 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003401 goto error;
3402 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003403 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou9c254862011-04-03 18:15:34 +02003404 r = SSL_CTX_use_PrivateKey_file(self->ctx,
Antoine Pitrou152efa22010-05-16 18:19:27 +00003405 PyBytes_AS_STRING(keyfile ? keyfile_bytes : certfile_bytes),
3406 SSL_FILETYPE_PEM);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003407 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
3408 Py_CLEAR(keyfile_bytes);
3409 Py_CLEAR(certfile_bytes);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003410 if (r != 1) {
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003411 if (pw_info.error) {
3412 ERR_clear_error();
3413 /* the password callback has already set the error information */
3414 }
3415 else if (errno != 0) {
Giampaolo Rodolàe0f98632010-09-01 19:28:49 +00003416 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003417 PyErr_SetFromErrno(PyExc_OSError);
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003418 }
3419 else {
3420 _setSSLError(NULL, 0, __FILE__, __LINE__);
3421 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003422 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003423 }
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003424 PySSL_BEGIN_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003425 r = SSL_CTX_check_private_key(self->ctx);
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003426 PySSL_END_ALLOW_THREADS_S(pw_info.thread_state);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003427 if (r != 1) {
3428 _setSSLError(NULL, 0, __FILE__, __LINE__);
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 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3432 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003433 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003434 Py_RETURN_NONE;
3435
3436error:
Antoine Pitrou4fd1e6a2011-08-25 14:39:44 +02003437 SSL_CTX_set_default_passwd_cb(self->ctx, orig_passwd_cb);
3438 SSL_CTX_set_default_passwd_cb_userdata(self->ctx, orig_passwd_userdata);
Victor Stinner11ebff22013-07-07 17:07:52 +02003439 PyMem_Free(pw_info.password);
Antoine Pitrou152efa22010-05-16 18:19:27 +00003440 Py_XDECREF(keyfile_bytes);
3441 Py_XDECREF(certfile_bytes);
3442 return NULL;
3443}
3444
Christian Heimesefff7062013-11-21 03:35:02 +01003445/* internal helper function, returns -1 on error
3446 */
3447static int
3448_add_ca_certs(PySSLContext *self, void *data, Py_ssize_t len,
3449 int filetype)
3450{
3451 BIO *biobuf = NULL;
3452 X509_STORE *store;
3453 int retval = 0, err, loaded = 0;
3454
3455 assert(filetype == SSL_FILETYPE_ASN1 || filetype == SSL_FILETYPE_PEM);
3456
3457 if (len <= 0) {
3458 PyErr_SetString(PyExc_ValueError,
3459 "Empty certificate data");
3460 return -1;
3461 } else if (len > INT_MAX) {
3462 PyErr_SetString(PyExc_OverflowError,
3463 "Certificate data is too long.");
3464 return -1;
3465 }
3466
Christian Heimes1dbf61f2013-11-22 00:34:18 +01003467 biobuf = BIO_new_mem_buf(data, (int)len);
Christian Heimesefff7062013-11-21 03:35:02 +01003468 if (biobuf == NULL) {
3469 _setSSLError("Can't allocate buffer", 0, __FILE__, __LINE__);
3470 return -1;
3471 }
3472
3473 store = SSL_CTX_get_cert_store(self->ctx);
3474 assert(store != NULL);
3475
3476 while (1) {
3477 X509 *cert = NULL;
3478 int r;
3479
3480 if (filetype == SSL_FILETYPE_ASN1) {
3481 cert = d2i_X509_bio(biobuf, NULL);
3482 } else {
3483 cert = PEM_read_bio_X509(biobuf, NULL,
Christian Heimes598894f2016-09-05 23:19:05 +02003484 SSL_CTX_get_default_passwd_cb(self->ctx),
3485 SSL_CTX_get_default_passwd_cb_userdata(self->ctx)
3486 );
Christian Heimesefff7062013-11-21 03:35:02 +01003487 }
3488 if (cert == NULL) {
3489 break;
3490 }
3491 r = X509_STORE_add_cert(store, cert);
3492 X509_free(cert);
3493 if (!r) {
3494 err = ERR_peek_last_error();
3495 if ((ERR_GET_LIB(err) == ERR_LIB_X509) &&
3496 (ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE)) {
3497 /* cert already in hash table, not an error */
3498 ERR_clear_error();
3499 } else {
3500 break;
3501 }
3502 }
3503 loaded++;
3504 }
3505
3506 err = ERR_peek_last_error();
3507 if ((filetype == SSL_FILETYPE_ASN1) &&
3508 (loaded > 0) &&
3509 (ERR_GET_LIB(err) == ERR_LIB_ASN1) &&
3510 (ERR_GET_REASON(err) == ASN1_R_HEADER_TOO_LONG)) {
3511 /* EOF ASN1 file, not an error */
3512 ERR_clear_error();
3513 retval = 0;
3514 } else if ((filetype == SSL_FILETYPE_PEM) &&
3515 (loaded > 0) &&
3516 (ERR_GET_LIB(err) == ERR_LIB_PEM) &&
3517 (ERR_GET_REASON(err) == PEM_R_NO_START_LINE)) {
3518 /* EOF PEM file, not an error */
3519 ERR_clear_error();
3520 retval = 0;
3521 } else {
3522 _setSSLError(NULL, 0, __FILE__, __LINE__);
3523 retval = -1;
3524 }
3525
3526 BIO_free(biobuf);
3527 return retval;
3528}
3529
3530
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003531/*[clinic input]
3532_ssl._SSLContext.load_verify_locations
3533 cafile: object = NULL
3534 capath: object = NULL
3535 cadata: object = NULL
3536
3537[clinic start generated code]*/
3538
Antoine Pitrou152efa22010-05-16 18:19:27 +00003539static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003540_ssl__SSLContext_load_verify_locations_impl(PySSLContext *self,
3541 PyObject *cafile,
3542 PyObject *capath,
3543 PyObject *cadata)
3544/*[clinic end generated code: output=454c7e41230ca551 input=997f1fb3a784ef88]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003545{
Antoine Pitrou152efa22010-05-16 18:19:27 +00003546 PyObject *cafile_bytes = NULL, *capath_bytes = NULL;
3547 const char *cafile_buf = NULL, *capath_buf = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003548 int r = 0, ok = 1;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003549
Giampaolo Rodolà745ab382010-08-29 19:25:49 +00003550 errno = 0;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003551 if (cafile == Py_None)
3552 cafile = NULL;
3553 if (capath == Py_None)
3554 capath = NULL;
Christian Heimesefff7062013-11-21 03:35:02 +01003555 if (cadata == Py_None)
3556 cadata = NULL;
3557
3558 if (cafile == NULL && capath == NULL && cadata == NULL) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003559 PyErr_SetString(PyExc_TypeError,
Christian Heimesefff7062013-11-21 03:35:02 +01003560 "cafile, capath and cadata cannot be all omitted");
3561 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003562 }
3563 if (cafile && !PyUnicode_FSConverter(cafile, &cafile_bytes)) {
3564 PyErr_SetString(PyExc_TypeError,
3565 "cafile should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003566 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003567 }
3568 if (capath && !PyUnicode_FSConverter(capath, &capath_bytes)) {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003569 PyErr_SetString(PyExc_TypeError,
3570 "capath should be a valid filesystem path");
Christian Heimesefff7062013-11-21 03:35:02 +01003571 goto error;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003572 }
Christian Heimesefff7062013-11-21 03:35:02 +01003573
3574 /* validata cadata type and load cadata */
3575 if (cadata) {
3576 Py_buffer buf;
3577 PyObject *cadata_ascii = NULL;
3578
3579 if (PyObject_GetBuffer(cadata, &buf, PyBUF_SIMPLE) == 0) {
3580 if (!PyBuffer_IsContiguous(&buf, 'C') || buf.ndim > 1) {
3581 PyBuffer_Release(&buf);
3582 PyErr_SetString(PyExc_TypeError,
3583 "cadata should be a contiguous buffer with "
3584 "a single dimension");
3585 goto error;
3586 }
3587 r = _add_ca_certs(self, buf.buf, buf.len, SSL_FILETYPE_ASN1);
3588 PyBuffer_Release(&buf);
3589 if (r == -1) {
3590 goto error;
3591 }
3592 } else {
3593 PyErr_Clear();
3594 cadata_ascii = PyUnicode_AsASCIIString(cadata);
3595 if (cadata_ascii == NULL) {
3596 PyErr_SetString(PyExc_TypeError,
Serhiy Storchakad65c9492015-11-02 14:10:23 +02003597 "cadata should be an ASCII string or a "
Christian Heimesefff7062013-11-21 03:35:02 +01003598 "bytes-like object");
3599 goto error;
3600 }
3601 r = _add_ca_certs(self,
3602 PyBytes_AS_STRING(cadata_ascii),
3603 PyBytes_GET_SIZE(cadata_ascii),
3604 SSL_FILETYPE_PEM);
3605 Py_DECREF(cadata_ascii);
3606 if (r == -1) {
3607 goto error;
3608 }
3609 }
3610 }
3611
3612 /* load cafile or capath */
3613 if (cafile || capath) {
3614 if (cafile)
3615 cafile_buf = PyBytes_AS_STRING(cafile_bytes);
3616 if (capath)
3617 capath_buf = PyBytes_AS_STRING(capath_bytes);
3618 PySSL_BEGIN_ALLOW_THREADS
3619 r = SSL_CTX_load_verify_locations(self->ctx, cafile_buf, capath_buf);
3620 PySSL_END_ALLOW_THREADS
3621 if (r != 1) {
3622 ok = 0;
3623 if (errno != 0) {
3624 ERR_clear_error();
Serhiy Storchaka55fe1ae2017-04-16 10:46:38 +03003625 PyErr_SetFromErrno(PyExc_OSError);
Christian Heimesefff7062013-11-21 03:35:02 +01003626 }
3627 else {
3628 _setSSLError(NULL, 0, __FILE__, __LINE__);
3629 }
3630 goto error;
3631 }
3632 }
3633 goto end;
3634
3635 error:
3636 ok = 0;
3637 end:
Antoine Pitrou152efa22010-05-16 18:19:27 +00003638 Py_XDECREF(cafile_bytes);
3639 Py_XDECREF(capath_bytes);
Christian Heimesefff7062013-11-21 03:35:02 +01003640 if (ok) {
3641 Py_RETURN_NONE;
3642 } else {
Antoine Pitrou152efa22010-05-16 18:19:27 +00003643 return NULL;
3644 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003645}
3646
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003647/*[clinic input]
3648_ssl._SSLContext.load_dh_params
3649 path as filepath: object
3650 /
3651
3652[clinic start generated code]*/
3653
Antoine Pitrou152efa22010-05-16 18:19:27 +00003654static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003655_ssl__SSLContext_load_dh_params(PySSLContext *self, PyObject *filepath)
3656/*[clinic end generated code: output=1c8e57a38e055af0 input=c8871f3c796ae1d6]*/
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003657{
3658 FILE *f;
3659 DH *dh;
3660
Victor Stinnerdaf45552013-08-28 00:53:59 +02003661 f = _Py_fopen_obj(filepath, "rb");
Victor Stinnere42ccd22015-03-18 01:39:23 +01003662 if (f == NULL)
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003663 return NULL;
Victor Stinnere42ccd22015-03-18 01:39:23 +01003664
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003665 errno = 0;
3666 PySSL_BEGIN_ALLOW_THREADS
3667 dh = PEM_read_DHparams(f, NULL, NULL, NULL);
Antoine Pitrou457a2292013-01-12 21:43:45 +01003668 fclose(f);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003669 PySSL_END_ALLOW_THREADS
3670 if (dh == NULL) {
3671 if (errno != 0) {
3672 ERR_clear_error();
3673 PyErr_SetFromErrnoWithFilenameObject(PyExc_OSError, filepath);
3674 }
3675 else {
3676 _setSSLError(NULL, 0, __FILE__, __LINE__);
3677 }
3678 return NULL;
3679 }
3680 if (SSL_CTX_set_tmp_dh(self->ctx, dh) == 0)
3681 _setSSLError(NULL, 0, __FILE__, __LINE__);
3682 DH_free(dh);
3683 Py_RETURN_NONE;
3684}
3685
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003686/*[clinic input]
3687_ssl._SSLContext._wrap_socket
3688 sock: object(subclass_of="PySocketModule.Sock_Type")
3689 server_side: int
3690 server_hostname as hostname_obj: object = None
3691
3692[clinic start generated code]*/
3693
Antoine Pitrou0e576f12011-12-22 10:03:38 +01003694static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003695_ssl__SSLContext__wrap_socket_impl(PySSLContext *self, PyObject *sock,
3696 int server_side, PyObject *hostname_obj)
3697/*[clinic end generated code: output=6973e4b60995e933 input=83859b9156ddfc63]*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00003698{
Antoine Pitroud5323212010-10-22 18:19:07 +00003699 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003700 PyObject *res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003701
Antoine Pitroud5323212010-10-22 18:19:07 +00003702 /* server_hostname is either None (or absent), or to be encoded
3703 using the idna encoding. */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003704 if (hostname_obj != Py_None) {
3705 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
Antoine Pitroud5323212010-10-22 18:19:07 +00003706 return NULL;
Antoine Pitroud5323212010-10-22 18:19:07 +00003707 }
Antoine Pitrou152efa22010-05-16 18:19:27 +00003708
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003709 res = (PyObject *) newPySSLSocket(self, (PySocketSockObject *)sock,
3710 server_side, hostname,
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003711 NULL, NULL);
Antoine Pitroud5323212010-10-22 18:19:07 +00003712 if (hostname != NULL)
3713 PyMem_Free(hostname);
3714 return res;
Antoine Pitrou152efa22010-05-16 18:19:27 +00003715}
3716
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003717/*[clinic input]
3718_ssl._SSLContext._wrap_bio
3719 incoming: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3720 outgoing: object(subclass_of="&PySSLMemoryBIO_Type", type="PySSLMemoryBIO *")
3721 server_side: int
3722 server_hostname as hostname_obj: object = None
3723
3724[clinic start generated code]*/
3725
Antoine Pitroub0182c82010-10-12 20:09:02 +00003726static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003727_ssl__SSLContext__wrap_bio_impl(PySSLContext *self, PySSLMemoryBIO *incoming,
3728 PySSLMemoryBIO *outgoing, int server_side,
3729 PyObject *hostname_obj)
3730/*[clinic end generated code: output=4fe4ba75ad95940d input=17725ecdac0bf220]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003731{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003732 char *hostname = NULL;
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003733 PyObject *res;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003734
3735 /* server_hostname is either None (or absent), or to be encoded
3736 using the idna encoding. */
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003737 if (hostname_obj != Py_None) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003738 if (!PyArg_Parse(hostname_obj, "et", "idna", &hostname))
3739 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003740 }
3741
3742 res = (PyObject *) newPySSLSocket(self, NULL, server_side, hostname,
3743 incoming, outgoing);
3744
3745 PyMem_Free(hostname);
3746 return res;
3747}
3748
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003749/*[clinic input]
3750_ssl._SSLContext.session_stats
3751[clinic start generated code]*/
3752
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003753static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003754_ssl__SSLContext_session_stats_impl(PySSLContext *self)
3755/*[clinic end generated code: output=0d96411c42893bfb input=7e0a81fb11102c8b]*/
Antoine Pitroub0182c82010-10-12 20:09:02 +00003756{
3757 int r;
3758 PyObject *value, *stats = PyDict_New();
3759 if (!stats)
3760 return NULL;
3761
3762#define ADD_STATS(SSL_NAME, KEY_NAME) \
3763 value = PyLong_FromLong(SSL_CTX_sess_ ## SSL_NAME (self->ctx)); \
3764 if (value == NULL) \
3765 goto error; \
3766 r = PyDict_SetItemString(stats, KEY_NAME, value); \
3767 Py_DECREF(value); \
3768 if (r < 0) \
3769 goto error;
3770
3771 ADD_STATS(number, "number");
3772 ADD_STATS(connect, "connect");
3773 ADD_STATS(connect_good, "connect_good");
3774 ADD_STATS(connect_renegotiate, "connect_renegotiate");
3775 ADD_STATS(accept, "accept");
3776 ADD_STATS(accept_good, "accept_good");
3777 ADD_STATS(accept_renegotiate, "accept_renegotiate");
3778 ADD_STATS(accept, "accept");
3779 ADD_STATS(hits, "hits");
3780 ADD_STATS(misses, "misses");
3781 ADD_STATS(timeouts, "timeouts");
3782 ADD_STATS(cache_full, "cache_full");
3783
3784#undef ADD_STATS
3785
3786 return stats;
3787
3788error:
3789 Py_DECREF(stats);
3790 return NULL;
3791}
3792
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003793/*[clinic input]
3794_ssl._SSLContext.set_default_verify_paths
3795[clinic start generated code]*/
3796
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003797static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003798_ssl__SSLContext_set_default_verify_paths_impl(PySSLContext *self)
3799/*[clinic end generated code: output=0bee74e6e09deaaa input=35f3408021463d74]*/
Antoine Pitrou664c2d12010-11-17 20:29:42 +00003800{
3801 if (!SSL_CTX_set_default_verify_paths(self->ctx)) {
3802 _setSSLError(NULL, 0, __FILE__, __LINE__);
3803 return NULL;
3804 }
3805 Py_RETURN_NONE;
3806}
3807
Antoine Pitrou501da612011-12-21 09:27:41 +01003808#ifndef OPENSSL_NO_ECDH
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003809/*[clinic input]
3810_ssl._SSLContext.set_ecdh_curve
3811 name: object
3812 /
3813
3814[clinic start generated code]*/
3815
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003816static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003817_ssl__SSLContext_set_ecdh_curve(PySSLContext *self, PyObject *name)
3818/*[clinic end generated code: output=23022c196e40d7d2 input=c2bafb6f6e34726b]*/
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003819{
3820 PyObject *name_bytes;
3821 int nid;
3822 EC_KEY *key;
3823
3824 if (!PyUnicode_FSConverter(name, &name_bytes))
3825 return NULL;
3826 assert(PyBytes_Check(name_bytes));
3827 nid = OBJ_sn2nid(PyBytes_AS_STRING(name_bytes));
3828 Py_DECREF(name_bytes);
3829 if (nid == 0) {
3830 PyErr_Format(PyExc_ValueError,
3831 "unknown elliptic curve name %R", name);
3832 return NULL;
3833 }
3834 key = EC_KEY_new_by_curve_name(nid);
3835 if (key == NULL) {
3836 _setSSLError(NULL, 0, __FILE__, __LINE__);
3837 return NULL;
3838 }
3839 SSL_CTX_set_tmp_ecdh(self->ctx, key);
3840 EC_KEY_free(key);
3841 Py_RETURN_NONE;
3842}
Antoine Pitrou501da612011-12-21 09:27:41 +01003843#endif
Antoine Pitrou923df6f2011-12-19 17:16:51 +01003844
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003845#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003846static int
3847_servername_callback(SSL *s, int *al, void *args)
3848{
3849 int ret;
3850 PySSLContext *ssl_ctx = (PySSLContext *) args;
3851 PySSLSocket *ssl;
3852 PyObject *servername_o;
3853 PyObject *servername_idna;
3854 PyObject *result;
3855 /* The high-level ssl.SSLSocket object */
3856 PyObject *ssl_socket;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003857 const char *servername = SSL_get_servername(s, TLSEXT_NAMETYPE_host_name);
Stefan Krah20d60802013-01-17 17:07:17 +01003858 PyGILState_STATE gstate = PyGILState_Ensure();
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003859
3860 if (ssl_ctx->set_hostname == NULL) {
3861 /* remove race condition in this the call back while if removing the
3862 * callback is in progress */
3863 PyGILState_Release(gstate);
Antoine Pitrou5dd12a52013-01-06 15:25:36 +01003864 return SSL_TLSEXT_ERR_OK;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003865 }
3866
3867 ssl = SSL_get_app_data(s);
3868 assert(PySSLSocket_Check(ssl));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003869
Serhiy Storchakaf51d7152015-11-02 14:40:41 +02003870 /* The servername callback expects an argument that represents the current
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003871 * SSL connection and that has a .context attribute that can be changed to
3872 * identify the requested hostname. Since the official API is the Python
3873 * level API we want to pass the callback a Python level object rather than
3874 * a _ssl.SSLSocket instance. If there's an "owner" (typically an
3875 * SSLObject) that will be passed. Otherwise if there's a socket then that
3876 * will be passed. If both do not exist only then the C-level object is
3877 * passed. */
3878 if (ssl->owner)
3879 ssl_socket = PyWeakref_GetObject(ssl->owner);
3880 else if (ssl->Socket)
3881 ssl_socket = PyWeakref_GetObject(ssl->Socket);
3882 else
3883 ssl_socket = (PyObject *) ssl;
3884
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003885 Py_INCREF(ssl_socket);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02003886 if (ssl_socket == Py_None)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003887 goto error;
Victor Stinner7e001512013-06-25 00:44:31 +02003888
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003889 if (servername == NULL) {
3890 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3891 Py_None, ssl_ctx, NULL);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003892 }
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003893 else {
3894 servername_o = PyBytes_FromString(servername);
3895 if (servername_o == NULL) {
3896 PyErr_WriteUnraisable((PyObject *) ssl_ctx);
3897 goto error;
3898 }
3899 servername_idna = PyUnicode_FromEncodedObject(servername_o, "idna", NULL);
3900 if (servername_idna == NULL) {
3901 PyErr_WriteUnraisable(servername_o);
3902 Py_DECREF(servername_o);
3903 goto error;
3904 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003905 Py_DECREF(servername_o);
Antoine Pitrou50b24d02013-04-11 20:48:42 +02003906 result = PyObject_CallFunctionObjArgs(ssl_ctx->set_hostname, ssl_socket,
3907 servername_idna, ssl_ctx, NULL);
3908 Py_DECREF(servername_idna);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003909 }
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003910 Py_DECREF(ssl_socket);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003911
3912 if (result == NULL) {
3913 PyErr_WriteUnraisable(ssl_ctx->set_hostname);
3914 *al = SSL_AD_HANDSHAKE_FAILURE;
3915 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3916 }
3917 else {
3918 if (result != Py_None) {
3919 *al = (int) PyLong_AsLong(result);
3920 if (PyErr_Occurred()) {
3921 PyErr_WriteUnraisable(result);
3922 *al = SSL_AD_INTERNAL_ERROR;
3923 }
3924 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3925 }
3926 else {
3927 ret = SSL_TLSEXT_ERR_OK;
3928 }
3929 Py_DECREF(result);
3930 }
3931
3932 PyGILState_Release(gstate);
3933 return ret;
3934
3935error:
3936 Py_DECREF(ssl_socket);
3937 *al = SSL_AD_INTERNAL_ERROR;
3938 ret = SSL_TLSEXT_ERR_ALERT_FATAL;
3939 PyGILState_Release(gstate);
3940 return ret;
3941}
Antoine Pitroua5963382013-03-30 16:39:00 +01003942#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003943
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003944/*[clinic input]
3945_ssl._SSLContext.set_servername_callback
3946 method as cb: object
3947 /
3948
3949Set a callback that will be called when a server name is provided by the SSL/TLS client in the SNI extension.
3950
3951If the argument is None then the callback is disabled. The method is called
3952with the SSLSocket, the server name as a string, and the SSLContext object.
3953See RFC 6066 for details of the SNI extension.
3954[clinic start generated code]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003955
3956static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003957_ssl__SSLContext_set_servername_callback(PySSLContext *self, PyObject *cb)
3958/*[clinic end generated code: output=3439a1b2d5d3b7ea input=a2a83620197d602b]*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003959{
Antoine Pitrou912fbff2013-03-30 16:29:32 +01003960#if HAVE_SNI && !defined(OPENSSL_NO_TLSEXT)
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003961 Py_CLEAR(self->set_hostname);
3962 if (cb == Py_None) {
3963 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3964 }
3965 else {
3966 if (!PyCallable_Check(cb)) {
3967 SSL_CTX_set_tlsext_servername_callback(self->ctx, NULL);
3968 PyErr_SetString(PyExc_TypeError,
3969 "not a callable object");
3970 return NULL;
3971 }
3972 Py_INCREF(cb);
3973 self->set_hostname = cb;
3974 SSL_CTX_set_tlsext_servername_callback(self->ctx, _servername_callback);
3975 SSL_CTX_set_tlsext_servername_arg(self->ctx, self);
3976 }
3977 Py_RETURN_NONE;
3978#else
3979 PyErr_SetString(PyExc_NotImplementedError,
3980 "The TLS extension servername callback, "
3981 "SSL_CTX_set_tlsext_servername_callback, "
3982 "is not in the current OpenSSL library.");
Antoine Pitrou41f8c4f2013-03-30 16:36:54 +01003983 return NULL;
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01003984#endif
3985}
3986
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03003987/*[clinic input]
3988_ssl._SSLContext.cert_store_stats
3989
3990Returns quantities of loaded X.509 certificates.
3991
3992X.509 certificates with a CA extension and certificate revocation lists
3993inside the context's cert store.
3994
3995NOTE: Certificates in a capath directory aren't loaded unless they have
3996been used at least once.
3997[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02003998
3999static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004000_ssl__SSLContext_cert_store_stats_impl(PySSLContext *self)
4001/*[clinic end generated code: output=5f356f4d9cca874d input=eb40dd0f6d0e40cf]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004002{
4003 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004004 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004005 X509_OBJECT *obj;
Christian Heimes598894f2016-09-05 23:19:05 +02004006 int x509 = 0, crl = 0, ca = 0, i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004007
4008 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004009 objs = X509_STORE_get0_objects(store);
4010 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
4011 obj = sk_X509_OBJECT_value(objs, i);
4012 switch (X509_OBJECT_get_type(obj)) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004013 case X509_LU_X509:
4014 x509++;
Christian Heimes598894f2016-09-05 23:19:05 +02004015 if (X509_check_ca(X509_OBJECT_get0_X509(obj))) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004016 ca++;
4017 }
4018 break;
4019 case X509_LU_CRL:
4020 crl++;
4021 break;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004022 default:
4023 /* Ignore X509_LU_FAIL, X509_LU_RETRY, X509_LU_PKEY.
4024 * As far as I can tell they are internal states and never
4025 * stored in a cert store */
4026 break;
4027 }
4028 }
4029 return Py_BuildValue("{sisisi}", "x509", x509, "crl", crl,
4030 "x509_ca", ca);
4031}
4032
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004033/*[clinic input]
4034_ssl._SSLContext.get_ca_certs
4035 binary_form: bool = False
4036
4037Returns a list of dicts with information of loaded CA certs.
4038
4039If the optional argument is True, returns a DER-encoded copy of the CA
4040certificate.
4041
4042NOTE: Certificates in a capath directory aren't loaded unless they have
4043been used at least once.
4044[clinic start generated code]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004045
4046static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004047_ssl__SSLContext_get_ca_certs_impl(PySSLContext *self, int binary_form)
4048/*[clinic end generated code: output=0d58f148f37e2938 input=6887b5a09b7f9076]*/
Christian Heimes9a5395a2013-06-17 15:44:12 +02004049{
4050 X509_STORE *store;
Christian Heimes598894f2016-09-05 23:19:05 +02004051 STACK_OF(X509_OBJECT) *objs;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004052 PyObject *ci = NULL, *rlist = NULL;
4053 int i;
Christian Heimes9a5395a2013-06-17 15:44:12 +02004054
4055 if ((rlist = PyList_New(0)) == NULL) {
4056 return NULL;
4057 }
4058
4059 store = SSL_CTX_get_cert_store(self->ctx);
Christian Heimes598894f2016-09-05 23:19:05 +02004060 objs = X509_STORE_get0_objects(store);
4061 for (i = 0; i < sk_X509_OBJECT_num(objs); i++) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004062 X509_OBJECT *obj;
4063 X509 *cert;
4064
Christian Heimes598894f2016-09-05 23:19:05 +02004065 obj = sk_X509_OBJECT_value(objs, i);
4066 if (X509_OBJECT_get_type(obj) != X509_LU_X509) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004067 /* not a x509 cert */
4068 continue;
4069 }
4070 /* CA for any purpose */
Christian Heimes598894f2016-09-05 23:19:05 +02004071 cert = X509_OBJECT_get0_X509(obj);
Christian Heimes9a5395a2013-06-17 15:44:12 +02004072 if (!X509_check_ca(cert)) {
4073 continue;
4074 }
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004075 if (binary_form) {
Christian Heimes9a5395a2013-06-17 15:44:12 +02004076 ci = _certificate_to_der(cert);
4077 } else {
4078 ci = _decode_certificate(cert);
4079 }
4080 if (ci == NULL) {
4081 goto error;
4082 }
4083 if (PyList_Append(rlist, ci) == -1) {
4084 goto error;
4085 }
4086 Py_CLEAR(ci);
4087 }
4088 return rlist;
4089
4090 error:
4091 Py_XDECREF(ci);
4092 Py_XDECREF(rlist);
4093 return NULL;
4094}
4095
4096
Antoine Pitrou152efa22010-05-16 18:19:27 +00004097static PyGetSetDef context_getsetlist[] = {
Christian Heimes1aa9a752013-12-02 02:41:19 +01004098 {"check_hostname", (getter) get_check_hostname,
4099 (setter) set_check_hostname, NULL},
Antoine Pitroub5218772010-05-21 09:56:06 +00004100 {"options", (getter) get_options,
4101 (setter) set_options, NULL},
Christian Heimes22587792013-11-21 23:56:13 +01004102 {"verify_flags", (getter) get_verify_flags,
4103 (setter) set_verify_flags, NULL},
Antoine Pitrou152efa22010-05-16 18:19:27 +00004104 {"verify_mode", (getter) get_verify_mode,
4105 (setter) set_verify_mode, NULL},
4106 {NULL}, /* sentinel */
4107};
4108
4109static struct PyMethodDef context_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004110 _SSL__SSLCONTEXT__WRAP_SOCKET_METHODDEF
4111 _SSL__SSLCONTEXT__WRAP_BIO_METHODDEF
4112 _SSL__SSLCONTEXT_SET_CIPHERS_METHODDEF
4113 _SSL__SSLCONTEXT__SET_ALPN_PROTOCOLS_METHODDEF
4114 _SSL__SSLCONTEXT__SET_NPN_PROTOCOLS_METHODDEF
4115 _SSL__SSLCONTEXT_LOAD_CERT_CHAIN_METHODDEF
4116 _SSL__SSLCONTEXT_LOAD_DH_PARAMS_METHODDEF
4117 _SSL__SSLCONTEXT_LOAD_VERIFY_LOCATIONS_METHODDEF
4118 _SSL__SSLCONTEXT_SESSION_STATS_METHODDEF
4119 _SSL__SSLCONTEXT_SET_DEFAULT_VERIFY_PATHS_METHODDEF
4120 _SSL__SSLCONTEXT_SET_ECDH_CURVE_METHODDEF
4121 _SSL__SSLCONTEXT_SET_SERVERNAME_CALLBACK_METHODDEF
4122 _SSL__SSLCONTEXT_CERT_STORE_STATS_METHODDEF
4123 _SSL__SSLCONTEXT_GET_CA_CERTS_METHODDEF
Christian Heimes25bfcd52016-09-06 00:04:45 +02004124 _SSL__SSLCONTEXT_GET_CIPHERS_METHODDEF
Antoine Pitrou152efa22010-05-16 18:19:27 +00004125 {NULL, NULL} /* sentinel */
4126};
4127
4128static PyTypeObject PySSLContext_Type = {
4129 PyVarObject_HEAD_INIT(NULL, 0)
4130 "_ssl._SSLContext", /*tp_name*/
4131 sizeof(PySSLContext), /*tp_basicsize*/
4132 0, /*tp_itemsize*/
4133 (destructor)context_dealloc, /*tp_dealloc*/
4134 0, /*tp_print*/
4135 0, /*tp_getattr*/
4136 0, /*tp_setattr*/
4137 0, /*tp_reserved*/
4138 0, /*tp_repr*/
4139 0, /*tp_as_number*/
4140 0, /*tp_as_sequence*/
4141 0, /*tp_as_mapping*/
4142 0, /*tp_hash*/
4143 0, /*tp_call*/
4144 0, /*tp_str*/
4145 0, /*tp_getattro*/
4146 0, /*tp_setattro*/
4147 0, /*tp_as_buffer*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004148 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004149 0, /*tp_doc*/
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01004150 (traverseproc) context_traverse, /*tp_traverse*/
4151 (inquiry) context_clear, /*tp_clear*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004152 0, /*tp_richcompare*/
4153 0, /*tp_weaklistoffset*/
4154 0, /*tp_iter*/
4155 0, /*tp_iternext*/
4156 context_methods, /*tp_methods*/
4157 0, /*tp_members*/
4158 context_getsetlist, /*tp_getset*/
4159 0, /*tp_base*/
4160 0, /*tp_dict*/
4161 0, /*tp_descr_get*/
4162 0, /*tp_descr_set*/
4163 0, /*tp_dictoffset*/
4164 0, /*tp_init*/
4165 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004166 _ssl__SSLContext, /*tp_new*/
Antoine Pitrou152efa22010-05-16 18:19:27 +00004167};
4168
4169
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004170/*
4171 * MemoryBIO objects
4172 */
4173
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004174/*[clinic input]
4175@classmethod
4176_ssl.MemoryBIO.__new__
4177
4178[clinic start generated code]*/
4179
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004180static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004181_ssl_MemoryBIO_impl(PyTypeObject *type)
4182/*[clinic end generated code: output=8820a58db78330ac input=26d22e4909ecb1b5]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004183{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004184 BIO *bio;
4185 PySSLMemoryBIO *self;
4186
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004187 bio = BIO_new(BIO_s_mem());
4188 if (bio == NULL) {
4189 PyErr_SetString(PySSLErrorObject,
4190 "failed to allocate BIO");
4191 return NULL;
4192 }
4193 /* Since our BIO is non-blocking an empty read() does not indicate EOF,
4194 * just that no data is currently available. The SSL routines should retry
4195 * the read, which we can achieve by calling BIO_set_retry_read(). */
4196 BIO_set_retry_read(bio);
4197 BIO_set_mem_eof_return(bio, -1);
4198
4199 assert(type != NULL && type->tp_alloc != NULL);
4200 self = (PySSLMemoryBIO *) type->tp_alloc(type, 0);
4201 if (self == NULL) {
4202 BIO_free(bio);
4203 return NULL;
4204 }
4205 self->bio = bio;
4206 self->eof_written = 0;
4207
4208 return (PyObject *) self;
4209}
4210
4211static void
4212memory_bio_dealloc(PySSLMemoryBIO *self)
4213{
4214 BIO_free(self->bio);
4215 Py_TYPE(self)->tp_free(self);
4216}
4217
4218static PyObject *
4219memory_bio_get_pending(PySSLMemoryBIO *self, void *c)
4220{
Segev Finer5cff6372017-07-27 01:19:17 +03004221 return PyLong_FromSize_t(BIO_ctrl_pending(self->bio));
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004222}
4223
4224PyDoc_STRVAR(PySSL_memory_bio_pending_doc,
4225"The number of bytes pending in the memory BIO.");
4226
4227static PyObject *
4228memory_bio_get_eof(PySSLMemoryBIO *self, void *c)
4229{
4230 return PyBool_FromLong((BIO_ctrl_pending(self->bio) == 0)
4231 && self->eof_written);
4232}
4233
4234PyDoc_STRVAR(PySSL_memory_bio_eof_doc,
4235"Whether the memory BIO is at EOF.");
4236
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004237/*[clinic input]
4238_ssl.MemoryBIO.read
4239 size as len: int = -1
4240 /
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004241
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004242Read up to size bytes from the memory BIO.
4243
4244If size is not specified, read the entire buffer.
4245If the return value is an empty bytes instance, this means either
4246EOF or that no data is available. Use the "eof" property to
4247distinguish between the two.
4248[clinic start generated code]*/
4249
4250static PyObject *
4251_ssl_MemoryBIO_read_impl(PySSLMemoryBIO *self, int len)
4252/*[clinic end generated code: output=a657aa1e79cd01b3 input=574d7be06a902366]*/
4253{
4254 int avail, nbytes;
4255 PyObject *result;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004256
Segev Finer5cff6372017-07-27 01:19:17 +03004257 avail = (int)Py_MIN(BIO_ctrl_pending(self->bio), INT_MAX);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004258 if ((len < 0) || (len > avail))
4259 len = avail;
4260
4261 result = PyBytes_FromStringAndSize(NULL, len);
4262 if ((result == NULL) || (len == 0))
4263 return result;
4264
4265 nbytes = BIO_read(self->bio, PyBytes_AS_STRING(result), len);
4266 /* There should never be any short reads but check anyway. */
4267 if ((nbytes < len) && (_PyBytes_Resize(&result, len) < 0)) {
4268 Py_DECREF(result);
4269 return NULL;
4270 }
4271
4272 return result;
4273}
4274
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004275/*[clinic input]
4276_ssl.MemoryBIO.write
4277 b: Py_buffer
4278 /
4279
4280Writes the bytes b into the memory BIO.
4281
4282Returns the number of bytes written.
4283[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004284
4285static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004286_ssl_MemoryBIO_write_impl(PySSLMemoryBIO *self, Py_buffer *b)
4287/*[clinic end generated code: output=156ec59110d75935 input=e45757b3e17c4808]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004288{
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004289 int nbytes;
4290
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004291 if (b->len > INT_MAX) {
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004292 PyErr_Format(PyExc_OverflowError,
4293 "string longer than %d bytes", INT_MAX);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004294 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004295 }
4296
4297 if (self->eof_written) {
4298 PyErr_SetString(PySSLErrorObject,
4299 "cannot write() after write_eof()");
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004300 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004301 }
4302
Segev Finer5cff6372017-07-27 01:19:17 +03004303 nbytes = BIO_write(self->bio, b->buf, (int)b->len);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004304 if (nbytes < 0) {
4305 _setSSLError(NULL, 0, __FILE__, __LINE__);
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004306 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004307 }
4308
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004309 return PyLong_FromLong(nbytes);
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004310}
4311
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004312/*[clinic input]
4313_ssl.MemoryBIO.write_eof
4314
4315Write an EOF marker to the memory BIO.
4316
4317When all data has been read, the "eof" property will be True.
4318[clinic start generated code]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004319
4320static PyObject *
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004321_ssl_MemoryBIO_write_eof_impl(PySSLMemoryBIO *self)
4322/*[clinic end generated code: output=d4106276ccd1ed34 input=56a945f1d29e8bd6]*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004323{
4324 self->eof_written = 1;
4325 /* After an EOF is written, a zero return from read() should be a real EOF
4326 * i.e. it should not be retried. Clear the SHOULD_RETRY flag. */
4327 BIO_clear_retry_flags(self->bio);
4328 BIO_set_mem_eof_return(self->bio, 0);
4329
4330 Py_RETURN_NONE;
4331}
4332
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004333static PyGetSetDef memory_bio_getsetlist[] = {
4334 {"pending", (getter) memory_bio_get_pending, NULL,
4335 PySSL_memory_bio_pending_doc},
4336 {"eof", (getter) memory_bio_get_eof, NULL,
4337 PySSL_memory_bio_eof_doc},
4338 {NULL}, /* sentinel */
4339};
4340
4341static struct PyMethodDef memory_bio_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004342 _SSL_MEMORYBIO_READ_METHODDEF
4343 _SSL_MEMORYBIO_WRITE_METHODDEF
4344 _SSL_MEMORYBIO_WRITE_EOF_METHODDEF
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004345 {NULL, NULL} /* sentinel */
4346};
4347
4348static PyTypeObject PySSLMemoryBIO_Type = {
4349 PyVarObject_HEAD_INIT(NULL, 0)
4350 "_ssl.MemoryBIO", /*tp_name*/
4351 sizeof(PySSLMemoryBIO), /*tp_basicsize*/
4352 0, /*tp_itemsize*/
4353 (destructor)memory_bio_dealloc, /*tp_dealloc*/
4354 0, /*tp_print*/
4355 0, /*tp_getattr*/
4356 0, /*tp_setattr*/
4357 0, /*tp_reserved*/
4358 0, /*tp_repr*/
4359 0, /*tp_as_number*/
4360 0, /*tp_as_sequence*/
4361 0, /*tp_as_mapping*/
4362 0, /*tp_hash*/
4363 0, /*tp_call*/
4364 0, /*tp_str*/
4365 0, /*tp_getattro*/
4366 0, /*tp_setattro*/
4367 0, /*tp_as_buffer*/
4368 Py_TPFLAGS_DEFAULT, /*tp_flags*/
4369 0, /*tp_doc*/
4370 0, /*tp_traverse*/
4371 0, /*tp_clear*/
4372 0, /*tp_richcompare*/
4373 0, /*tp_weaklistoffset*/
4374 0, /*tp_iter*/
4375 0, /*tp_iternext*/
4376 memory_bio_methods, /*tp_methods*/
4377 0, /*tp_members*/
4378 memory_bio_getsetlist, /*tp_getset*/
4379 0, /*tp_base*/
4380 0, /*tp_dict*/
4381 0, /*tp_descr_get*/
4382 0, /*tp_descr_set*/
4383 0, /*tp_dictoffset*/
4384 0, /*tp_init*/
4385 0, /*tp_alloc*/
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004386 _ssl_MemoryBIO, /*tp_new*/
Antoine Pitroub1fdf472014-10-05 20:41:53 +02004387};
4388
Antoine Pitrou152efa22010-05-16 18:19:27 +00004389
Christian Heimes99a65702016-09-10 23:44:53 +02004390/*
4391 * SSL Session object
4392 */
4393
4394static void
4395PySSLSession_dealloc(PySSLSession *self)
4396{
INADA Naokia6296d32017-08-24 14:55:17 +09004397 /* bpo-31095: UnTrack is needed before calling any callbacks */
Christian Heimesa5d07652016-09-24 10:48:05 +02004398 PyObject_GC_UnTrack(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004399 Py_XDECREF(self->ctx);
4400 if (self->session != NULL) {
4401 SSL_SESSION_free(self->session);
4402 }
Christian Heimesa5d07652016-09-24 10:48:05 +02004403 PyObject_GC_Del(self);
Christian Heimes99a65702016-09-10 23:44:53 +02004404}
4405
4406static PyObject *
4407PySSLSession_richcompare(PyObject *left, PyObject *right, int op)
4408{
4409 int result;
4410
4411 if (left == NULL || right == NULL) {
4412 PyErr_BadInternalCall();
4413 return NULL;
4414 }
4415
4416 if (!PySSLSession_Check(left) || !PySSLSession_Check(right)) {
4417 Py_RETURN_NOTIMPLEMENTED;
4418 }
4419
4420 if (left == right) {
4421 result = 0;
4422 } else {
4423 const unsigned char *left_id, *right_id;
4424 unsigned int left_len, right_len;
4425 left_id = SSL_SESSION_get_id(((PySSLSession *)left)->session,
4426 &left_len);
4427 right_id = SSL_SESSION_get_id(((PySSLSession *)right)->session,
4428 &right_len);
4429 if (left_len == right_len) {
4430 result = memcmp(left_id, right_id, left_len);
4431 } else {
4432 result = 1;
4433 }
4434 }
4435
4436 switch (op) {
4437 case Py_EQ:
4438 if (result == 0) {
4439 Py_RETURN_TRUE;
4440 } else {
4441 Py_RETURN_FALSE;
4442 }
4443 break;
4444 case Py_NE:
4445 if (result != 0) {
4446 Py_RETURN_TRUE;
4447 } else {
4448 Py_RETURN_FALSE;
4449 }
4450 break;
4451 case Py_LT:
4452 case Py_LE:
4453 case Py_GT:
4454 case Py_GE:
4455 Py_RETURN_NOTIMPLEMENTED;
4456 break;
4457 default:
4458 PyErr_BadArgument();
4459 return NULL;
4460 }
4461}
4462
4463static int
4464PySSLSession_traverse(PySSLSession *self, visitproc visit, void *arg)
4465{
4466 Py_VISIT(self->ctx);
4467 return 0;
4468}
4469
4470static int
4471PySSLSession_clear(PySSLSession *self)
4472{
4473 Py_CLEAR(self->ctx);
4474 return 0;
4475}
4476
4477
4478static PyObject *
4479PySSLSession_get_time(PySSLSession *self, void *closure) {
4480 return PyLong_FromLong(SSL_SESSION_get_time(self->session));
4481}
4482
4483PyDoc_STRVAR(PySSLSession_get_time_doc,
4484"Session creation time (seconds since epoch).");
4485
4486
4487static PyObject *
4488PySSLSession_get_timeout(PySSLSession *self, void *closure) {
4489 return PyLong_FromLong(SSL_SESSION_get_timeout(self->session));
4490}
4491
4492PyDoc_STRVAR(PySSLSession_get_timeout_doc,
4493"Session timeout (delta in seconds).");
4494
4495
4496static PyObject *
4497PySSLSession_get_ticket_lifetime_hint(PySSLSession *self, void *closure) {
4498 unsigned long hint = SSL_SESSION_get_ticket_lifetime_hint(self->session);
4499 return PyLong_FromUnsignedLong(hint);
4500}
4501
4502PyDoc_STRVAR(PySSLSession_get_ticket_lifetime_hint_doc,
4503"Ticket life time hint.");
4504
4505
4506static PyObject *
4507PySSLSession_get_session_id(PySSLSession *self, void *closure) {
4508 const unsigned char *id;
4509 unsigned int len;
4510 id = SSL_SESSION_get_id(self->session, &len);
4511 return PyBytes_FromStringAndSize((const char *)id, len);
4512}
4513
4514PyDoc_STRVAR(PySSLSession_get_session_id_doc,
4515"Session id");
4516
4517
4518static PyObject *
4519PySSLSession_get_has_ticket(PySSLSession *self, void *closure) {
4520 if (SSL_SESSION_has_ticket(self->session)) {
4521 Py_RETURN_TRUE;
4522 } else {
4523 Py_RETURN_FALSE;
4524 }
4525}
4526
4527PyDoc_STRVAR(PySSLSession_get_has_ticket_doc,
4528"Does the session contain a ticket?");
4529
4530
4531static PyGetSetDef PySSLSession_getsetlist[] = {
4532 {"has_ticket", (getter) PySSLSession_get_has_ticket, NULL,
4533 PySSLSession_get_has_ticket_doc},
4534 {"id", (getter) PySSLSession_get_session_id, NULL,
4535 PySSLSession_get_session_id_doc},
4536 {"ticket_lifetime_hint", (getter) PySSLSession_get_ticket_lifetime_hint,
4537 NULL, PySSLSession_get_ticket_lifetime_hint_doc},
4538 {"time", (getter) PySSLSession_get_time, NULL,
4539 PySSLSession_get_time_doc},
4540 {"timeout", (getter) PySSLSession_get_timeout, NULL,
4541 PySSLSession_get_timeout_doc},
4542 {NULL}, /* sentinel */
4543};
4544
4545static PyTypeObject PySSLSession_Type = {
4546 PyVarObject_HEAD_INIT(NULL, 0)
4547 "_ssl.Session", /*tp_name*/
4548 sizeof(PySSLSession), /*tp_basicsize*/
4549 0, /*tp_itemsize*/
4550 (destructor)PySSLSession_dealloc, /*tp_dealloc*/
4551 0, /*tp_print*/
4552 0, /*tp_getattr*/
4553 0, /*tp_setattr*/
4554 0, /*tp_reserved*/
4555 0, /*tp_repr*/
4556 0, /*tp_as_number*/
4557 0, /*tp_as_sequence*/
4558 0, /*tp_as_mapping*/
4559 0, /*tp_hash*/
4560 0, /*tp_call*/
4561 0, /*tp_str*/
4562 0, /*tp_getattro*/
4563 0, /*tp_setattro*/
4564 0, /*tp_as_buffer*/
Christian Heimesa5d07652016-09-24 10:48:05 +02004565 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /*tp_flags*/
Christian Heimes99a65702016-09-10 23:44:53 +02004566 0, /*tp_doc*/
4567 (traverseproc)PySSLSession_traverse, /*tp_traverse*/
4568 (inquiry)PySSLSession_clear, /*tp_clear*/
4569 PySSLSession_richcompare, /*tp_richcompare*/
4570 0, /*tp_weaklistoffset*/
4571 0, /*tp_iter*/
4572 0, /*tp_iternext*/
4573 0, /*tp_methods*/
4574 0, /*tp_members*/
4575 PySSLSession_getsetlist, /*tp_getset*/
4576};
4577
4578
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004579/* helper routines for seeding the SSL PRNG */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004580/*[clinic input]
4581_ssl.RAND_add
Larry Hastingsdbfdc382015-05-04 06:59:46 -07004582 string as view: Py_buffer(accept={str, buffer})
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004583 entropy: double
4584 /
4585
4586Mix string into the OpenSSL PRNG state.
4587
4588entropy (a float) is a lower bound on the entropy contained in
Chandan Kumar63c2c8a2017-06-09 15:13:58 +05304589string. See RFC 4086.
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004590[clinic start generated code]*/
4591
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004592static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004593_ssl_RAND_add_impl(PyObject *module, Py_buffer *view, double entropy)
Serhiy Storchaka5f31d5c2017-06-10 13:13:51 +03004594/*[clinic end generated code: output=e6dd48df9c9024e9 input=5c33017422828f5c]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004595{
Serhiy Storchaka8490f5a2015-03-20 09:00:36 +02004596 const char *buf;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004597 Py_ssize_t len, written;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004598
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004599 buf = (const char *)view->buf;
4600 len = view->len;
Victor Stinner2e57b4e2014-07-01 16:37:17 +02004601 do {
4602 written = Py_MIN(len, INT_MAX);
4603 RAND_add(buf, (int)written, entropy);
4604 buf += written;
4605 len -= written;
4606 } while (len);
Serhiy Storchaka228b12e2017-01-23 09:47:21 +02004607 Py_RETURN_NONE;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004608}
4609
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004610static PyObject *
Victor Stinner99c8b162011-05-24 12:05:19 +02004611PySSL_RAND(int len, int pseudo)
4612{
4613 int ok;
4614 PyObject *bytes;
4615 unsigned long err;
4616 const char *errstr;
4617 PyObject *v;
4618
Victor Stinner1e81a392013-12-19 16:47:04 +01004619 if (len < 0) {
4620 PyErr_SetString(PyExc_ValueError, "num must be positive");
4621 return NULL;
4622 }
4623
Victor Stinner99c8b162011-05-24 12:05:19 +02004624 bytes = PyBytes_FromStringAndSize(NULL, len);
4625 if (bytes == NULL)
4626 return NULL;
4627 if (pseudo) {
4628 ok = RAND_pseudo_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4629 if (ok == 0 || ok == 1)
4630 return Py_BuildValue("NO", bytes, ok == 1 ? Py_True : Py_False);
4631 }
4632 else {
4633 ok = RAND_bytes((unsigned char*)PyBytes_AS_STRING(bytes), len);
4634 if (ok == 1)
4635 return bytes;
4636 }
4637 Py_DECREF(bytes);
4638
4639 err = ERR_get_error();
4640 errstr = ERR_reason_error_string(err);
4641 v = Py_BuildValue("(ks)", err, errstr);
4642 if (v != NULL) {
4643 PyErr_SetObject(PySSLErrorObject, v);
4644 Py_DECREF(v);
4645 }
4646 return NULL;
4647}
4648
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004649/*[clinic input]
4650_ssl.RAND_bytes
4651 n: int
4652 /
4653
4654Generate n cryptographically strong pseudo-random bytes.
4655[clinic start generated code]*/
4656
Victor Stinner99c8b162011-05-24 12:05:19 +02004657static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004658_ssl_RAND_bytes_impl(PyObject *module, int n)
4659/*[clinic end generated code: output=977da635e4838bc7 input=678ddf2872dfebfc]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004660{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004661 return PySSL_RAND(n, 0);
Victor Stinner99c8b162011-05-24 12:05:19 +02004662}
4663
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004664/*[clinic input]
4665_ssl.RAND_pseudo_bytes
4666 n: int
4667 /
4668
4669Generate n pseudo-random bytes.
4670
4671Return a pair (bytes, is_cryptographic). is_cryptographic is True
4672if the bytes generated are cryptographically strong.
4673[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004674
4675static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004676_ssl_RAND_pseudo_bytes_impl(PyObject *module, int n)
4677/*[clinic end generated code: output=b1509e937000e52d input=58312bd53f9bbdd0]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004678{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004679 return PySSL_RAND(n, 1);
Victor Stinner99c8b162011-05-24 12:05:19 +02004680}
4681
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004682/*[clinic input]
4683_ssl.RAND_status
4684
4685Returns 1 if the OpenSSL PRNG has been seeded with enough data and 0 if not.
4686
4687It is necessary to seed the PRNG with RAND_add() on some platforms before
4688using the ssl() function.
4689[clinic start generated code]*/
Victor Stinner99c8b162011-05-24 12:05:19 +02004690
4691static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004692_ssl_RAND_status_impl(PyObject *module)
4693/*[clinic end generated code: output=7e0aaa2d39fdc1ad input=8a774b02d1dc81f3]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004694{
Christian Heimes217cfd12007-12-02 14:31:20 +00004695 return PyLong_FromLong(RAND_status());
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004696}
4697
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004698#ifndef OPENSSL_NO_EGD
Christian Heimesa5d07652016-09-24 10:48:05 +02004699/* LCOV_EXCL_START */
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004700/*[clinic input]
4701_ssl.RAND_egd
4702 path: object(converter="PyUnicode_FSConverter")
4703 /
4704
4705Queries the entropy gather daemon (EGD) on the socket named by 'path'.
4706
4707Returns number of bytes read. Raises SSLError if connection to EGD
4708fails or if it does not provide enough data to seed PRNG.
4709[clinic start generated code]*/
4710
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004711static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004712_ssl_RAND_egd_impl(PyObject *module, PyObject *path)
4713/*[clinic end generated code: output=02a67c7c367f52fa input=1aeb7eb948312195]*/
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004714{
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004715 int bytes = RAND_egd(PyBytes_AsString(path));
Victor Stinnerf9faaad2010-05-16 21:36:37 +00004716 Py_DECREF(path);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004717 if (bytes == -1) {
Antoine Pitrou525807b2010-05-12 14:05:24 +00004718 PyErr_SetString(PySSLErrorObject,
4719 "EGD connection failed or EGD did not return "
4720 "enough data to seed the PRNG");
4721 return NULL;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004722 }
Christian Heimes217cfd12007-12-02 14:31:20 +00004723 return PyLong_FromLong(bytes);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004724}
Christian Heimesa5d07652016-09-24 10:48:05 +02004725/* LCOV_EXCL_STOP */
Benjamin Petersonb8a2f512016-07-06 23:55:15 -07004726#endif /* OPENSSL_NO_EGD */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004727
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00004728
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004729
4730/*[clinic input]
4731_ssl.get_default_verify_paths
4732
4733Return search paths and environment vars that are used by SSLContext's set_default_verify_paths() to load default CAs.
4734
4735The values are 'cert_file_env', 'cert_file', 'cert_dir_env', 'cert_dir'.
4736[clinic start generated code]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004737
4738static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004739_ssl_get_default_verify_paths_impl(PyObject *module)
4740/*[clinic end generated code: output=e5b62a466271928b input=5210c953d98c3eb5]*/
Christian Heimes6d7ad132013-06-09 18:02:55 +02004741{
4742 PyObject *ofile_env = NULL;
4743 PyObject *ofile = NULL;
4744 PyObject *odir_env = NULL;
4745 PyObject *odir = NULL;
4746
Benjamin Petersond113c962015-07-18 10:59:13 -07004747#define CONVERT(info, target) { \
Christian Heimes6d7ad132013-06-09 18:02:55 +02004748 const char *tmp = (info); \
4749 target = NULL; \
4750 if (!tmp) { Py_INCREF(Py_None); target = Py_None; } \
4751 else if ((target = PyUnicode_DecodeFSDefault(tmp)) == NULL) { \
4752 target = PyBytes_FromString(tmp); } \
4753 if (!target) goto error; \
Benjamin Peterson025a1fd2015-11-14 15:12:38 -08004754 }
Christian Heimes6d7ad132013-06-09 18:02:55 +02004755
Benjamin Petersond113c962015-07-18 10:59:13 -07004756 CONVERT(X509_get_default_cert_file_env(), ofile_env);
4757 CONVERT(X509_get_default_cert_file(), ofile);
4758 CONVERT(X509_get_default_cert_dir_env(), odir_env);
4759 CONVERT(X509_get_default_cert_dir(), odir);
4760#undef CONVERT
Christian Heimes6d7ad132013-06-09 18:02:55 +02004761
Christian Heimes200bb1b2013-06-14 15:14:29 +02004762 return Py_BuildValue("NNNN", ofile_env, ofile, odir_env, odir);
Christian Heimes6d7ad132013-06-09 18:02:55 +02004763
4764 error:
4765 Py_XDECREF(ofile_env);
4766 Py_XDECREF(ofile);
4767 Py_XDECREF(odir_env);
4768 Py_XDECREF(odir);
4769 return NULL;
4770}
4771
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004772static PyObject*
4773asn1obj2py(ASN1_OBJECT *obj)
4774{
4775 int nid;
4776 const char *ln, *sn;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004777
4778 nid = OBJ_obj2nid(obj);
4779 if (nid == NID_undef) {
4780 PyErr_Format(PyExc_ValueError, "Unknown object");
4781 return NULL;
4782 }
4783 sn = OBJ_nid2sn(nid);
4784 ln = OBJ_nid2ln(nid);
Serhiy Storchakae503ca52017-09-05 01:28:53 +03004785 return Py_BuildValue("issN", nid, sn, ln, _asn1obj2py(obj, 1));
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004786}
4787
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004788/*[clinic input]
4789_ssl.txt2obj
4790 txt: str
4791 name: bool = False
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004792
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004793Lookup NID, short name, long name and OID of an ASN1_OBJECT.
4794
4795By default objects are looked up by OID. With name=True short and
4796long name are also matched.
4797[clinic start generated code]*/
4798
4799static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004800_ssl_txt2obj_impl(PyObject *module, const char *txt, int name)
4801/*[clinic end generated code: output=c38e3991347079c1 input=1c1e7d0aa7c48602]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004802{
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004803 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004804 ASN1_OBJECT *obj;
4805
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004806 obj = OBJ_txt2obj(txt, name ? 0 : 1);
4807 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004808 PyErr_Format(PyExc_ValueError, "unknown object '%.100s'", txt);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004809 return NULL;
4810 }
4811 result = asn1obj2py(obj);
4812 ASN1_OBJECT_free(obj);
4813 return result;
4814}
4815
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004816/*[clinic input]
4817_ssl.nid2obj
4818 nid: int
4819 /
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004820
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004821Lookup NID, short name, long name and OID of an ASN1_OBJECT by NID.
4822[clinic start generated code]*/
4823
4824static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004825_ssl_nid2obj_impl(PyObject *module, int nid)
4826/*[clinic end generated code: output=4a98ab691cd4f84a input=51787a3bee7d8f98]*/
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004827{
4828 PyObject *result = NULL;
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004829 ASN1_OBJECT *obj;
4830
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004831 if (nid < NID_undef) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004832 PyErr_SetString(PyExc_ValueError, "NID must be positive.");
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004833 return NULL;
4834 }
4835 obj = OBJ_nid2obj(nid);
4836 if (obj == NULL) {
Christian Heimes5398e1a2013-11-22 16:20:53 +01004837 PyErr_Format(PyExc_ValueError, "unknown NID %i", nid);
Christian Heimesa6bc95a2013-11-17 19:59:14 +01004838 return NULL;
4839 }
4840 result = asn1obj2py(obj);
4841 ASN1_OBJECT_free(obj);
4842 return result;
4843}
4844
Christian Heimes46bebee2013-06-09 19:03:31 +02004845#ifdef _MSC_VER
Christian Heimes44109d72013-11-22 01:51:30 +01004846
4847static PyObject*
4848certEncodingType(DWORD encodingType)
4849{
4850 static PyObject *x509_asn = NULL;
4851 static PyObject *pkcs_7_asn = NULL;
4852
4853 if (x509_asn == NULL) {
4854 x509_asn = PyUnicode_InternFromString("x509_asn");
4855 if (x509_asn == NULL)
4856 return NULL;
4857 }
4858 if (pkcs_7_asn == NULL) {
4859 pkcs_7_asn = PyUnicode_InternFromString("pkcs_7_asn");
4860 if (pkcs_7_asn == NULL)
4861 return NULL;
4862 }
4863 switch(encodingType) {
4864 case X509_ASN_ENCODING:
4865 Py_INCREF(x509_asn);
4866 return x509_asn;
4867 case PKCS_7_ASN_ENCODING:
4868 Py_INCREF(pkcs_7_asn);
4869 return pkcs_7_asn;
4870 default:
4871 return PyLong_FromLong(encodingType);
4872 }
4873}
4874
4875static PyObject*
4876parseKeyUsage(PCCERT_CONTEXT pCertCtx, DWORD flags)
4877{
4878 CERT_ENHKEY_USAGE *usage;
4879 DWORD size, error, i;
4880 PyObject *retval;
4881
4882 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, NULL, &size)) {
4883 error = GetLastError();
4884 if (error == CRYPT_E_NOT_FOUND) {
4885 Py_RETURN_TRUE;
4886 }
4887 return PyErr_SetFromWindowsErr(error);
4888 }
4889
4890 usage = (CERT_ENHKEY_USAGE*)PyMem_Malloc(size);
4891 if (usage == NULL) {
4892 return PyErr_NoMemory();
4893 }
4894
4895 /* Now get the actual enhanced usage property */
4896 if (!CertGetEnhancedKeyUsage(pCertCtx, flags, usage, &size)) {
4897 PyMem_Free(usage);
4898 error = GetLastError();
4899 if (error == CRYPT_E_NOT_FOUND) {
4900 Py_RETURN_TRUE;
4901 }
4902 return PyErr_SetFromWindowsErr(error);
4903 }
4904 retval = PySet_New(NULL);
4905 if (retval == NULL) {
4906 goto error;
4907 }
4908 for (i = 0; i < usage->cUsageIdentifier; ++i) {
4909 if (usage->rgpszUsageIdentifier[i]) {
4910 PyObject *oid;
4911 int err;
4912 oid = PyUnicode_FromString(usage->rgpszUsageIdentifier[i]);
4913 if (oid == NULL) {
4914 Py_CLEAR(retval);
4915 goto error;
4916 }
4917 err = PySet_Add(retval, oid);
4918 Py_DECREF(oid);
4919 if (err == -1) {
4920 Py_CLEAR(retval);
4921 goto error;
4922 }
4923 }
4924 }
4925 error:
4926 PyMem_Free(usage);
4927 return retval;
4928}
4929
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03004930/*[clinic input]
4931_ssl.enum_certificates
4932 store_name: str
4933
4934Retrieve certificates from Windows' cert store.
4935
4936store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
4937more cert storages, too. The function returns a list of (bytes,
4938encoding_type, trust) tuples. The encoding_type flag can be interpreted
4939with X509_ASN_ENCODING or PKCS_7_ASN_ENCODING. The trust setting is either
4940a set of OIDs or the boolean True.
4941[clinic start generated code]*/
Bill Janssen40a0f662008-08-12 16:56:25 +00004942
Christian Heimes46bebee2013-06-09 19:03:31 +02004943static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03004944_ssl_enum_certificates_impl(PyObject *module, const char *store_name)
4945/*[clinic end generated code: output=5134dc8bb3a3c893 input=915f60d70461ea4e]*/
Christian Heimes46bebee2013-06-09 19:03:31 +02004946{
Christian Heimes46bebee2013-06-09 19:03:31 +02004947 HCERTSTORE hStore = NULL;
Christian Heimes44109d72013-11-22 01:51:30 +01004948 PCCERT_CONTEXT pCertCtx = NULL;
4949 PyObject *keyusage = NULL, *cert = NULL, *enc = NULL, *tup = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004950 PyObject *result = NULL;
Christian Heimes46bebee2013-06-09 19:03:31 +02004951
Christian Heimes44109d72013-11-22 01:51:30 +01004952 result = PyList_New(0);
4953 if (result == NULL) {
4954 return NULL;
4955 }
Benjamin Peterson94912722016-02-17 22:13:19 -08004956 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
4957 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
4958 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01004959 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02004960 Py_DECREF(result);
4961 return PyErr_SetFromWindowsErr(GetLastError());
4962 }
4963
Christian Heimes44109d72013-11-22 01:51:30 +01004964 while (pCertCtx = CertEnumCertificatesInStore(hStore, pCertCtx)) {
4965 cert = PyBytes_FromStringAndSize((const char*)pCertCtx->pbCertEncoded,
4966 pCertCtx->cbCertEncoded);
4967 if (!cert) {
4968 Py_CLEAR(result);
4969 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004970 }
Christian Heimes44109d72013-11-22 01:51:30 +01004971 if ((enc = certEncodingType(pCertCtx->dwCertEncodingType)) == NULL) {
4972 Py_CLEAR(result);
4973 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004974 }
Christian Heimes44109d72013-11-22 01:51:30 +01004975 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_PROP_ONLY_ENHKEY_USAGE_FLAG);
4976 if (keyusage == Py_True) {
4977 Py_DECREF(keyusage);
4978 keyusage = parseKeyUsage(pCertCtx, CERT_FIND_EXT_ONLY_ENHKEY_USAGE_FLAG);
Christian Heimes46bebee2013-06-09 19:03:31 +02004979 }
Christian Heimes44109d72013-11-22 01:51:30 +01004980 if (keyusage == NULL) {
4981 Py_CLEAR(result);
4982 break;
Christian Heimes46bebee2013-06-09 19:03:31 +02004983 }
Christian Heimes44109d72013-11-22 01:51:30 +01004984 if ((tup = PyTuple_New(3)) == NULL) {
4985 Py_CLEAR(result);
4986 break;
4987 }
4988 PyTuple_SET_ITEM(tup, 0, cert);
4989 cert = NULL;
4990 PyTuple_SET_ITEM(tup, 1, enc);
4991 enc = NULL;
4992 PyTuple_SET_ITEM(tup, 2, keyusage);
4993 keyusage = NULL;
4994 if (PyList_Append(result, tup) < 0) {
4995 Py_CLEAR(result);
4996 break;
4997 }
4998 Py_CLEAR(tup);
4999 }
5000 if (pCertCtx) {
5001 /* loop ended with an error, need to clean up context manually */
5002 CertFreeCertificateContext(pCertCtx);
Christian Heimes46bebee2013-06-09 19:03:31 +02005003 }
5004
5005 /* In error cases cert, enc and tup may not be NULL */
5006 Py_XDECREF(cert);
5007 Py_XDECREF(enc);
Christian Heimes44109d72013-11-22 01:51:30 +01005008 Py_XDECREF(keyusage);
Christian Heimes46bebee2013-06-09 19:03:31 +02005009 Py_XDECREF(tup);
5010
5011 if (!CertCloseStore(hStore, 0)) {
5012 /* This error case might shadow another exception.*/
Christian Heimes44109d72013-11-22 01:51:30 +01005013 Py_XDECREF(result);
5014 return PyErr_SetFromWindowsErr(GetLastError());
5015 }
5016 return result;
5017}
5018
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005019/*[clinic input]
5020_ssl.enum_crls
5021 store_name: str
5022
5023Retrieve CRLs from Windows' cert store.
5024
5025store_name may be one of 'CA', 'ROOT' or 'MY'. The system may provide
5026more cert storages, too. The function returns a list of (bytes,
5027encoding_type) tuples. The encoding_type flag can be interpreted with
5028X509_ASN_ENCODING or PKCS_7_ASN_ENCODING.
5029[clinic start generated code]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005030
5031static PyObject *
Serhiy Storchaka1a2b24f2016-07-07 17:35:15 +03005032_ssl_enum_crls_impl(PyObject *module, const char *store_name)
5033/*[clinic end generated code: output=bce467f60ccd03b6 input=a1f1d7629f1c5d3d]*/
Christian Heimes44109d72013-11-22 01:51:30 +01005034{
Christian Heimes44109d72013-11-22 01:51:30 +01005035 HCERTSTORE hStore = NULL;
5036 PCCRL_CONTEXT pCrlCtx = NULL;
5037 PyObject *crl = NULL, *enc = NULL, *tup = NULL;
5038 PyObject *result = NULL;
5039
Christian Heimes44109d72013-11-22 01:51:30 +01005040 result = PyList_New(0);
5041 if (result == NULL) {
5042 return NULL;
5043 }
Benjamin Peterson94912722016-02-17 22:13:19 -08005044 hStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, (HCRYPTPROV)NULL,
5045 CERT_STORE_READONLY_FLAG | CERT_SYSTEM_STORE_LOCAL_MACHINE,
5046 store_name);
Christian Heimes44109d72013-11-22 01:51:30 +01005047 if (hStore == NULL) {
Christian Heimes46bebee2013-06-09 19:03:31 +02005048 Py_DECREF(result);
5049 return PyErr_SetFromWindowsErr(GetLastError());
5050 }
Christian Heimes44109d72013-11-22 01:51:30 +01005051
5052 while (pCrlCtx = CertEnumCRLsInStore(hStore, pCrlCtx)) {
5053 crl = PyBytes_FromStringAndSize((const char*)pCrlCtx->pbCrlEncoded,
5054 pCrlCtx->cbCrlEncoded);
5055 if (!crl) {
5056 Py_CLEAR(result);
5057 break;
5058 }
5059 if ((enc = certEncodingType(pCrlCtx->dwCertEncodingType)) == NULL) {
5060 Py_CLEAR(result);
5061 break;
5062 }
5063 if ((tup = PyTuple_New(2)) == NULL) {
5064 Py_CLEAR(result);
5065 break;
5066 }
5067 PyTuple_SET_ITEM(tup, 0, crl);
5068 crl = NULL;
5069 PyTuple_SET_ITEM(tup, 1, enc);
5070 enc = NULL;
5071
5072 if (PyList_Append(result, tup) < 0) {
5073 Py_CLEAR(result);
5074 break;
5075 }
5076 Py_CLEAR(tup);
Christian Heimes46bebee2013-06-09 19:03:31 +02005077 }
Christian Heimes44109d72013-11-22 01:51:30 +01005078 if (pCrlCtx) {
5079 /* loop ended with an error, need to clean up context manually */
5080 CertFreeCRLContext(pCrlCtx);
5081 }
5082
5083 /* In error cases cert, enc and tup may not be NULL */
5084 Py_XDECREF(crl);
5085 Py_XDECREF(enc);
5086 Py_XDECREF(tup);
5087
5088 if (!CertCloseStore(hStore, 0)) {
5089 /* This error case might shadow another exception.*/
5090 Py_XDECREF(result);
5091 return PyErr_SetFromWindowsErr(GetLastError());
5092 }
5093 return result;
Christian Heimes46bebee2013-06-09 19:03:31 +02005094}
Christian Heimes44109d72013-11-22 01:51:30 +01005095
5096#endif /* _MSC_VER */
Bill Janssen40a0f662008-08-12 16:56:25 +00005097
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005098/* List of functions exported by this module. */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005099static PyMethodDef PySSL_methods[] = {
Serhiy Storchaka4b7b82f2015-05-03 16:14:08 +03005100 _SSL__TEST_DECODE_CERT_METHODDEF
5101 _SSL_RAND_ADD_METHODDEF
5102 _SSL_RAND_BYTES_METHODDEF
5103 _SSL_RAND_PSEUDO_BYTES_METHODDEF
5104 _SSL_RAND_EGD_METHODDEF
5105 _SSL_RAND_STATUS_METHODDEF
5106 _SSL_GET_DEFAULT_VERIFY_PATHS_METHODDEF
5107 _SSL_ENUM_CERTIFICATES_METHODDEF
5108 _SSL_ENUM_CRLS_METHODDEF
5109 _SSL_TXT2OBJ_METHODDEF
5110 _SSL_NID2OBJ_METHODDEF
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005111 {NULL, NULL} /* Sentinel */
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005112};
5113
5114
Christian Heimes598894f2016-09-05 23:19:05 +02005115#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005116
5117/* an implementation of OpenSSL threading operations in terms
Christian Heimes598894f2016-09-05 23:19:05 +02005118 * of the Python C thread library
5119 * Only used up to 1.0.2. OpenSSL 1.1.0+ has its own locking code.
5120 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005121
5122static PyThread_type_lock *_ssl_locks = NULL;
5123
Christian Heimes4d98ca92013-08-19 17:36:29 +02005124#if OPENSSL_VERSION_NUMBER >= 0x10000000
5125/* use new CRYPTO_THREADID API. */
5126static void
5127_ssl_threadid_callback(CRYPTO_THREADID *id)
5128{
Serhiy Storchakaaefa7eb2017-03-23 15:48:39 +02005129 CRYPTO_THREADID_set_numeric(id, PyThread_get_thread_ident());
Christian Heimes4d98ca92013-08-19 17:36:29 +02005130}
5131#else
5132/* deprecated CRYPTO_set_id_callback() API. */
5133static unsigned long
5134_ssl_thread_id_function (void) {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005135 return PyThread_get_thread_ident();
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005136}
Christian Heimes4d98ca92013-08-19 17:36:29 +02005137#endif
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005138
Bill Janssen6e027db2007-11-15 22:23:56 +00005139static void _ssl_thread_locking_function
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005140 (int mode, int n, const char *file, int line) {
5141 /* this function is needed to perform locking on shared data
5142 structures. (Note that OpenSSL uses a number of global data
5143 structures that will be implicitly shared whenever multiple
5144 threads use OpenSSL.) Multi-threaded applications will
5145 crash at random if it is not set.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005146
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005147 locking_function() must be able to handle up to
5148 CRYPTO_num_locks() different mutex locks. It sets the n-th
5149 lock if mode & CRYPTO_LOCK, and releases it otherwise.
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005150
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005151 file and line are the file number of the function setting the
5152 lock. They can be useful for debugging.
5153 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005154
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005155 if ((_ssl_locks == NULL) ||
5156 (n < 0) || ((unsigned)n >= _ssl_locks_count))
5157 return;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005158
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005159 if (mode & CRYPTO_LOCK) {
5160 PyThread_acquire_lock(_ssl_locks[n], 1);
5161 } else {
5162 PyThread_release_lock(_ssl_locks[n]);
5163 }
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005164}
5165
5166static int _setup_ssl_threads(void) {
5167
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005168 unsigned int i;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005169
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005170 if (_ssl_locks == NULL) {
5171 _ssl_locks_count = CRYPTO_num_locks();
Christian Heimesf6365e32016-09-13 20:48:13 +02005172 _ssl_locks = PyMem_Calloc(_ssl_locks_count,
5173 sizeof(PyThread_type_lock));
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005174 if (_ssl_locks == NULL) {
5175 PyErr_NoMemory();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005176 return 0;
Serhiy Storchaka1a1ff292015-02-16 13:28:22 +02005177 }
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005178 for (i = 0; i < _ssl_locks_count; i++) {
5179 _ssl_locks[i] = PyThread_allocate_lock();
5180 if (_ssl_locks[i] == NULL) {
5181 unsigned int j;
5182 for (j = 0; j < i; j++) {
5183 PyThread_free_lock(_ssl_locks[j]);
5184 }
Victor Stinnerb6404912013-07-07 16:21:41 +02005185 PyMem_Free(_ssl_locks);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005186 return 0;
5187 }
5188 }
5189 CRYPTO_set_locking_callback(_ssl_thread_locking_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005190#if OPENSSL_VERSION_NUMBER >= 0x10000000
5191 CRYPTO_THREADID_set_callback(_ssl_threadid_callback);
5192#else
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005193 CRYPTO_set_id_callback(_ssl_thread_id_function);
Christian Heimes4d98ca92013-08-19 17:36:29 +02005194#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005195 }
5196 return 1;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005197}
5198
Antoine Pitroua6a4dc82017-09-07 18:56:24 +02005199#endif /* HAVE_OPENSSL_CRYPTO_LOCK for OpenSSL < 1.1.0 */
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005200
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005201PyDoc_STRVAR(module_doc,
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005202"Implementation module for SSL socket operations. See the socket module\n\
Martin v. Löwis14f8b4c2002-06-13 20:33:02 +00005203for documentation.");
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005204
Martin v. Löwis1a214512008-06-11 05:26:20 +00005205
5206static struct PyModuleDef _sslmodule = {
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005207 PyModuleDef_HEAD_INIT,
5208 "_ssl",
5209 module_doc,
5210 -1,
5211 PySSL_methods,
5212 NULL,
5213 NULL,
5214 NULL,
5215 NULL
Martin v. Löwis1a214512008-06-11 05:26:20 +00005216};
5217
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005218
5219static void
5220parse_openssl_version(unsigned long libver,
5221 unsigned int *major, unsigned int *minor,
5222 unsigned int *fix, unsigned int *patch,
5223 unsigned int *status)
5224{
5225 *status = libver & 0xF;
5226 libver >>= 4;
5227 *patch = libver & 0xFF;
5228 libver >>= 8;
5229 *fix = libver & 0xFF;
5230 libver >>= 8;
5231 *minor = libver & 0xFF;
5232 libver >>= 8;
5233 *major = libver & 0xFF;
5234}
5235
Mark Hammondfe51c6d2002-08-02 02:27:13 +00005236PyMODINIT_FUNC
Martin v. Löwis1a214512008-06-11 05:26:20 +00005237PyInit__ssl(void)
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005238{
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005239 PyObject *m, *d, *r, *bases;
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005240 unsigned long libver;
5241 unsigned int major, minor, fix, patch, status;
5242 PySocketModule_APIObject *socket_api;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005243 struct py_ssl_error_code *errcode;
5244 struct py_ssl_library_code *libcode;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005245
Antoine Pitrou152efa22010-05-16 18:19:27 +00005246 if (PyType_Ready(&PySSLContext_Type) < 0)
5247 return NULL;
5248 if (PyType_Ready(&PySSLSocket_Type) < 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005249 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005250 if (PyType_Ready(&PySSLMemoryBIO_Type) < 0)
5251 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005252 if (PyType_Ready(&PySSLSession_Type) < 0)
5253 return NULL;
5254
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005255
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005256 m = PyModule_Create(&_sslmodule);
5257 if (m == NULL)
5258 return NULL;
5259 d = PyModule_GetDict(m);
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005260
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005261 /* Load _socket module and its C API */
5262 socket_api = PySocketModule_ImportModuleAndAPI();
5263 if (!socket_api)
5264 return NULL;
5265 PySocketModule = *socket_api;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005266
Christian Heimesc941e622017-09-05 15:47:11 +02005267#ifndef OPENSSL_VERSION_1_1
5268 /* Load all algorithms and initialize cpuid */
5269 OPENSSL_add_all_algorithms_noconf();
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005270 /* Init OpenSSL */
5271 SSL_load_error_strings();
5272 SSL_library_init();
Christian Heimesc941e622017-09-05 15:47:11 +02005273#endif
5274
Christian Heimes598894f2016-09-05 23:19:05 +02005275#ifdef HAVE_OPENSSL_CRYPTO_LOCK
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005276 /* note that this will start threading if not already started */
5277 if (!_setup_ssl_threads()) {
5278 return NULL;
5279 }
Christian Heimes598894f2016-09-05 23:19:05 +02005280#elif OPENSSL_VERSION_1_1 && defined(OPENSSL_THREADS)
5281 /* OpenSSL 1.1.0 builtin thread support is enabled */
5282 _ssl_locks_count++;
Thomas Wouters1b7f8912007-09-19 03:06:30 +00005283#endif
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005284
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005285 /* Add symbols to module dict */
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005286 sslerror_type_slots[0].pfunc = PyExc_OSError;
5287 PySSLErrorObject = PyType_FromSpec(&sslerror_type_spec);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005288 if (PySSLErrorObject == NULL)
5289 return NULL;
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005290
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005291 /* ssl.CertificateError used to be a subclass of ValueError */
5292 bases = Py_BuildValue("OO", PySSLErrorObject, PyExc_ValueError);
5293 if (bases == NULL)
5294 return NULL;
5295 PySSLCertVerificationErrorObject = PyErr_NewExceptionWithDoc(
5296 "ssl.SSLCertVerificationError", SSLCertVerificationError_doc,
5297 bases, NULL);
5298 Py_DECREF(bases);
Antoine Pitrou41032a62011-10-27 23:56:55 +02005299 PySSLZeroReturnErrorObject = PyErr_NewExceptionWithDoc(
5300 "ssl.SSLZeroReturnError", SSLZeroReturnError_doc,
5301 PySSLErrorObject, NULL);
5302 PySSLWantReadErrorObject = PyErr_NewExceptionWithDoc(
5303 "ssl.SSLWantReadError", SSLWantReadError_doc,
5304 PySSLErrorObject, NULL);
5305 PySSLWantWriteErrorObject = PyErr_NewExceptionWithDoc(
5306 "ssl.SSLWantWriteError", SSLWantWriteError_doc,
5307 PySSLErrorObject, NULL);
5308 PySSLSyscallErrorObject = PyErr_NewExceptionWithDoc(
5309 "ssl.SSLSyscallError", SSLSyscallError_doc,
5310 PySSLErrorObject, NULL);
5311 PySSLEOFErrorObject = PyErr_NewExceptionWithDoc(
5312 "ssl.SSLEOFError", SSLEOFError_doc,
5313 PySSLErrorObject, NULL);
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005314 if (PySSLCertVerificationErrorObject == NULL
5315 || PySSLZeroReturnErrorObject == NULL
Antoine Pitrou41032a62011-10-27 23:56:55 +02005316 || PySSLWantReadErrorObject == NULL
5317 || PySSLWantWriteErrorObject == NULL
5318 || PySSLSyscallErrorObject == NULL
5319 || PySSLEOFErrorObject == NULL)
5320 return NULL;
5321 if (PyDict_SetItemString(d, "SSLError", PySSLErrorObject) != 0
Christian Heimesb3ad0e52017-09-08 12:00:19 -07005322 || PyDict_SetItemString(d, "SSLCertVerificationError",
5323 PySSLCertVerificationErrorObject) != 0
Antoine Pitrou41032a62011-10-27 23:56:55 +02005324 || PyDict_SetItemString(d, "SSLZeroReturnError", PySSLZeroReturnErrorObject) != 0
5325 || PyDict_SetItemString(d, "SSLWantReadError", PySSLWantReadErrorObject) != 0
5326 || PyDict_SetItemString(d, "SSLWantWriteError", PySSLWantWriteErrorObject) != 0
5327 || PyDict_SetItemString(d, "SSLSyscallError", PySSLSyscallErrorObject) != 0
5328 || PyDict_SetItemString(d, "SSLEOFError", PySSLEOFErrorObject) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005329 return NULL;
Antoine Pitrou152efa22010-05-16 18:19:27 +00005330 if (PyDict_SetItemString(d, "_SSLContext",
5331 (PyObject *)&PySSLContext_Type) != 0)
5332 return NULL;
5333 if (PyDict_SetItemString(d, "_SSLSocket",
5334 (PyObject *)&PySSLSocket_Type) != 0)
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005335 return NULL;
Antoine Pitroub1fdf472014-10-05 20:41:53 +02005336 if (PyDict_SetItemString(d, "MemoryBIO",
5337 (PyObject *)&PySSLMemoryBIO_Type) != 0)
5338 return NULL;
Christian Heimes99a65702016-09-10 23:44:53 +02005339 if (PyDict_SetItemString(d, "SSLSession",
5340 (PyObject *)&PySSLSession_Type) != 0)
5341 return NULL;
5342
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005343 PyModule_AddIntConstant(m, "SSL_ERROR_ZERO_RETURN",
5344 PY_SSL_ERROR_ZERO_RETURN);
5345 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_READ",
5346 PY_SSL_ERROR_WANT_READ);
5347 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_WRITE",
5348 PY_SSL_ERROR_WANT_WRITE);
5349 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_X509_LOOKUP",
5350 PY_SSL_ERROR_WANT_X509_LOOKUP);
5351 PyModule_AddIntConstant(m, "SSL_ERROR_SYSCALL",
5352 PY_SSL_ERROR_SYSCALL);
5353 PyModule_AddIntConstant(m, "SSL_ERROR_SSL",
5354 PY_SSL_ERROR_SSL);
5355 PyModule_AddIntConstant(m, "SSL_ERROR_WANT_CONNECT",
5356 PY_SSL_ERROR_WANT_CONNECT);
5357 /* non ssl.h errorcodes */
5358 PyModule_AddIntConstant(m, "SSL_ERROR_EOF",
5359 PY_SSL_ERROR_EOF);
5360 PyModule_AddIntConstant(m, "SSL_ERROR_INVALID_ERROR_CODE",
5361 PY_SSL_ERROR_INVALID_ERROR_CODE);
5362 /* cert requirements */
5363 PyModule_AddIntConstant(m, "CERT_NONE",
5364 PY_SSL_CERT_NONE);
5365 PyModule_AddIntConstant(m, "CERT_OPTIONAL",
5366 PY_SSL_CERT_OPTIONAL);
5367 PyModule_AddIntConstant(m, "CERT_REQUIRED",
5368 PY_SSL_CERT_REQUIRED);
Christian Heimes22587792013-11-21 23:56:13 +01005369 /* CRL verification for verification_flags */
5370 PyModule_AddIntConstant(m, "VERIFY_DEFAULT",
5371 0);
5372 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_LEAF",
5373 X509_V_FLAG_CRL_CHECK);
5374 PyModule_AddIntConstant(m, "VERIFY_CRL_CHECK_CHAIN",
5375 X509_V_FLAG_CRL_CHECK|X509_V_FLAG_CRL_CHECK_ALL);
5376 PyModule_AddIntConstant(m, "VERIFY_X509_STRICT",
5377 X509_V_FLAG_X509_STRICT);
Benjamin Peterson990fcaa2015-03-04 22:49:41 -05005378#ifdef X509_V_FLAG_TRUSTED_FIRST
5379 PyModule_AddIntConstant(m, "VERIFY_X509_TRUSTED_FIRST",
5380 X509_V_FLAG_TRUSTED_FIRST);
5381#endif
Martin v. Löwis6af3e2d2002-04-20 07:47:40 +00005382
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005383 /* Alert Descriptions from ssl.h */
5384 /* note RESERVED constants no longer intended for use have been removed */
5385 /* http://www.iana.org/assignments/tls-parameters/tls-parameters.xml#tls-parameters-6 */
5386
5387#define ADD_AD_CONSTANT(s) \
5388 PyModule_AddIntConstant(m, "ALERT_DESCRIPTION_"#s, \
5389 SSL_AD_##s)
5390
5391 ADD_AD_CONSTANT(CLOSE_NOTIFY);
5392 ADD_AD_CONSTANT(UNEXPECTED_MESSAGE);
5393 ADD_AD_CONSTANT(BAD_RECORD_MAC);
5394 ADD_AD_CONSTANT(RECORD_OVERFLOW);
5395 ADD_AD_CONSTANT(DECOMPRESSION_FAILURE);
5396 ADD_AD_CONSTANT(HANDSHAKE_FAILURE);
5397 ADD_AD_CONSTANT(BAD_CERTIFICATE);
5398 ADD_AD_CONSTANT(UNSUPPORTED_CERTIFICATE);
5399 ADD_AD_CONSTANT(CERTIFICATE_REVOKED);
5400 ADD_AD_CONSTANT(CERTIFICATE_EXPIRED);
5401 ADD_AD_CONSTANT(CERTIFICATE_UNKNOWN);
5402 ADD_AD_CONSTANT(ILLEGAL_PARAMETER);
5403 ADD_AD_CONSTANT(UNKNOWN_CA);
5404 ADD_AD_CONSTANT(ACCESS_DENIED);
5405 ADD_AD_CONSTANT(DECODE_ERROR);
5406 ADD_AD_CONSTANT(DECRYPT_ERROR);
5407 ADD_AD_CONSTANT(PROTOCOL_VERSION);
5408 ADD_AD_CONSTANT(INSUFFICIENT_SECURITY);
5409 ADD_AD_CONSTANT(INTERNAL_ERROR);
5410 ADD_AD_CONSTANT(USER_CANCELLED);
5411 ADD_AD_CONSTANT(NO_RENEGOTIATION);
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005412 /* Not all constants are in old OpenSSL versions */
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005413#ifdef SSL_AD_UNSUPPORTED_EXTENSION
5414 ADD_AD_CONSTANT(UNSUPPORTED_EXTENSION);
5415#endif
5416#ifdef SSL_AD_CERTIFICATE_UNOBTAINABLE
5417 ADD_AD_CONSTANT(CERTIFICATE_UNOBTAINABLE);
5418#endif
5419#ifdef SSL_AD_UNRECOGNIZED_NAME
5420 ADD_AD_CONSTANT(UNRECOGNIZED_NAME);
5421#endif
Antoine Pitrou58ddc9d2013-01-05 21:20:29 +01005422#ifdef SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE
5423 ADD_AD_CONSTANT(BAD_CERTIFICATE_STATUS_RESPONSE);
5424#endif
5425#ifdef SSL_AD_BAD_CERTIFICATE_HASH_VALUE
5426 ADD_AD_CONSTANT(BAD_CERTIFICATE_HASH_VALUE);
5427#endif
5428#ifdef SSL_AD_UNKNOWN_PSK_IDENTITY
5429 ADD_AD_CONSTANT(UNKNOWN_PSK_IDENTITY);
5430#endif
5431
5432#undef ADD_AD_CONSTANT
5433
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005434 /* protocol versions */
Victor Stinner3de49192011-05-09 00:42:58 +02005435#ifndef OPENSSL_NO_SSL2
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005436 PyModule_AddIntConstant(m, "PROTOCOL_SSLv2",
5437 PY_SSL_VERSION_SSL2);
Victor Stinner3de49192011-05-09 00:42:58 +02005438#endif
Benjamin Petersone32467c2014-12-05 21:59:35 -05005439#ifndef OPENSSL_NO_SSL3
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005440 PyModule_AddIntConstant(m, "PROTOCOL_SSLv3",
5441 PY_SSL_VERSION_SSL3);
Benjamin Petersone32467c2014-12-05 21:59:35 -05005442#endif
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005443 PyModule_AddIntConstant(m, "PROTOCOL_SSLv23",
Christian Heimes598894f2016-09-05 23:19:05 +02005444 PY_SSL_VERSION_TLS);
5445 PyModule_AddIntConstant(m, "PROTOCOL_TLS",
5446 PY_SSL_VERSION_TLS);
Christian Heimes5fe668c2016-09-12 00:01:11 +02005447 PyModule_AddIntConstant(m, "PROTOCOL_TLS_CLIENT",
5448 PY_SSL_VERSION_TLS_CLIENT);
5449 PyModule_AddIntConstant(m, "PROTOCOL_TLS_SERVER",
5450 PY_SSL_VERSION_TLS_SERVER);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005451 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1",
5452 PY_SSL_VERSION_TLS1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005453#if HAVE_TLSv1_2
5454 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_1",
5455 PY_SSL_VERSION_TLS1_1);
5456 PyModule_AddIntConstant(m, "PROTOCOL_TLSv1_2",
5457 PY_SSL_VERSION_TLS1_2);
5458#endif
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005459
Antoine Pitroub5218772010-05-21 09:56:06 +00005460 /* protocol options */
Antoine Pitrou3f366312012-01-27 09:50:45 +01005461 PyModule_AddIntConstant(m, "OP_ALL",
5462 SSL_OP_ALL & ~SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
Antoine Pitroub5218772010-05-21 09:56:06 +00005463 PyModule_AddIntConstant(m, "OP_NO_SSLv2", SSL_OP_NO_SSLv2);
5464 PyModule_AddIntConstant(m, "OP_NO_SSLv3", SSL_OP_NO_SSLv3);
5465 PyModule_AddIntConstant(m, "OP_NO_TLSv1", SSL_OP_NO_TLSv1);
Antoine Pitrou2463e5f2013-03-28 22:24:43 +01005466#if HAVE_TLSv1_2
5467 PyModule_AddIntConstant(m, "OP_NO_TLSv1_1", SSL_OP_NO_TLSv1_1);
5468 PyModule_AddIntConstant(m, "OP_NO_TLSv1_2", SSL_OP_NO_TLSv1_2);
5469#endif
Christian Heimescb5b68a2017-09-07 18:07:00 -07005470#ifdef SSL_OP_NO_TLSv1_3
5471 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", SSL_OP_NO_TLSv1_3);
5472#else
5473 PyModule_AddIntConstant(m, "OP_NO_TLSv1_3", 0);
5474#endif
Antoine Pitrou6db49442011-12-19 13:27:11 +01005475 PyModule_AddIntConstant(m, "OP_CIPHER_SERVER_PREFERENCE",
5476 SSL_OP_CIPHER_SERVER_PREFERENCE);
Antoine Pitrou0e576f12011-12-22 10:03:38 +01005477 PyModule_AddIntConstant(m, "OP_SINGLE_DH_USE", SSL_OP_SINGLE_DH_USE);
Christian Heimes99a65702016-09-10 23:44:53 +02005478 PyModule_AddIntConstant(m, "OP_NO_TICKET", SSL_OP_NO_TICKET);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005479#ifdef SSL_OP_SINGLE_ECDH_USE
Antoine Pitrou923df6f2011-12-19 17:16:51 +01005480 PyModule_AddIntConstant(m, "OP_SINGLE_ECDH_USE", SSL_OP_SINGLE_ECDH_USE);
Antoine Pitroue9fccb32012-02-17 11:53:10 +01005481#endif
Antoine Pitrou8abdb8a2011-12-20 10:13:40 +01005482#ifdef SSL_OP_NO_COMPRESSION
5483 PyModule_AddIntConstant(m, "OP_NO_COMPRESSION",
5484 SSL_OP_NO_COMPRESSION);
5485#endif
Antoine Pitroub5218772010-05-21 09:56:06 +00005486
Antoine Pitrou912fbff2013-03-30 16:29:32 +01005487#if HAVE_SNI
Antoine Pitroud5323212010-10-22 18:19:07 +00005488 r = Py_True;
5489#else
5490 r = Py_False;
5491#endif
5492 Py_INCREF(r);
5493 PyModule_AddObject(m, "HAS_SNI", r);
5494
Antoine Pitroud6494802011-07-21 01:11:30 +02005495 r = Py_True;
Antoine Pitroud6494802011-07-21 01:11:30 +02005496 Py_INCREF(r);
5497 PyModule_AddObject(m, "HAS_TLS_UNIQUE", r);
5498
Antoine Pitrou501da612011-12-21 09:27:41 +01005499#ifdef OPENSSL_NO_ECDH
5500 r = Py_False;
5501#else
5502 r = Py_True;
5503#endif
5504 Py_INCREF(r);
5505 PyModule_AddObject(m, "HAS_ECDH", r);
5506
Melvyn Sopacuab2d096b2017-09-04 23:35:15 +02005507#if defined(OPENSSL_NPN_NEGOTIATED) && !defined(OPENSSL_NO_NEXTPROTONEG)
Antoine Pitroud5d17eb2012-03-22 00:23:03 +01005508 r = Py_True;
5509#else
5510 r = Py_False;
5511#endif
5512 Py_INCREF(r);
5513 PyModule_AddObject(m, "HAS_NPN", r);
5514
Benjamin Petersoncca27322015-01-23 16:35:37 -05005515#ifdef HAVE_ALPN
5516 r = Py_True;
5517#else
5518 r = Py_False;
5519#endif
5520 Py_INCREF(r);
5521 PyModule_AddObject(m, "HAS_ALPN", r);
5522
Christian Heimescb5b68a2017-09-07 18:07:00 -07005523#if defined(TLS1_3_VERSION) && !defined(OPENSSL_NO_TLS1_3)
5524 r = Py_True;
5525#else
5526 r = Py_False;
5527#endif
5528 Py_INCREF(r);
5529 PyModule_AddObject(m, "HAS_TLSv1_3", r);
5530
Antoine Pitrou3b36fb12012-06-22 21:11:52 +02005531 /* Mappings for error codes */
5532 err_codes_to_names = PyDict_New();
5533 err_names_to_codes = PyDict_New();
5534 if (err_codes_to_names == NULL || err_names_to_codes == NULL)
5535 return NULL;
5536 errcode = error_codes;
5537 while (errcode->mnemonic != NULL) {
5538 PyObject *mnemo, *key;
5539 mnemo = PyUnicode_FromString(errcode->mnemonic);
5540 key = Py_BuildValue("ii", errcode->library, errcode->reason);
5541 if (mnemo == NULL || key == NULL)
5542 return NULL;
5543 if (PyDict_SetItem(err_codes_to_names, key, mnemo))
5544 return NULL;
5545 if (PyDict_SetItem(err_names_to_codes, mnemo, key))
5546 return NULL;
5547 Py_DECREF(key);
5548 Py_DECREF(mnemo);
5549 errcode++;
5550 }
5551 if (PyModule_AddObject(m, "err_codes_to_names", err_codes_to_names))
5552 return NULL;
5553 if (PyModule_AddObject(m, "err_names_to_codes", err_names_to_codes))
5554 return NULL;
5555
5556 lib_codes_to_names = PyDict_New();
5557 if (lib_codes_to_names == NULL)
5558 return NULL;
5559 libcode = library_codes;
5560 while (libcode->library != NULL) {
5561 PyObject *mnemo, *key;
5562 key = PyLong_FromLong(libcode->code);
5563 mnemo = PyUnicode_FromString(libcode->library);
5564 if (key == NULL || mnemo == NULL)
5565 return NULL;
5566 if (PyDict_SetItem(lib_codes_to_names, key, mnemo))
5567 return NULL;
5568 Py_DECREF(key);
5569 Py_DECREF(mnemo);
5570 libcode++;
5571 }
5572 if (PyModule_AddObject(m, "lib_codes_to_names", lib_codes_to_names))
5573 return NULL;
Victor Stinner4569cd52013-06-23 14:58:43 +02005574
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005575 /* OpenSSL version */
5576 /* SSLeay() gives us the version of the library linked against,
5577 which could be different from the headers version.
5578 */
5579 libver = SSLeay();
5580 r = PyLong_FromUnsignedLong(libver);
5581 if (r == NULL)
5582 return NULL;
5583 if (PyModule_AddObject(m, "OPENSSL_VERSION_NUMBER", r))
5584 return NULL;
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005585 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005586 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5587 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION_INFO", r))
5588 return NULL;
5589 r = PyUnicode_FromString(SSLeay_version(SSLEAY_VERSION));
5590 if (r == NULL || PyModule_AddObject(m, "OPENSSL_VERSION", r))
5591 return NULL;
Antoine Pitrou04f6a322010-04-05 21:40:07 +00005592
Antoine Pitroub9ac25d2011-07-08 18:47:06 +02005593 libver = OPENSSL_VERSION_NUMBER;
5594 parse_openssl_version(libver, &major, &minor, &fix, &patch, &status);
5595 r = Py_BuildValue("IIIII", major, minor, fix, patch, status);
5596 if (r == NULL || PyModule_AddObject(m, "_OPENSSL_API_VERSION", r))
5597 return NULL;
5598
Antoine Pitroucbb82eb2010-05-05 15:57:33 +00005599 return m;
Marc-André Lemburga5d2b4c2002-02-16 18:23:30 +00005600}